List of all hosts on LAN network

我只是一个虾纸丫 提交于 2020-02-02 02:44:50

问题


How can I get all the IP addresses and associated host names in a LAN?


回答1:


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 or arp commands.



来源:https://stackoverflow.com/questions/4023222/list-of-all-hosts-on-lan-network

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!