博客> 获取本地的ip地址
获取本地的ip地址
2017-12-11 23:55 评论:0 阅读:210 wanghiccup
iOS开发

以下给出了开发中获取本地ip地址的示例

///获取本地ip地址,返回字符串形式

  • (NSString )getLocalIPAddress { NSString address = @"error"; struct ifaddrs interfaces = NULL; struct ifaddrs temp_addr = NULL; int success = 0; int netPriority=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_flags&IFF_UP)) { temp_addr = temp_addr->ifa_next; continue; } if(temp_addr->ifa_addr->sa_family == AF_INET) { // Check if interface is en0 which is the wifi connection on the iPhone // lo0 //本地ip, 127.0.0.1 netPriority=0 // pdp_ip0 //WWAN地址,即3G ip, netPriority=1 // en0 //局域网ip, 192.168.1.23 netPriority=2 // bridge0 //桥接、热点ip,172.20.10.1 netPriority=3 // ppp0 //vpn开启 netPriority=4 //temp_addr->ifa_flags== if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"ppp0"]) { // Get NSString from C String if(netPriority<4 xss=removed>ifa_addr)->sin_addr)]; netPriority=4; } } else if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"bridge0"]) { // Get NSString from C String if(netPriority<3 xss=removed>ifa_addr)->sin_addr)]; netPriority=3; } } else if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) { // Get NSString from C String if(netPriority<2 xss=removed>ifa_addr)->sin_addr)]; netPriority=2; } } else if ([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"pdp_ip0"]){ if(netPriority<1 xss=removed>ifa_addr)->sin_addr)]; netPriority=1; } }

        }
         temp_addr = temp_addr->ifa_next;
    }

    } // Free memory freeifaddrs(interfaces); return address;

}

收藏
0
sina weixin mail 回到顶部