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


我有代码允许我确定iPhone上的WiFi连接的MAC地址和IP地址,但我无法弄清楚如何获得连接的子网掩码和路由器地址。任何人都能指出我在正确的方向吗?


6905
2018-01-07 20:54


起源

现在我正在看ICMP(路由器请求)或ICMP(回应请求,1跳,看谁回复)。我不认为我的路由器响应路由器请求ICMP请求;第二种方法是traceroute如何工作(我相信)。另一种选择是DHCP API(在Iphone上找不到)或发送DHCP数据包以获取信息(因为在我的情况下总会有DHCP,路由器也总是DHCP服务器)。 - Bill
仅供参考 - iPhone应用程序旨在控制DLink Home NAT路由器上的安全/访问策略(Web界面使用起来很痛苦);我只是想避免让用户输入路由器的地址。他们将不得不提供密码,如果我在这里找不到好的解决方案那么没什么大不了的。 - Bill
@bvanderw - 您是否可以发布指向您的代码或文档的链接以确定WiFi连接的MAC地址?我无法追踪它。 - Ciaran


答案:


您可以通过致电获取该信息 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地址的格式。它不坏,只是乏味和丑陋。玩的开心!


13
2018-01-09 01:07



ifa-> ifa_dstaddr是广播地址,而不是路由器地址。 - Bill
@Bill:修正我的回答,请重新考虑你的downvote。 - benzado
你需要导入ifaddrs.h - Allen Zeng


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);

3
2017-09-30 06:41