tags:

views:

177

answers:

3

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() the only solution (binding to the given port using a socket with the SO_REUSEADDR option, and then closing it) ?

A: 

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.

bmargulies
A: 

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.

Benj
nice, especially using strace. Beside using that file, is there direct API call ?
CsTamas
No, it doesn't look as though there is unfortunately. The Berkley socket API is pretty concise really and non of them do what you're after. Some APIs (like Microsofts) have non-standard extensions which aren't available in just Berkley sockets but I don't think the Linux one does (for very good portability reasons).
Benj
A: 

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.

Thorsten79