iOS获取路由器地址

来源:互联网 发布:佐拉算法提及奇异博士 编辑:程序博客网 时间:2024/05/22 00:19

找了好多资料,终于找到可以用的了。

#include <sys/socket.h>  #import <netinet/in.h>  #import <netinet6/in6.h>  #import <arpa/inet.h>  #import <ifaddrs.h>  #include <netdb.h>  #import <SystemConfiguration/SCNetworkReachability.h>   #import "getgateway.h"  #import <arpa/inet.h> 

- (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)          /*/           int i=255;           while((i--)>0)           //*/          {              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                      //ifa->ifa_dstaddr is the broadcast address, which explains the "255's"                      //                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_dstaddr)->sin_addr)];                                            address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];                                            //routerIP----192.168.1.255 广播地址                      NSLog(@"broadcast address--%@",[NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_dstaddr)->sin_addr)]);                      //--192.168.1.106 本机地址                      NSLog(@"local device ip--%@",[NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)]);                      //--255.255.255.0 子网掩码地址                      NSLog(@"netmask--%@",[NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_netmask)->sin_addr)]);                      //--en0 端口地址                      NSLog(@"interface--%@",[NSString stringWithUTF8String:temp_addr->ifa_name]);                                        }                                }                            temp_addr = temp_addr->ifa_next;          }      }            // Free memory      freeifaddrs(interfaces);            in_addr_t i =inet_addr([address cStringUsingEncoding:NSUTF8StringEncoding]);      in_addr_t* x =&i;                  unsigned charchar *s=getdefaultgateway(x);      NSString *ip=[NSString stringWithFormat:@"%d.%d.%d.%d",s[0],s[1],s[2],s[3]];            NSLog(@"路由器地址-----%@",ip);      return ip;  } 
源码下载 https://code.csdn.net/u010990519/ios_routeip/tree/master

1 0