如何进行 netstat 以查看 C 中是否正在使用端口? | 珊瑚贝

How to do a netstat to see if a port is in use in C++?


在命令提示符下,我可以运行 netstat 来查看某台机器上是否已经在使用单个端口,如下所示:

1
netstat nap | grep <portnum>

我可以在 Linux 上调用 C 中的哪些函数来查看特定端口当前是否正在使用?我宁愿不对 netstat 本身进行系统调用。

  • stackoverflow.com/questions/1756107/…


如果你这样做:

1
strace netstat nap

您可以推断 netstat 正在做什么来获取该信息。

例如:

1
2
3
4
open directory: openat(AT_FDCWD,“/proc/2073/fd”, …) = 4)
get entries: getdents(4, /* 15 entries */, 32768)    = 360
read symbolic links: readlink(“/proc/2073/fd/4”,“socket:[48395]”, 29) = 14
that one was a socket connected on port 48395
  • 我没有看到 strace 是如何调用 C 函数的?
  • 这是特定于操作系统的东西,您将无法调用 C 函数。您将需要基本上使用一组特定于操作系统的库。 strace 命令为您提供 Linux 上的系统调用。这在 Windows 上不起作用,如果你想要结果,你将需要使用另一个分析器(例如 Solaris 上的桁架)。然而,以上是在 Linux 上探索的最佳方式。顺便说一句,perreal 说的是,如果你想复制 \\’netstat -nap\\’ 的行为,你需要使用系统调用 \\’openat\\’、\\’getdents\\’ 和 \\’readlink\\’。


来源:https://www.codenong.com/15079403/

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_8796.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?