Bind failed: Address already in use - c

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?

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:
What exactly does SO_REUSEADDR do?
This socket option tells the kernel that even if this port is busy (in
the TIME_WAIT state), go ahead and reuse it anyway. If it is busy,
but with another state, you will still get an address already in use
error. It is useful if your server has been shut down, and then
restarted right away while sockets are still active on its port. You
should be aware that if any unexpected data comes in, it may confuse
your server, but while this is possible, it is not likely.
It has been pointed out that "A socket is a 5 tuple (proto, local
addr, local port, remote addr, remote port). SO_REUSEADDR just says
that you can reuse local addresses. The 5 tuple still must be
unique!" by Michael Hunter (mphunter#qnx.com). This is true, and this
is why it is very unlikely that unexpected data will ever be seen by
your server. The danger is that such a 5 tuple is still floating
around on the net, and while it is bouncing around, a new connection
from the same client, on the same system, happens to get the same
remote port. This is explained by Richard Stevens in ``2.7 Please
explain the TIME_WAIT state.''.

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.

Address already in use means that the port you are trying to allocate for your current execution is already occupied/allocated to some other process.
If you are a developer and if you are working on an application which require lots of testing, you might have an instance of your same application running in background (may be you forgot to stop it properly)
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,
Use netstat -tulpn to display the processes
kill <pid> This will terminate the process
If you are using windows,
Use netstat -a -o -n to check for the port usages
Use taskkill /F /PID <pid> to kill that process

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)

if address is already in use can you just want to kill whoso ever process is using the port, you can use
lsof -ti:PortNumberGoesHere | xargs kill -9
source and inspiration this.
PS: Could not use netstat because it not installed already.

As mentioned above the port is in use already.
This could be due to several reasons
some other application is already using it.
The port is in 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).
The program might be in time_wait state. you can wait or use socket option SO_REUSEADDR as mentioned in another post.
Do netstat -a | grep <portno> to check the port state.

It also happens when you have not give enough permissions(read and write) to your sock file!
Just add expected permission to your sock contained folder and your sock file:
chmod ug+rw /path/to/your/
chmod ug+rw /path/to/your/file.sock
Then have fun!

I was also facing that problem, but I resolved it.
Make sure that both the programs for client-side and server-side are on different projects in your IDE, in my case NetBeans. Then assuming you're using localhost, I recommend you to implement both the programs as two different projects.

To terminate all node processes:
killall -9 node

First of check which port are listening,
netstat -tlpn
then select available port to conect,
sudo netstat -tlpn | grep ':port'
Fix it into also to your server and clients interfaces. Go Barrier tab -> change settings, -> port value type -> save/ok
Check both clients and server have similar port values
Then Reload.
Now it should be ok.

Check for running process pid:
pidof <process-name>
Kill processes:
sudo kill -9 process_id_1 process_id_2 process_id_3

Related

How do I remove a CLOSE_WAIT socket connection?

I have write a simple program using socket in C that create a connect between X86 running windows and ARM running embedded linux(consist of only Busybox and libc).Suddenly this small program could not connect the windows and linux,then I running "netsta -a" found 3 socket's state is CLOSE_WAIT and PID is NULL.So I try to modify “net.ipv4.tcp_keepalive_×” but because busybox has only the basic functions that I could not using /etc/rc.d/init.d/network restart makes the modify take effect.
So I want to know:
how to make the change take effect with Busybox?
how I using socket can avoid the CLOSE_WAIT problem?
How do I remove a CLOSE_WAIT connection that doesn't belong to any tasks?
As we've established that the process is still running, it does belong to a task. We've also established that the netstat output was a complete red herring.
All you have to do is close the socket. You probably forget to close it after you got the connection failure. It's just a common or garden file/socket descriptor leak.
You might want to check out: https://github.com/rghose/kill-close-wait-connections
What this script does is send out the ACK which the connection was waiting for.
This is what worked for me.

How do I not destroy an UDP port when binding a socket?

