iOS獲取路由器地址類似於192.168.1.1
阿新 • • 發佈:2019-01-31
最近做的專案需要獲取路由器地址,查了很多資料以下方法終於成功了。
需要引用的標頭檔案
#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>
具體實現
原始碼下載 https://code.csdn.net/u010990519/ios_routeip/tree/master- (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 char *s=getdefaultgateway(x); NSString *ip=[NSString stringWithFormat:@"%d.%d.%d.%d",s[0],s[1],s[2],s[3]]; NSLog(@"路由器地址-----%@",ip); return ip; }