On Tue, Jan 25, 2000 at 07:45:04AM +0000, Rick Welykochy wrote:
> Any socket programmers out there?
> A (simple) question, C++ code:
> 
> 1. create a socket
>    int const sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); 
> 
> 2. bind to it
>    unsigned int const port = 1234;
>    unsigned long const listenaddr = INADDR_ANY;
>    sockaddr_in listensock = { AF_INET, htons(listenport), { htonl(listenaddr) } };
>    if (bind(sockfd, &listensock, sizeof(listensock)) != -1)
>    ...
> 
> The above sequence works fine the first time the program is
> run. An immediate second invocation fails at step 2, i.e.
> cannot bind to 0.0.0.0:1234.

The OS will not allow you to use the same host/port combination (in this
case, 0.0.0.0:1234) twice within a short period (Thats not entirely correct,
but it's close enough :)  If you so a netstat during this period, which
is between about 1 and 4 minutes depending on the OS, you'll see a connection
in TIME_WAIT state on this port.

For full default, have a look at "TCP/IP Illustrated Volume 1" by W. Richard
Stevens, or do a websearch on "2msl", or possible time_wait.

Thankfully you can tell the OS to ignore it by putting the following between
1 and 2 above :

      setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on));

where "on" is defined above as :
int on = 1;

  Scott.
--
SLUG - Sydney Linux Users Group Mailing List - http://www.slug.org.au
To unsubscribe send email to [EMAIL PROTECTED] with
unsubscribe in the text

Reply via email to