iOS获取手机的IP地址

时间:2021-02-22 13:40:24

1.添加这五个库(在联网的情况下)

#import <sys/socket.h>
#import <sys/sockio.h>
#import <sys/ioctl.h>
#import <net/if.h>
#import <arpa/inet.h>

2.写一个方法

- (NSString *)getDeviceIPIpAddresses
{
int sockfd =socket(AF_INET,SOCK_DGRAM, 0);
// if (sockfd <</span> 0) return nil;
NSMutableArray *ips = [NSMutableArrayarray];
int BUFFERSIZE =4096;
structifconf ifc;
char buffer[BUFFERSIZE], *ptr, lastname[IFNAMSIZ], *cptr;
structifreq *ifr, ifrcopy;

ifc.ifc_len = BUFFERSIZE;
ifc.ifc_buf = buffer;

if (ioctl(sockfd,SIOCGIFCONF, &ifc) >= 0){
for (ptr = buffer; ptr < buffer + ifc.ifc_len; ){
ifr = (structifreq *)ptr;
int len =sizeof(structsockaddr);
if (ifr->ifr_addr.sa_len > len) {
len = ifr->ifr_addr.sa_len;
}
ptr += sizeof(ifr->ifr_name) + len;
if (ifr->ifr_addr.sa_family !=AF_INET) continue;

if ((cptr = (char *)strchr(ifr->ifr_name,':')) != NULL) *cptr =0;

if (strncmp(lastname, ifr->ifr_name,IFNAMSIZ) == 0)continue;

memcpy(lastname, ifr->ifr_name,IFNAMSIZ);

ifrcopy = *ifr;
ioctl(sockfd,SIOCGIFFLAGS, &ifrcopy);

if ((ifrcopy.ifr_flags &IFF_UP) == 0)continue;

NSString *ip = [NSString stringWithFormat:@"%s",inet_ntoa(((structsockaddr_in *)&ifr->ifr_addr)->sin_addr)];
[ips addObject:ip];
}
}
close(sockfd);

NSString *deviceIP =@"";
for (int i=0; i < ips.count; i++)
{
if (ips.count >0)
{
deviceIP = [NSStringstringWithFormat:@"%@",ips.lastObject];
}
}
NSLog(@"deviceIP========%@",deviceIP);
return deviceIP;
}

*上找到一种方法,能实时获取IP

#include <ifaddrs.h>
#include <arpa/inet.h>
#include <net/if.h>

#define IOS_CELLULAR @"pdp_ip0"
#define IOS_WIFI @"en0"
//#define IOS_VPN @"utun0"
#define IP_ADDR_IPv4 @"ipv4"
#define IP_ADDR_IPv6 @"ipv6"

- (NSString *)getIPAddress:(BOOL)preferIPv4
{
NSArray *searchArray = preferIPv4 ?
@[ /*IOS_VPN @"/" IP_ADDR_IPv4, IOS_VPN @"/" IP_ADDR_IPv6,*/ IOS_WIFI @"/" IP_ADDR_IPv4, IOS_WIFI @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6 ] :
@[ /*IOS_VPN @"/" IP_ADDR_IPv6, IOS_VPN @"/" IP_ADDR_IPv4,*/ IOS_WIFI @"/" IP_ADDR_IPv6, IOS_WIFI @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4 ] ;

NSDictionary *addresses = [self getIPAddresses];
NSLog(@"addresses: %@", addresses);

__block NSString *address;
[searchArray enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL *stop)
{
address = addresses[key];
if(address) *stop = YES;
} ];
return address ? address : @"0.0.0.0";
}

- (NSDictionary *)getIPAddresses
{
NSMutableDictionary *addresses = [NSMutableDictionary dictionaryWithCapacity:8];

// retrieve the current interfaces - returns 0 on success
struct ifaddrs *interfaces;
if(!getifaddrs(&interfaces)) {
// Loop through linked list of interfaces
struct ifaddrs *interface;
for(interface=interfaces; interface; interface=interface->ifa_next) {
if(!(interface->ifa_flags & IFF_UP) /* || (interface->ifa_flags & IFF_LOOPBACK) */ ) {
continue; // deeply nested code harder to read
}
const struct sockaddr_in *addr = (const struct sockaddr_in*)interface->ifa_addr;
char addrBuf[ MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) ];
if(addr && (addr->sin_family==AF_INET || addr->sin_family==AF_INET6)) {
NSString *name = [NSString stringWithUTF8String:interface->ifa_name];
NSString *type;
if(addr->sin_family == AF_INET) {
if(inet_ntop(AF_INET, &addr->sin_addr, addrBuf, INET_ADDRSTRLEN)) {
type = IP_ADDR_IPv4;
}
} else {
const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6*)interface->ifa_addr;
if(inet_ntop(AF_INET6, &addr6->sin6_addr, addrBuf, INET6_ADDRSTRLEN)) {
type = IP_ADDR_IPv6;
}
}
if(type) {
NSString *key = [NSString stringWithFormat:@"%@/%@", name, type];
addresses[key] = [NSString stringWithUTF8String:addrBuf];
}
}
}
// Free memory
freeifaddrs(interfaces);
}
return [addresses count] ? addresses : nil;
}

