我有一些代码,让我来决定的MAC地址和iPhone上的Wi-Fi连接的IP地址,但我无法弄清楚如何获得用于连接的子网掩码和路由器地址。任何人都可以点我在这里向正确的方向?

有帮助吗?

解决方案

您可以通过调用的 getifaddrs 的。 (I使用此功能在矿井的一个应用程序来找出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连接(其他的东西,如Loopback接口将在那里了)。那么你可能取决于你想读的IP地址是什么格式使用像INET_NTOA功能()。这并不坏,只是乏味和丑陋。玩得开心!

其他提示

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);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top