获取本机IP地址

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了获取本机IP地址相关的知识,希望对你有一定的参考价值。

这里有两种方法:

 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地址的主要内容,如果未能解决你的问题,请参考以下文章

详谈再论JAVA获取本机IP地址

如何在Node.js中获取本机本地IP地址

java 怎么获取本机ip地址

Delphi 7中快速获取本机IP地址

java如何查询本机ip地址和mac地址

Delphi7中快速得到本机IP地址