第三种方法

//获取公网IP非局域网IP
<span class="hljs-built_in" style="color: rgb(38, 139, 210); font-size: 12px;">直接访问此网址 NSString</span><span style="font-size: 12px; background-color: transparent;"> *url = </span><span class="hljs-string" style="color: rgb(42, 161, 152); font-size: 12px;">@"http://ip.taobao.com/service/getIpInfo.php?ip=myip"</span><span style="font-size: 12px; background-color: transparent;">;</span>
<span style="color: rgb(85, 85, 85); font-family: Menlo, Monaco, Consolas, "Helvetica Neue", Helvetica, "Courier New", 微软雅黑, monospace, Arial, sans-serif, 黑体; font-size: 14px; background-color: transparent;">网址返回的JSON数据段</span><pre class="hljs objectivec" name="code" style="white-space: pre-wrap; word-wrap: normal; padding: 9.5px; background: rgb(253, 246, 227); margin-top: 0px; margin-bottom: 20px; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; line-height: 20px; word-break: break-all; overflow: auto;"><code class="objectivec" style="padding: 0px; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; font-size: 12px; border: none; background-color: transparent;"><span style="color: rgb(85, 85, 85); font-family: Menlo, Monaco, Consolas, "Helvetica Neue", Helvetica, "Courier New", 微软雅黑, monospace, Arial, sans-serif, 黑体; font-size: 14px;">    {</span><span class="json_key" style="color: rgb(146, 39, 143); font-weight: bold; font-family: Menlo, Monaco, Consolas, "Helvetica Neue", Helvetica, "Courier New", 微软雅黑, monospace, Arial, sans-serif, 黑体; font-size: 14px;">"code"</span><span style="color: rgb(85, 85, 85); font-family: Menlo, Monaco, Consolas, "Helvetica Neue", Helvetica, "Courier New", 微软雅黑, monospace, Arial, sans-serif, 黑体; font-size: 14px;">:</span><span class="json_number" style="color: rgb(37, 170, 226); font-weight: bold; font-family: Menlo, Monaco, Consolas, "Helvetica Neue", Helvetica, "Courier New", 微软雅黑, monospace, Arial, sans-serif, 黑体; font-size: 14px;">0</span><span style="color: rgb(85, 85, 85); font-family: Menlo, Monaco, Consolas, "Helvetica Neue", Helvetica, "Courier New", 微软雅黑, monospace, Arial, sans-serif, 黑体; font-size: 14px;">,</span><br style="color: rgb(85, 85, 85); font-family: Menlo, Monaco, Consolas, "Helvetica Neue", Helvetica, "Courier New", 微软雅黑, monospace, Arial, sans-serif, 黑体; font-size: 14px;" /><span style="color: rgb(85, 85, 85); font-family: Menlo, Monaco, Consolas, "Helvetica Neue", Helvetica, "Courier New", 微软雅黑, monospace, Arial, sans-serif, 黑体; font-size: 14px;">    </span><span class="json_key" style="color: rgb(146, 39, 143); font-weight: bold; font-family: Menlo, Monaco, Consolas, "Helvetica Neue", Helvetica, "Courier New", 微软雅黑, monospace, Arial, sans-serif, 黑体; font-size: 14px;">"data"</span><span style="color: rgb(85, 85, 85); font-family: Menlo, Monaco, Consolas, "Helvetica Neue", Helvetica, "Courier New", 微软雅黑, monospace, Arial, sans-serif, 黑体; font-size: 14px;">:</span><span style="color: rgb(85, 85, 85); font-family: Menlo, Monaco, Consolas, "Helvetica Neue", Helvetica, "Courier New", 微软雅黑, monospace, Arial, sans-serif, 黑体; font-size: 14px;"><span class="fa fa-minus-square-o"></span>{        <span class="json_key" style="color: rgb(146, 39, 143); font-weight: bold;">"country"</span>:<span class="json_string" style="color: rgb(58, 181, 74); font-weight: bold;">"中国"</span>,        <span class="json_key" style="color: rgb(146, 39, 143); font-weight: bold;">"country_id"</span>:<span class="json_string" style="color: rgb(58, 181, 74); font-weight: bold;">"CN"</span>,        <span class="json_key" style="color: rgb(146, 39, 143); font-weight: bold;">"area"</span>:<span class="json_string" style="color: rgb(58, 181, 74); font-weight: bold;">"华东"</span>,        <span class="json_key" style="color: rgb(146, 39, 143); font-weight: bold;">"area_id"</span>:<span class="json_string" style="color: rgb(58, 181, 74); font-weight: bold;">"300000"</span>,        <span class="json_key" style="color: rgb(146, 39, 143); font-weight: bold;">"region"</span>:<span class="json_string" style="color: rgb(58, 181, 74); font-weight: bold;">"上海市"</span>,        <span class="json_key" style="color: rgb(146, 39, 143); font-weight: bold;">"region_id"</span>:<span class="json_string" style="color: rgb(58, 181, 74); font-weight: bold;">"310000"</span>,        <span class="json_key" style="color: rgb(146, 39, 143); font-weight: bold;">"city"</span>:<span class="json_string" style="color: rgb(58, 181, 74); font-weight: bold;">"上海市"</span>,        <span class="json_key" style="color: rgb(146, 39, 143); font-weight: bold;">"city_id"</span>:<span class="json_string" style="color: rgb(58, 181, 74); font-weight: bold;">"310100"</span>,        <span class="json_key" style="color: rgb(146, 39, 143); font-weight: bold;">"county"</span>:<span class="json_string" style="color: rgb(58, 181, 74); font-weight: bold;">"浦东"</span>,        <span class="json_key" style="color: rgb(146, 39, 143); font-weight: bold;">"county_id"</span>:<span class="json_string" style="color: rgb(58, 181, 74); font-weight: bold;">"334115"</span>,        <span class="json_key" style="color: rgb(146, 39, 143); font-weight: bold;">"isp"</span>:<span class="json_string" style="color: rgb(58, 181, 74); font-weight: bold;">"电信"</span>,        <span class="json_key" style="color: rgb(146, 39, 143); font-weight: bold;">"isp_id"</span>:<span class="json_string" style="color: rgb(58, 181, 74); font-weight: bold;">"100227"</span>,        <span class="json_key" style="color: rgb(146, 39, 143); font-weight: bold;">"ip"</span>:<span class="json_string" style="color: rgb(58, 181, 74); font-weight: bold;">"126.231.115.34"</span>    }</span><br style="color: rgb(85, 85, 85); font-family: Menlo, Monaco, Consolas, "Helvetica Neue", Helvetica, "Courier New", 微软雅黑, monospace, Arial, sans-serif, 黑体; font-size: 14px;" /><span style="color: rgb(85, 85, 85); font-family: Menlo, Monaco, Consolas, "Helvetica Neue", Helvetica, "Courier New", 微软雅黑, monospace, Arial, sans-serif, 黑体; font-size: 14px;">}</span></code>
<pre class="hljs objectivec" name="code" style="white-space: pre-wrap; word-wrap: normal; padding: 9.5px; background: rgb(253, 246, 227); margin-top: 0px; margin-bottom: 20px; line-height: 20px; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; word-break: break-all; overflow: auto;"><p class="p1" style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px;"><span class="s1">- (</span><span class="s2">void</span><span class="s1">)urlRequestOperation{</span></p><p class="p2" style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px;"><span class="s3">    </span><span class="s1">dispatch_async</span><span class="s3">(</span><span class="s1">dispatch_get_global_queue</span><span class="s3">(</span><span class="s4">DISPATCH_QUEUE_PRIORITY_BACKGROUND</span><span class="s3">, </span><span class="s5">0</span><span class="s3">), ^{</span></p><p class="p3" style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px;"><span class="s3">        </span><span class="s6">NSString</span><span class="s3"> *URLTmp1 = </span><span class="s1">@"http://1212.ip138.com/ic.asp"</span><span class="s3">;</span></p><p class="p2" style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px;"><span class="s3">        </span><span class="s6">NSString</span><span class="s3"> *URLTmp = [URLTmp1 </span><span class="s1">stringByAddingPercentEscapesUsingEncoding</span><span class="s3">:</span><span class="s1">NSUTF8StringEncoding</span><span class="s3">];</span></p><p class="p1" style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px;"><span class="s1">        </span><span class="s6">NSData</span><span class="s1"> * resData = [</span><span class="s6">NSData</span><span class="s1"> </span><span class="s7">dataWithContentsOfURL</span><span class="s1">:[</span><span class="s6">NSURL</span><span class="s1"> </span><span class="s7">URLWithString</span><span class="s1">:URLTmp]];</span></p><p class="p2" style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px;"><span class="s3">        </span><span class="s1">dispatch_async</span><span class="s3">(</span><span class="s1">dispatch_get_main_queue</span><span class="s3">(), ^{</span></p><p class="p1" style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px;"><span class="s1">            </span><span class="s2">if</span><span class="s1"> (resData) {</span></p><p class="p1" style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px;"><span class="s1">                </span><span class="s8">//</span><span class="s9">系统自带</span><span class="s8">JSON</span><span class="s9">解析</span></p><p class="p2" style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px;"><span class="s3">                </span><span class="s10">NSStringEncoding</span><span class="s3"> gbkEncoding = </span><span class="s1">CFStringConvertEncodingToNSStringEncoding</span><span class="s3">(</span><span class="s1">kCFStringEncodingGB_18030_2000</span><span class="s3">);</span></p><p class="p2" style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px;"><span class="s3">//<span style="font-family: STHeiti; font-size: 14px;">您的IP是:[122.222.122.22] 来自:上海市某某区 某某运营商</span></span></p><p class="p1" style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px;"><span class="s1">                </span><span class="s6">NSString</span><span class="s1"> *str3 = [[</span><span class="s6">NSString</span><span class="s1"> </span><span class="s7">alloc</span><span class="s1">] </span><span class="s7">initWithData</span><span class="s1">:resData </span><span class="s7">encoding</span><span class="s1">:gbkEncoding];</span></p><p class="p1" style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px;"><span class="s1">   }</span></p><p class="p1" style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px;"><span class="s1">        });</span></p><p class="p1" style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px;"><span class="s1">    });</span></p><p class="p1" style="margin-top: 0px; margin-bottom: 0px; padding-top: 0px; padding-bottom: 0px;"><span class="s1">}</span></p>

 
 
<pre class="hljs objectivec" name="code" style="white-space: pre-wrap; word-wrap: normal; padding: 9.5px; background: rgb(253, 246, 227); font-family: Menlo, Monaco, Consolas, "Courier New", monospace; margin-top: 0px; margin-bottom: 20px; line-height: 20px; word-break: break-all; overflow: auto;"><code class="objectivec" style="padding: 0px; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; font-size: 12px; background-color: transparent; border: none;"><span class="hljs-comment" style="color: rgb(147, 161, 161);">//获取局域网IP地址</span>
- (<span class="hljs-built_in" style="color: rgb(38, 139, 210);">NSString</span> *)getIpAddresses{
<span class="hljs-built_in" style="color: rgb(38, 139, 210);">NSString</span> *address = <span class="hljs-string" style="color: rgb(42, 161, 152);">@"error"</span>;
<span class="hljs-keyword" style="color: rgb(133, 153, 0);">struct</span> ifaddrs *interfaces = <span class="hljs-literal" style="color: rgb(0, 102, 102);">NULL</span>;
<span class="hljs-keyword" style="color: rgb(133, 153, 0);">struct</span> ifaddrs *temp_addr = <span class="hljs-literal" style="color: rgb(0, 102, 102);">NULL</span>;
<span class="hljs-keyword" style="color: rgb(133, 153, 0);">int</span> success = <span class="hljs-number" style="color: rgb(42, 161, 152);">0</span>;
<span class="hljs-comment" style="color: rgb(147, 161, 161);">// retrieve the current interfaces - returns 0 on success</span>
success = getifaddrs(&interfaces);
<span class="hljs-keyword" style="color: rgb(133, 153, 0);">if</span> (success == <span class="hljs-number" style="color: rgb(42, 161, 152);">0</span>)
{
<span class="hljs-comment" style="color: rgb(147, 161, 161);">// Loop through linked list of interfaces</span>
temp_addr = interfaces;
<span class="hljs-keyword" style="color: rgb(133, 153, 0);">while</span>(temp_addr != <span class="hljs-literal" style="color: rgb(0, 102, 102);">NULL</span>)
{
<span class="hljs-keyword" style="color: rgb(133, 153, 0);">if</span>(temp_addr->ifa_addr->sa_family == AF_INET)
{
<span class="hljs-comment" style="color: rgb(147, 161, 161);">// Check if interface is en0 which is the wifi connection on the iPhone</span>
<span class="hljs-keyword" style="color: rgb(133, 153, 0);">if</span>([[<span class="hljs-built_in" style="color: rgb(38, 139, 210);">NSString</span> stringWithUTF8String:temp_addr->ifa_name] isEqualToString:<span class="hljs-string" style="color: rgb(42, 161, 152);">@"en0"</span>])
{
<span class="hljs-comment" style="color: rgb(147, 161, 161);">// Get NSString from C String</span>
address = [<span class="hljs-built_in" style="color: rgb(38, 139, 210);">NSString</span> stringWithUTF8String:inet_ntoa(((<span class="hljs-keyword" style="color: rgb(133, 153, 0);">struct</span> sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
}
}
temp_addr = temp_addr->ifa_next;
}
}
<span class="hljs-comment" style="color: rgb(147, 161, 161);">// Free memory</span>
freeifaddrs(interfaces);
<span class="hljs-keyword" style="color: rgb(133, 153, 0);">return</span> address;
}</code>