arvind
arvind

Reputation: 127

error in binding port "Address already in use" TCP socket programming in unix

I've gone through many posts and forums and I'm new to socket programming. Major parts of my code are similar to BIND ERROR : Address already in use

but then i changed my code so that i include "setsockopt" function like so:

const char* port="5555";
int opt=1;
portno=atoi(port);
//parameters for server address
serv_addr.sin_family=AF_INET;
serv_addr.sin_port=htons(portno);
serv_addr.sin_addr.s_addr=INADDR_ANY;
//bind the socket to the address
setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,(const char *)&opt,sizeof(int));


 if(bind(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr))<0)
{close(sockfd);
error("error in binding port!");
}

But still i get the error. I have to close the terminal and restart it in order to use the port again. I want to use a hardcoded port (like i mentioned in the code above)

                                                            Thanks a lot in advance

Upvotes: 2

Views: 29331

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409482

A port number can only be used by one application at a time. That means you can not start the same program twice expecting both to bind to the same port.

The SO_REUSEADDR is for when the socket bound to an address has already been closed, the same address (ip-address/port pair) can be used again directly.

Upvotes: 2

Ed Heal
Ed Heal

Reputation: 60037

Check to see if the port is in use. Either telnet to that port or use netstat -a. It should be in use (as the error indicates) and kill the appropriate process. Perhaps using ps to find the process.

Upvotes: 3

Related Questions