獲取iOS裝置當前ip位址

2021-06-18 19:25:28 字數 2733 閱讀 5522

第一種方法是用系統api的方式獲取,如下

#include 

#include 

#include 

#include 

#include 

#include 

#include 

#include 

#include 

#include 

#include 

#include 

#include 

#include 

//#include "getaddresses.h"

#define min(a,b)    ((a) < (b) ? (a) : (b))

#define max(a,b)    ((a) > (b) ? (a) : (b))

#define buffersize  4000

char

*if_names[maxaddrs];  

char

*ip_names[maxaddrs];  

char

*hw_addrs[maxaddrs];  

unsigned long

ip_addrs[maxaddrs];  

static

intnextaddr = 0;  

void

initaddresses()  

}  void

freeaddresses()  

initaddresses();  

}  void

getipaddresses()  

sockfd = socket(af_inet, sock_dgram, 0);  

if(sockfd < 0)  

ifc.ifc_len = buffersize;  

ifc.ifc_buf = buffer;  

if(ioctl(sockfd, siocgifconf, &ifc) < 0)  

lastname[0] = 0;  

for(ptr = buffer; ptr < buffer + ifc.ifc_len; )  

if((cptr = (

char

*)strchr(ifr->ifr_name, 

':')) != null)  

if(strncmp(lastname, ifr->ifr_name, ifnamsiz) == 0)  

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

ifrcopy = *ifr;  

ioctl(sockfd, siocgifflags, &ifrcopy);  

flags = ifrcopy.ifr_flags;  

if((flags & iff_up) == 0)  

if_names[nextaddr] = (char

*)malloc(strlen(ifr->ifr_name)+1);  

if(if_names[nextaddr] == null)  

strcpy(if_names[nextaddr], ifr->ifr_name);  

sin = (struct

sockaddr_in *)&ifr->ifr_addr;  

strcpy(temp, inet_ntoa(sin->sin_addr));  

ip_names[nextaddr] = (char

*)malloc(strlen(temp)+1);  

if(ip_names[nextaddr] == null)  

strcpy(ip_names[nextaddr], temp);  

ip_addrs[nextaddr] = sin->sin_addr.s_addr;  

++nextaddr;  

}  close(sockfd);  

}  void

gethwaddresses()  

sockfd = socket(af_inet, sock_dgram, 0);  

if(sockfd < 0)  

ifc.ifc_len = buffersize;  

ifc.ifc_buf = buffer;  

if(ioctl(sockfd, siocgifconf, (

char

*)&ifc) < 0)  

ifr = ifc.ifc_req;  

cplim = buffer + ifc.ifc_len;  

for(cp=buffer; cp < cplim; )  

}  }  }  

cp += sizeof

(ifr->ifr_name) + max(

sizeof

(ifr->ifr_addr), ifr->ifr_addr.sa_len);  

}  close(sockfd);  

}  

- (nsstring *)deviceipadress   

這樣得到的ip,如果在內網中,那麼就是內網的ip.

第二種方法是可以獲取公網ip

- (void

)getcurrentip  

;  }];  

[request setfailedblock:^];  

}  

用到了asihttprequest這個網路開源庫。

這個http url就可以獲取你當前的ip位址。

獲取iOS裝置當前ip位址

第一種方法是用系統api的方式獲取,如下 include include include include include include include include include include include include include include include getaddres...

獲取iOS裝置當前ip位址

第一種方法是用系統api的方式獲取,如下 include include include include include include include include include include include include include include include getaddres...

獲取iOS裝置當前ip位址

第一種方法是用系統api的方式獲取,如下 include include include include include include include include include include include include include include include getaddres...