How to free a port?

hi all,

Im using a tcp socket for communication. After all the communications I close the socket and bind another socket to the same port. But it shows bind error. I see it is due to the port no being used immediately. But i am closing the first socket before the binding the second one to the same port. Why is the port not set free? How can i do it (set the port free)?

Thank you

Without seeing your code I can't guess why it's still open, but something must have been left open somewhere. Remember that, if it's a server socket, you've already bound it and can just accept() new connections without reopening it.

Its a client socket.

length=sizeof(clientAddr);
socketFd=createSocket("tcp");

//setting the server address
clientAddr.sin\_family=AF_INET;
clientAddr.sin\_addr.s\_addr=INADDR_ANY;
port=port\+\(\(incrementor\+\+\)%50\);
clientAddr.sin_port=htons\(port\);
bindSocket\(socketFd,&clientAddr,length\);

//setting the server address
serverAddr.sin\_family=AF_INET;
serverAddr.sin\_addr.s\_addr=INADDR_ANY;
serverAddr.sin_port=htons\(31000\);

/*TCP Connection with slave*/
if\(\(connect\(socketFd,\(struct sockaddr*\)&serverAddr,sizeof\(serverAddr\)\)\)==-1\)\{
 printf\("Err in connect\\n"\);
 exit\(0\);
\}

//request to server
if\(send\(socketFd,command,strlen\(command\)\+1,0\)<0\)\{
	printf\("Err in Sending read request to server\\n"\);
\}
if\(bytesReceived=recv\(socketFd,reply,sizeof\(reply\),0\)<0\)\{
	printf\("Err in receiving reply from server\\n"\);
\}
shutdown\(socketFd,2\);

shutdown is insufficient, you must close() it after that.

Yeah i tried that too. Din work. Only then i switched to shutdown.

I don't suppose you forked anywhere, leaving a copy in a child process?

no im using multithreaded programming.

fork() isn't threading. That's why a child would get a copy at all.

Have you checked the return values for every command you do, including close(), etc? Maybe the FD number is getting corrupted somewhere which causes close to fail.

I am assuming you have the TIMED_WAIT problem. See this for more information

free a port in TIMED_WAIT state (Page 1) / Networking / UNIX Socket FAQ

@jim , @Corona688 - Thank you for the help. Setsockopt helped. I guess it was due to TIME_WAIT the port was held for some period.

1 Like