我有代码允许我确定iPhone上的WiFi连接的MAC地址和IP地址,但我无法弄清楚如何获得连接的子网掩码和路由器地址。任何人都能指出我在正确的方向吗?
我有代码允许我确定iPhone上的WiFi连接的MAC地址和IP地址,但我无法弄清楚如何获得连接的子网掩码和路由器地址。任何人都能指出我在正确的方向吗?
您可以通过致电获取该信息 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地址的格式。它不坏,只是乏味和丑陋。玩的开心!
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);