码迷,mamicode.com
首页 > 其他好文 > 详细

获取本机IP地址

时间:2016-06-11 21:18:35      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:

这里有两种方法:

 1 //获取本机IP
 2 - (NSString *)localIPAddress
 3 {
 4     NSString *localIP = nil;
 5     struct ifaddrs *addrs;
 6     if (getifaddrs(&addrs)==0) {
 7         const struct ifaddrs *cursor = addrs;
 8         while (cursor != NULL) {
 9             if (cursor->ifa_addr->sa_family == AF_INET && (cursor->ifa_flags & IFF_LOOPBACK) == 0)
10             {
11                 {
12                     localIP = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)cursor->ifa_addr)->sin_addr)];
13                     break;
14                 }
15             }
16             cursor = cursor->ifa_next;
17         }
18         freeifaddrs(addrs);
19     }
20     return localIP;
21 }
 1 // 获取本机IP地址
 2 - (NSString *)getIPAddress
 3 {
 4     NSString *address = @"error";
 5     struct ifaddrs *interfaces = NULL;
 6     struct ifaddrs *temp_addr = NULL;
 7     int success = 0;
 8     
 9     // retrieve the current interfaces - returns 0 on success
10     success = getifaddrs(&interfaces);
11     if (success == 0) {
12         // Loop through linked list of interfaces
13         temp_addr = interfaces;
14         while (temp_addr != NULL) {
15             if( temp_addr->ifa_addr->sa_family == AF_INET) {
16                 // Check if interface is en0 which is the wifi connection on the iPhone
17                 if ([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
18                     // Get NSString from C String
19                     address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
20                 }
21             }
22             
23             temp_addr = temp_addr->ifa_next;
24         }
25     }
26     
27     // Free memory
28     freeifaddrs(interfaces);
29     
30     return address;
31 }

 

获取本机IP地址

标签:

原文地址:http://www.cnblogs.com/zhizunbao/p/5575877.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!