iPhone WiFi子网掩码和路由器地址

时间:2010-01-07 20:54:37

标签: iphone wifi

我有代码可以让我确定iPhone上的WiFi连接的MAC地址和IP地址,但我无法弄清楚如何获得连接的子网掩码和路由器地址。谁能指出我在这方面的正确方向?

2 个答案:

答案 0 :(得分: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

这可以获得子网掩码; the router address, see this question

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

答案 1 :(得分: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);