11

我有代码可以让我确定 iPhone 上 WiFi 连接的 MAC 地址和 IP 地址,但我不知道如何获取连接的子网掩码和路由器地址。谁能在这里指出我正确的方向?

4

2 回答 2

13

您可以通过调用getifaddrs获取该信息。(我在我的一个应用程序中使用这个函数来计算 iPhone 的 IP 地址。)

struct ifaddrs *ifa = NULL, *ifList;
getifaddrs(&ifList); // should check for errors
for (ifa = ifList; ifa != NULL; ifa = ifa->ifa_next) {
   ifa->ifa_addr // interface address
   ifa->ifa_netmask // subnet mask
   ifa->ifa_dstaddr // broadcast address, NOT router address
}
freeifaddrs(ifList); // clean up after yourself

这将为您提供子网掩码;对于路由器地址,请参阅此问题

这都是老式 UNIX 网络的东西,你必须选择哪个接口是 WiFi 连接(其他的东西,比如环回接口也会在那里)。然后,您可能必须使用诸如 inet_ntoa() 之类的函数,具体取决于您要读取 IP 地址的格式。这不是坏事,只是乏味和丑陋。玩得开心!

于 2010-01-09T01:07:46.063 回答
3
NSString *address = @"error";
NSString *netmask = @"error";
struct ifaddrs *interfaces = NULL;
struct ifaddrs *temp_addr = NULL;
int success = 0;

// retrieve the current interfaces - returns 0 on success
success = getifaddrs(&interfaces);
if (success == 0)
{
    // Loop through linked list of interfaces
    temp_addr = interfaces;
    while(temp_addr != NULL)
    {
        if(temp_addr->ifa_addr->sa_family == AF_INET)
        {
            // Check if interface is en0 which is the wifi connection on the iPhone

            if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"])
            {
                // Get NSString from C String
                address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                netmask = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_netmask)->sin_addr)];
            }
        }

        temp_addr = temp_addr->ifa_next;
    }
}

// Free memory
freeifaddrs(interfaces);
NSLog(@"address %@", address);
NSLog(@"netmask %@", netmask);
于 2014-09-30T06:41:36.407 回答