[ale] connect()
Chris Fowler
ChrisF at computone.com
Wed Aug 1 22:50:52 EDT 2001
Stephan,
He is some test code that works like a champ!
I'm sure I need the option to reuse but this code works on Linux. Now it will need to be tested on our embedded platform. Thanks for the help.
I also verified I could read data from the remote machine. I pulled this code direclty from Beej's guide. I needed a fast solution to test the concept.
Thanks,
Chris
----- test.c ----
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#define THISPORT 3001
#define DEST_IP "160.77.63.112"
#define DEST_PORT 23
void
main(void)
{
       int sockfd;
       int status;
       struct sockaddr_in my_addr;
       struct sockaddr_in dest_addr;
       sockfd = socket(AF_INET, SOCK_STREAM, 0);
       my_addr.sin_family = AF_INET;
       my_addr.sin_port = htons(THISPORT);
       my_addr.sin_addr.s_addr = inet_addr("160.77.63.112");
       memset(&(my_addr.sin_zero), '\0', 8);
       status = bind(sockfd, (struct sockaddr *) &my_addr, sizeof(struct sockaddr));
       if (status == -1)
       {
               perror("bind()");
               exit(1);
       }
       printf("Bound to %d\n", THISPORT);
       fflush(stdout);
      Â
       dest_addr.sin_family = AF_INET;
       dest_addr.sin_port = htons(DEST_PORT);
       dest_addr.sin_addr.s_addr = inet_addr("160.77.63.112");
       memset(&(dest_addr.sin_zero), '\0', 8);
       status = connect(sockfd, (struct sockaddr *)&dest_addr, sizeof(struct sockaddr));
       if (status == -1)
       {
               perror("connect()");
               exit(1);
       }
       sleep(100);Â
      Â
}
Â
-----Original Message-----
From: Stephan Uphoff
To: Chris Fowler
Cc: ups at tree.com
Sent: 8/1/01 8:24 PM
Subject: Re: [ale] connect()
--SNIP--
>
> I do think the above should work. Do you see any problems?
>
> Thanks,
> Chris
>
Only if you do the socket,bind,connect stuff in a loop
binding to the same local port and to the same remote port.
In this case you are in deep trouble.
Even after a close of the socket the mapping
<localPort,localIP <=> remotePort,remoteIP> might
hang around for a certain time.
Your socket is closed but the kernel is still busy with the
protocol to close the connection
(see TCP protocol state machine closing states)
First Problem:
---------------
This will prevent you from binding to it.
( Especially on Solaris)
setsockopt() with SO_REUSEADDR should fix the problem.
Second Problem:
---------------
Even after the bind the old mapping <lp,li,rp,ri> is still there.
Now you get an error on the connect()
(EADDRNOTAVAIL)
If you try again and again you will eventually succeed ...
--------------------------
You are buying yourself a lot of trouble ....
This is also a way less traveled so you might just run into some
implementation bugs/features in the TCP stacks.
good luck
       Stephan
More information about the Ale
mailing list