I am attempting to bind a socket to a port below:
if( bind(socket_desc,(struct sockaddr *) &server, sizeof(server)) < 0)
{
perror("bind failed. Error");
return 1;
}
puts("bind done");
But it gives:
$ ./serve
Socket created
bind failed. Error: Address already in use
Why does this error occur?
You have a process that is already using that port.
netstat -tulpn
will enable one to find the process ID of that is using a particular port.Everyone is correct. However, if you're also busy testing your code your own application might still "own" the socket if it starts and stops relatively quickly. Try SO_REUSEADDR as a socket option:
I was also facing same problem. But I resolved it :)
Make Sure that both the programs for ClientSide and ServerSide are on DIFFERENT PROJECTS in your IDE, in my case it is NetBeans. Then assuming you're using localhost, I recommend you to implement both the programs as two different projects. Thank you !
As mentioned above the port is in use already. This could be due to several reasons
close_wait
state when your program is waiting for the other end to close the program.refer (https://unix.stackexchange.com/questions/10106/orphaned-connections-in-close-wait-state).time_wait
state. you can wait or use socket optionSO_REUSEADDR
as mentioned in another post.Do
netstat -a | grep <portno>
to check the port state.The error usually means that the port you are trying to open is being already used by another application try using netstat to see which ports are open and then use an available port.
Also check if you are binding to the right ip address (I am assuming it would be localhost)
Address already in use
means that theport
you are trying to allocate for your current execution is already occupied/allocated to some other process.So if you encounter this error, just see which application/process is using the port.
In linux try using
netstat -tulpn
. This command will list down a process list with all running processes.Check if an application is using your port. If that application or process is another important one then you might want to use another port which is not used by any process/application.
Anyway you can stop the process which uses your port and let your application take it.
If you are in linux environment try,
netstat -tulpn
to display the processeskill <pid>
This will terminate the processIf you are using windows,
netstat -a -o -n
to check for the port usagestaskkill /F /PID <pid>
to kill that process