Objective-C:如何获取路由器地址?

Dan*_*iel 7 iphone router objective-c ip-address

我试着以这种方式获取路由器地址.

- (NSString *) routerIp {

  NSString *address = @"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 //ifa_addr
          address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_dstaddr)->sin_addr)];
        }
      }

      temp_addr = temp_addr->ifa_next;
    }
  }

  // Free memory
  freeifaddrs(interfaces);

  return address;
}
Run Code Online (Sandbox Code Playgroud)

路由器地址总是看起来像xxx.xxx.255.255但它应该看起来像xxx.xxx.0.1或者这样......

有没有办法获得有效地址?

谢谢你的帮助!

mik*_*ike 10

我一直在寻找一种方法来获取默认网关的IP地址.我将专注于此 - 我不需要获取默认路由器的MAC地址,因此这只能部分回答OP的问题.

我不喜欢解析netstat输出的想法.此外,您无法根据计算机上的接口所具有的IP地址获取默认路由.与您的相同范围内的任何IP地址都可以是默认网关 - 唯一的规则是您的IP和默认网关都必须属于同一子网.

我想要确保的另一件事是获取默认网关的IP地址,即使我的本地接口有多个分配了IP地址(例如,我已连接到Wifi和有线以太网)时间,两个接口都已启动,其上有IP地址).对于我的应用程序,默认路由通过哪个接口设置无关紧要(可以是en0,en1,ppp0或其他任何东西).

我认为获得该信息的最佳方式(也是大多数类似于Apple的方法)是使用系统配置框架 - 此线程中上面帖子中的链接指向了我的方向,但是并没有真正详细说明如何使用它,我没有发现它上面的Apple文档非常有用(至少考虑到我的技能水平).

请注意我在Objective-C方面不是很有经验 - 我正在编写一个我自己需要的应用程序(我找不到),对于那个应用程序我只需要默认的IP地址网关.

所以 - 这就是我在我的应用程序中所做的事情,它似乎工作正常(加上比我到目前为止找到的大多数其他解决方案更短更简单:

- (NSString *)defaultRouter {

    SCDynamicStoreRef ds = SCDynamicStoreCreate(kCFAllocatorDefault, CFSTR("myapp"), NULL, NULL);
    CFDictionaryRef dr = SCDynamicStoreCopyValue(ds, CFSTR("State:/Network/Global/IPv4"));
    CFStringRef router = CFDictionaryGetValue(dr, CFSTR("Router"));
    NSString *routerString = [NSString stringWithString:(__bridge NSString *)router];
    CFRelease(dr);
    CFRelease(ds);

    return routerString;
}
Run Code Online (Sandbox Code Playgroud)

请注意,在我的应用程序中,上面是一个更大的方法的一部分(我实际上没有一个defaultRouter:方法).另外,为了简洁起见,我省略了一些检查(比如[routerString length]等).

希望有人发现这很有用.也请随时修复我上面代码中可能出现的任何错误 - 我还是新手!

PS.当我检查'scutil'的输出时,我知道要查找什么,它使用系统配置框架本身:

MacBook:~$ scutil 
> show State:/Network/Global/IPv4
<dictionary> {
  PrimaryInterface : en1
  PrimaryService : <service_id>
  Router : <ipv4_address>
}
> show State:/Network/Global/IPv6
<dictionary> {
  PrimaryInterface : en1
  PrimaryService : <service_id>
  Router : <ipv6_address>
}
Run Code Online (Sandbox Code Playgroud)

  • iOS上没有`SCDynamicStoreCreate`和`SCDynamicStoreCopyValue`.这只适用于Mac. (10认同)