I am using GCDAsyncUdpSocket to open an UDP socket and then I bind it to a port. The class is just a wrapper around the usual POSIX socket calls like socket, bind, etc.
SCENARIO 1:
MyMacBook: start process A
MyMacBook: open UDP port 23141 => SUCCESS
SomeComputer: send an UDP packet to MyMacBook, port 23141
MyMacBook: the standard OSX firewall asks me if i want to allow incoming network connections, and I agree.
MyMacBook: ignore packet, don't read it. (or at least, i don't see a log message that tells me that i got a packet. either my code is broken, or the CocoaAsyncSocket code is broken, or the OS didn't report the packet to my program.)
MyMacBook: kill process A
MyMacBook: start process A
MyMacBook: open UDP port 23141 => FAIL: Error Domain=NSPOSIXErrorDomain Code=48 "Address already in use" UserInfo=0x100407f30 {NSLocalizedDescription=Address already in use, NSLocalizedFailureReason=Error in bind() function
Why???
netstat -n |grep 2314
udp4 626 0 *.23146 *.*
udp4 1251 0 *.23141 *.*
^^this is how a broken UDP port looks like on the shell. If I ever want to use that port number again, I seem to have to restart my machine :-(
And no, I don't have old processes hanging around that block the port. I checked with ps aux and with lsof -i | grep UDP.
SCENARIO 2:
MyMacBook: start process A
MyMacBook: open UDP port 23143 => SUCCESS
MyMacBook: kill process A
MyMacBook: start process A
MyMacBook: open UDP port 23143 => SUCCESS
MyMacBook: kill process A
MyMacBook: start process A
MyMacBook: open UDP port 23143 => SUCCESS
MyMacBook: kill process A
...
If the port is never used, the system doesn't care if I dont close it nicely. This is how it should be.
My question:
What is wrong here? Of course, in a perfect world, a program wouldn't crash, and sockets are all closed with the POSIX close function. In an imperfect world, I just type Cmd-. in XCode to kill the app I am developing, and close isn't called.
When I am trying to bind my socket to an UDP port, what I am really trying to say to the OS is this: "Please OSX 10.8.5, bind my socket to port 23141. If some other program has it opened currently and is listening, then you may tell me that the port is in use, but if no running program cares about this port, then let me bind it to port 23141!!" Is this an OSX bug? Is it new? Is it a documented known bug, or a so-called "feature"?
This seems to be a bug in OSX.
Related posts:
https://superuser.com/questions/504750/kill-udp-port-that-has-no-process
https://apple.stackexchange.com/questions/71300/how-can-i-unbind-a-udp-port-that-has-no-entry-in-lsof
(#Barmar: thanks for finding these articles)
1) I have noted, that if a UDP port is broken (it is bound, but not bound to a particular process), then you have to restart the computer to use this port again. Logging off, and logging in again doesn't work.
2) I found out, that there is no problem if you disable the OSX Firewall. This means that the problem is a bug in the standard OSX firewall. However, a broken port doen't get unbroken if you disable the firewall, you still have to restart your computer to unbreak it. But: if the firewall is off, no port becomes broken.
There is something we can learn from part 2: the OSX firewall is not a simple packet filter. It seems to hack the socket commands on a kernel level.
Maybe someone wants to write a bug report and send it to Apple... (sounds like a joke, doesn't it?)

netstat process name information programmatically or from procfs

I have a requirement to get all the port numbers that a particular program is listening on. The program itself is a generic server type program (lets call it myserverd). myserverd can be configured to listen on any TCP port, and there can be more than one instance of myserverd running on a machine.
I can get the ports being used by running instances of myserverd by grep'ing for myserverd in netstat -natp (p option to display the program name in netstat)
I am trying to see this information in procfs (/proc/net/tcp) but it doesn't show any process names... my question is: is there a good/reliable API that can be used to programmatically figure out what processes are listening to a particular port (or get all process names bound to all listening ports)... ?
You can find the source code for netstat here: https://github.com/mirror/busybox/blob/master/networking/netstat.c. If you look through it, you should see how netstat gets the pids/names of bound processes.
Specifically, look at the prg_cache_load() function, as netstat just polls /proc/net/tcp anyway.

Cannot assign requested address - possible causes?

I have a program that consists of a master server and distributed slave servers. The slave servers send status updates to the server, and if the server hasn't heard from a specific slave in a fixed period, it marks the slave as down. This is happening consistently.
From inspecting logs, I have found that the slave is only able to send one status update to the server, and then is never able to send another update, always failing on the call to connect() "Cannot assign requested address (99).
Oddly enough, the slave is able to send several other updates to the server, and all of the connections are happening on the same port. It seems that the most common cause of this failure is that connections are left open, but I'm having trouble finding anything left open. Are there other possible explanations?
To clarify, here's how I'm connecting:
struct sockaddr *sa; // parameter
size_t sa_size; //parameter
int i = 1;
int stream;
stream = socket(AF_INET,SOCK_STREAM,0);
setsockopt(stream,SOL_SOCKET,SO_REUSEADDR,&i,sizeof(i));
bindresvport(stream,NULL);
connect(stream,sa,sa_size);
This code is in a function to obtain a connection to another server, and a failure on any of those 4 calls causes the function to fail.
It turns out that the problem really was that the address was busy - the busyness was caused by some other problems in how we are handling network communications. Your inputs have helped me figure this out. Thank you.
EDIT: to be specific, the problems in handling our network communications were that these status updates would be constantly re-sent if the first failed. It was only a matter of time until we had every distributed slave trying to send its status update at the same time, which was over-saturating our network.
Maybe SO_REUSEADDR helps here?
http://www.unixguide.net/network/socketfaq/4.5.shtml
this is just a shot in the dark : when you call connect without a bind first, the system allocates your local port, and if you have multiple threads connecting and disconnecting it could possibly try to allocate a port already in use. the kernel source file inet_connection_sock.c hints at this condition. just as an experiment try doing a bind to a local port first, making sure each bind/connect uses a different local port number.
Okay, my problem wasn't the port, but the binding address. My server has an internal address (10.0.0.4) and an external address (52.175.223.XX). When I tried connecting with:
$sock = #stream_socket_server('tcp://52.175.223.XX:123', $errNo, $errStr, STREAM_SERVER_BIND|STREAM_SERVER_LISTEN);
It failed because the local socket was 10.0.0.4 and not the external 52.175.223.XX. You can checkout the local available interfaces with sudo ifconfig.
sysctl -w net.ipv4.tcp_timestamps=1
sysctl -w net.ipv4.tcp_tw_recycle=1

How to prevent network ports being left open on program crash

I took Computer Networking last semester and did some C programming in linux (using gcc) for my projects. One extremely tedious thing I kept running into was if my program crashed or stalled (which I then would have to hit Ctrl+C to kill it), the network port would still be left open for a minute or so. So if I wanted to immediately run the program again, I would have to first go into the header file, change the port, remake the program, and then finally run it. Obviously, this gets very tedious very fast.
Is there any way to configure it where the port is immediately released as soon as the process is killed? Either via some setting in linux, or in the makefile for my program, or even programmatically in C?
Edit: I'm referring to when writing a server and choosing a specific port to host the program.
Set the the option SO_REUSEADDR on the socket.
int yes = 1;
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
From Beej's Guide to Network Programming.
I bet it's about two minutes :)
As #Cogsy noted, the SO_REUSEADDR socket option is your friend.
Make yourself familiar with TCP states, it's TIME_WAIT state that causes you problems:
I assume the program you're writing is a server, so you need to use a known port. If that's the case, you should use the SO_REUSE_ADDR option on the socket as pointed out by Cogsy.
If on the other hand you're writing a client sw, then you should avoid choosing a particular port, allowing the system to hand you a random one.

Resources