We help IT Professionals succeed at work.

Check out our new AWS podcast with Certified Expert, Phil Phillips! Listen to "How to Execute a Seamless AWS Migration" on EE or on your favorite podcast platform. Listen Now

x

How to close a tcp-ip socket connection in a common way ?

onsight
onsight asked
on
Medium Priority
669 Views
Last Modified: 2010-04-21
Hi experts,
I'm programming a client server application with TCP/IP socket connection. Program runs successfully.
But when I shutdwon the server and try to restart it ,I sometimes can't build the socket for a while and I receive
an socket errror. After ~ 1 minute waiting - it works. I guess the problem is the socket closing. Can you
recommend a offical handshake procedure? Do you have some code snippets for the client and the server
side program how to close the socket officially.
What do you think. Am I on the right track?
Thanks in advance
Martin
Comment
Watch Question

Commented:
I think the best examples on using sockets is the ones in the
book "unix network programming" by Richard Stevens, you can find the source code at

http://www.cis.temple.edu/~ingargio/cis307/software/StevensBook/stevens-net/

(a tarred version is there in the same page)


under the directory net you can find tcpcli.c and tcpserv.c, you can find the code on how to program a simple client and server. If you have any question regarding the code you find there, please don't hesitate to ask.....


Commented:
To close the socket, just do a close(descriptor) on it before exiting. This is the proper way.
CERTIFIED EXPERT
Top Expert 2006
Commented:
Unlock this solution with a free trial preview.
(No credit card required)
Get Preview
Another way to avoid this issue is to set your sever to run under xinet.d.

This way you are allowing the kernal to handle the creation and destruction of the socket. You don't have to worry about coding it at all.

If you would like I can provide you with more information

Paul

Commented:
PaulS_III's comment will help if you don't need to maintain any state information (in memory) between invocations.  I once wrote a web servers in K-Shell using this inetd!

But otherwise, check out the "setsockopt" man page and look at enabling SO_REUSEADDR on the socket after you bind() it.
Unlock this solution with a free trial preview.
(No credit card required)
Get Preview
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a free trial preview!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.