How to check if port is available
Is there an API function on Linux (kernel 2.6.20) which can be used to check if a given TCP/IP port is used - bound and/or connected ?
Is bind()
开发者_如何学C the only solution (binding to the given port using a socket with the SO_REUSEADDR
option, and then closing it) ?
Hmm,
According to strace -o trace.out netstat -at
netstat does this by looking at
/proc/net/tcp
and
/proc/net/tcp6
The used ports are in hex in the second field of the entries in that file.
You can get the state of the connection by looking at the 4th field, for example 0A is LISTEN and 01 is ESTABLISHED.
The holy portable BSD socket API won't allow you to know whether the port is in use before you try to allocate it. Don't try to outsmart the API. I know how tempting it is, I've been in that situation before. But any superficially smart way of doing this (by e.g. the proc filesystem) is prone to subtle errors, compatibility problems in the future, race conditions and so forth.
Grab the source of the netstat
command and see how it sees. However, you will always have a race. Also, SO_REUSEADDR
won't let you use a port someone else is actively using, of course, just one in close-wait.
精彩评论