我的目标是列出本地网络上所有设备的名称和 ip。
在 iPhone 上列出本地网络上的所有计算机名称,类似于这篇文章,但没有得到答复。
我研究过 Apples Bonjour,但认为这不是我需要的。它不会显示网络上的所有设备。
我也尝试了下面的代码,但我得到了奇怪的输出(下)。
int sock;
struct ifconf ifconf;
struct ifreq ifreq[30];
int interfaces;
int i;
// Create a socket or return an error.
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0)
diep("socket");
// Point ifconf's ifc_buf to our array of interface ifreqs.
ifconf.ifc_buf = (char *) ifreq;
// Set ifconf's ifc_len to the length of our array of interface ifreqs.
ifconf.ifc_len = sizeof ifreq;
// Populate ifconf.ifc_buf (ifreq) with a list of interface names and addresses.
if (ioctl(sock, SIOCGIFCONF, &ifconf) == -1)
diep("ioctl");
// Divide the length of the interface list by the size of each entry.
// This gives us the number of interfaces on the system.
interfaces = ifconf.ifc_len / sizeof(ifreq[0]);
// Print a heading that includes the total # of interfaces.
printf("IF(%d)\tIP\n", interfaces);
// Loop through the array of interfaces, printing each one's name and IP.
for (i = 0; i < interfaces; i++) {
char ip[INET_ADDRSTRLEN];
struct sockaddr_in *address = (struct sockaddr_in *) &ifreq[i].ifr_addr;
// Convert the binary IP address into a readable string.
if (!inet_ntop(AF_INET, &address->sin_addr, ip, sizeof(ip)))
diep("inet_ntop");
printf("FOUND: %s\t%s\n", ifreq[i].ifr_name, ip);
}
close(sock);
这是输出,我真的无法理解。
FOUND: lo0 24.3.0.0
FOUND: 28.30.0.0
FOUND: 0.0.0.0
FOUND: 0.0.0.0
FOUND: 0.0.0.1
FOUND: ip0 112.100.112.95
FOUND: pdp_ip1 255.7.0.0
FOUND: 20.18.4.0
FOUND: ip2 0.0.0.0
FOUND: ap1\256\372\272J\221\253 0.0.0.0
FOUND: 105.112.50.0
FOUND: 254.74.145.171
FOUND: ip2 0.0.0.0
FOUND: ip2 101.110.49.142
FOUND: awdl0 6.5.6.0
FOUND: \273Y\311 28.30.0.0
我想看到这样的输出:
My-Mac 192.168.0.21
My-iPad 192.168.0.22
Mum's iPhone 192.168.0.23
Objective-C 或 C++ 中的解决方案会很有用。谢谢。