Link to home
Start Free TrialLog in
Avatar of faster
faster

asked on

unable to create listening socket

SunOS:

I have a daemon program which opens a listening socket and accept requests.  The program is work fine.  Problem is that after the program terminates (the listening socket is closed and close() returns 0), if you run the daemon again, sometimes it will fail to create the socket (bind to the port), after several minutes it will be OK.

Any idea?
Avatar of rdelfino
rdelfino



Try using setsockopt() and setting SO_REUSEADDR

If bind fails after setting this option, the port is
in use by another process.

Example:

#define PORT 3333

struct sockaddr_in sAddr;
int s, opt;

s = socket(AF_INET, SOCK_STREAM, 0);
opt = 1;
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char*)&opt, sizeof(int));
memset(&sAddr, 0,sizeof(sAddr));

sAddr.sin_family = AF_INET;
sAddr.sin_port = htons(PORT);
sAddr.sin_addr.s_addr = inet_addr("111.111.111.111");

if (bind(s, (struct sockaddr*)&sAddr, sizeof(sAddr))  < 0)
{
  // the port is  in use by another process
}


I hope it helps

Reginaldo

Avatar of faster

ASKER

NO it does not work.  The port seems to be used by the died process until several minutes later.
Avatar of faster

ASKER

Sorry, my mistake.  It works.  Please re-submit your answer.

Could you please explain what causes this problem and why this setting can work?
Unless you use the REUSEADDR socket option, the port will be in use until it times out.  I think (may be wrong on this - didn't do any checking) that the socket has to remain open for a period of time as specified by the TCP protocol to allow and client connection to acknowlege closing the connection.  

What you must be careful of, however, is accidently binding again to the same socket.  This could cause a bad situation where multiple processes compete to read data from the socket.  This is generally a bad thing.
Avatar of faster

ASKER

under normal situation, there should not be such timeout.  There must be something speical and that what I am interested.
I have also encounter this problem.
I slove it by calling shutdown(2) first, then call close();
I have tryied it in my application, it works without problem.

ASKER CERTIFIED SOLUTION
Avatar of kannan042597
kannan042597

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of faster

ASKER

Sorry Kannan, since rdelfino answered the question first, the points should go to him.  If in the next several days he does not show up, I will accept your answer.



Oops;

I've made a mistake in the code I've sent.

Instead of:
sAddr.sin_addr.s_addr = inet_addr("111.111.111.111");

Try:
sAddr.sin_addr.s_addr = INADDR_ANY;

Reginaldo