Discussion:
Proper way to close a socket
(too old to reply)
Lorenzo Thurman
2007-08-19 04:18:57 UTC
Permalink
I'm playing around with socket programming and have found a few
tutorials in the 'net, but I have a question that they don't seem to answer:
What's the proper way to close a connection? I use close(fd), but if I
try to restart the server app, I get the error that the socket is in
use. netstat confirms the port is in TIME_WAIT and it eventually becomes
available again, but most server apps (apache, mysql, etc) can be
restarted without such a delay. How do I accomplish this?
TIA
Jerry McBride
2007-08-19 20:15:13 UTC
Permalink
Post by Lorenzo Thurman
I'm playing around with socket programming and have found a few
What's the proper way to close a connection? I use close(fd), but if I
try to restart the server app, I get the error that the socket is in
use. netstat confirms the port is in TIME_WAIT and it eventually becomes
available again, but most server apps (apache, mysql, etc) can be
restarted without such a delay. How do I accomplish this?
What language???


Under python, you can close and reuse the same socket almost immediately...


#!/usr/bin/python

try:
import socket
except ImportError:
print "Error imorting socket"
pass

# create an InterNET, STREAMing socket (aka TCP/IP)
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# allow quick restart and reuse of server socket
serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
--
Jerry McBride
Lorenzo Thurman
2007-08-19 23:43:15 UTC
Permalink
Post by Jerry McBride
Post by Lorenzo Thurman
I'm playing around with socket programming and have found a few
What's the proper way to close a connection? I use close(fd), but if I
try to restart the server app, I get the error that the socket is in
use. netstat confirms the port is in TIME_WAIT and it eventually becomes
available again, but most server apps (apache, mysql, etc) can be
restarted without such a delay. How do I accomplish this?
What language???
Under python, you can close and reuse the same socket almost immediately...
#!/usr/bin/python
import socket
print "Error imorting socket"
pass
# create an InterNET, STREAMing socket (aka TCP/IP)
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# allow quick restart and reuse of server socket
serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Sorry I wasn't clear, in C.

Lorenzo Thurman
2007-08-19 23:56:13 UTC
Permalink
Post by Lorenzo Thurman
I'm playing around with socket programming and have found a few
What's the proper way to close a connection? I use close(fd), but if I
try to restart the server app, I get the error that the socket is in
use. netstat confirms the port is in TIME_WAIT and it eventually becomes
available again, but most server apps (apache, mysql, etc) can be
restarted without such a delay. How do I accomplish this?
TIA
Ah, it looks like:
int shutdown(fd, how) is the way to go.
Loading...