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)?
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.
//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\);
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.