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 ?
Linux上是否有一个API函数(kernel 2.6.20),它可以用来检查给定的TCP/IP端口是否被使用-绑定和/或连接?
Is bind()
the only solution (binding to the given port using a socket with the SO_REUSEADDR
option, and then closing it) ?
bind()是惟一的解决方案(使用带有SO_REUSEADDR选项的套接字绑定到给定的端口,然后关闭它)吗?
3 个解决方案
#1
2
Hmm,
嗯,
According to strace -o trace.out netstat -at
根据strace -o跟踪。了netstat——
netstat does this by looking at
netstat通过查看
/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.
您可以通过查看第4个字段来获得连接的状态,例如,0A是LISTEN,而01是建立的。
#2
1
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.
神圣的便携式BSD套接字API不允许您在尝试分配端口之前知道端口是否正在使用。不要试图超越API。我知道这很诱人,我以前也遇到过这种情况。但是,任何表面上很聪明的方法(例如,通过proc文件系统)都容易出现细微的错误、未来的兼容性问题、竞争条件等等。
#3
0
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.
获取netstat命令的源代码并查看它是如何查看的。然而,你总是会有一场比赛。此外,SO_REUSEADDR不会允许您使用其他人正在积极使用的端口,当然,只允许在近距离等待时使用一个端口。
#1
2
Hmm,
嗯,
According to strace -o trace.out netstat -at
根据strace -o跟踪。了netstat——
netstat does this by looking at
netstat通过查看
/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.
您可以通过查看第4个字段来获得连接的状态,例如,0A是LISTEN,而01是建立的。
#2
1
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.
神圣的便携式BSD套接字API不允许您在尝试分配端口之前知道端口是否正在使用。不要试图超越API。我知道这很诱人,我以前也遇到过这种情况。但是,任何表面上很聪明的方法(例如,通过proc文件系统)都容易出现细微的错误、未来的兼容性问题、竞争条件等等。
#3
0
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.
获取netstat命令的源代码并查看它是如何查看的。然而,你总是会有一场比赛。此外,SO_REUSEADDR不会允许您使用其他人正在积极使用的端口,当然,只允许在近距离等待时使用一个端口。