0

I get a "bind: Address already in use" error. Is there any way to find which socket is bound? When I find it, how to I unlink it?

Doug Fulford
  • 49
  • 11

1 Answers1

1

A socket is binded to a process. You just need to find that process id using:

netstat -nap

The -p flag will include the process id but you have to be root

tcp 0 0 0.0.0.0:8080 0.0.0.0:* LISTEN 11152/lighttpd

In this example port 8080 is assigned to lighttpd, process id 11152

The command to list files opened by processes (lsof) will give similar information

Once you found the process id, you can simply kill it by issuing:

kill [pid]

Sainti
  • 11
  • 2
  • Doesn't this imply I need to know the port number? I'm sure I'm asking too much, but is there a way to find which port is bound when you get "bind: Address already in use"? – Doug Fulford Mar 08 '16 at 18:07
  • When you run a process and you get "Address Already in use" is because that process is trying to bind a specific port. For example a Webserver would by default try to bind port 80 (except you modify that, normally by editing a configuration file) Give me more details about what process you are running (are you coding something?) and I can help you to understand which port may be trying to bind() – Sainti Mar 09 '16 at 18:29
  • If you run a program through strace you will see every syscall that the process do, including the bind() syscall. Example: `strace ./myprogram` you will get a huge output and something like: `bind(3, {sa_family=AF_INET, sin_port=htons(8080), sin_addr=inet_addr("0.0.0.0")}, 16) = 0` – Sainti Mar 09 '16 at 18:33
  • Our system, which we develop and maintain, has many executables running using shared memory and socket interfaces. The error crops up about every two weeks (fortunately only in the development environment). I can fix it using kill -9 -1, but I'd like to see what socket is the offender and perhaps develop a permanent fix. I like your strace idea. I'll give that a try. – Doug Fulford Mar 10 '16 at 19:41
  • Maybe what's happening is that two processes, sharing a range of ports, checks which is the next available port at the same time and then try to bind it (which causes one to generate the error). These multi-process concurrency problem can be easily fixed with synchronization. Also a dirty quick fix may be loop until you are able to bind port++. Anyway, keeping strace output may be a lot of data but you'll definitely know what happened and when. Good luck hunting – Sainti Mar 12 '16 at 01:12