>Any socket programmers out there?
>A (simple) question, C++ code:
>
>1. create a socket
>   int const sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); 

Tsk, check the return value.

>2. bind to it
>   unsigned int const port = 1234;
>   unsigned long const listenaddr = INADDR_ANY;
>   sockaddr_in listensock = { AF_INET, htons(listenport), { htonl(listenaddr)
> } };

INADDR_ANY is already in network order so you shouldn't put it through
htonl although as it's all 0's it won't do any harm. Also you are
assuming an Internet address is a long = 4 bytes. This happens to be
true for IPv4 but you really should do a memcpy(&listensock.sin_addr,
&blah, sizeof(struct in_addr));

>   if (bind(sockfd, &listensock, sizeof(listensock)) != -1)

Stylistically you should test for < 0 rather than overconstraining
the test.

>   ...
>
>3. listen for incoming connection
>   if (listen(sockfd, 1) != -1)
>   ...

Ditto.

Listen actually sets the backlog queue despite what the name suggests. 5
is a usual value.

>4. accept connection
>   sockaddr_in clientsock;
>   socklen_t csl = sizeof(clientsock);
>   int const peerfd = ::accept(sockfd, reinterpret_cast<sockaddr*>(&clientsoc
>k), &csl); 
>   if (peerfd != -1)
>   ... talk to the connection ...

Ditto.

>5. close connection
>   close(peerfd);
>   close(sockfd);
>
>The problem:
>
>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.
>
>But, if I wait 2 minutes or so, run the program again,
>the whole process works fine.
>
>Me thinks that the two close() calls are not enough to
>free up the port (1234), but the kernel eventual times out
>the connection and resets the port .... any ideas?

Yes, the socket is in the twice maximum segment lifetime state,
if memory serves me. This wait is to ensure that any old packets
are no longer around to confuse a new connection. You should do a
setsockopt(... SO_REUSEADDR, ...) to allow the address to be reused
(violating the IP rules), or you should make sure your server shuts down
the socket gracefully when interrupted.
--
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