LAN网络上所有主机的列表
如何获取 LAN 中的所有 IP 地址和关联的主机名?
How can I get all the IP addresses and associated host names in a LAN?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
如何获取 LAN 中的所有 IP 地址和关联的主机名?
How can I get all the IP addresses and associated host names in a LAN?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(1)
要获取接口和 IP 地址的列表,请使用
getifaddrs()
。搜索具有
ifa_addr->sa_family == AF_INET
的接口IP 地址位于
sin_addr.s_addr
中。然后,您可以使用
gethostbyaddr()
查找该 IP 地址的 DNS 名称。更新:
有人向我指出,OP可能询问的是发现其他主机,而不是本地计算机上的接口地址。
没有可靠的方法来发现局域网上的其他计算机,但有一些技巧。
Ping 方法:使用 ping 实用程序(或等效程序)对本地广播地址执行 ping 操作,然后查看谁响应。可以通过如上所示列出接口来找到广播地址。我相信 ICMP 在 OSX 下不需要 root 访问权限。请注意,许多系统可能禁用了 ICMP ping 或设置了防火墙,因此您只能得到来自非隐形系统的响应。
ARP方法:检查系统ARP缓存以查看哪些IP地址最近处于活动状态。这只会显示最近几分钟内同一网段上有广播数据包的系统。
这两种方法都可以被防火墙、路由器甚至交换机阻止,因此“LAN”的确切边界可能非常窄。这两种方法都可以通过编程方式实现,但仅调用命令行
ping
或arp
命令可能更简单、更便携。To get the list of interfaces and IP addresses, use
getifaddrs()
.Search for interfaces with
ifa_addr->sa_family == AF_INET
The IP address is in
sin_addr.s_addr
.You can then use
gethostbyaddr()
to look up the DNS name for that IP address.Update:
It was pointed out to me that the OP was probably asking about discovering other hosts, rather than the addresses of interfaces on the local machine.
There is no reliable way to discover other machines on the local area network, but there are a couple of tricks.
Ping method: Use the ping utility (or a programatic equivalent) to ping the local broadcast address, then see who responds. The broadcast address can be found by listing the interfaces as shown above. I believe ICMP does not require root access under OSX. Note that many systems may have ICMP ping disabled or firewalled, so you will only get responses from the non-stealth ones.
ARP method: Check the system ARP cache to see what IP addresses have been recently active. This will only show systems which have broadcast packets on the same network segment in recent minutes.
Both methods can be blocked by firewalls, routers, and even switches, so the exact borders of the "LAN" can be pretty narrow. Both methods can be implemented programmatically, but it might be simpler and more portable to just call out to the command line
ping
orarp
commands.