iOS 取得 IP 位址的方法有很多,大致可分為兩類:透過系統內建功能取得本機 IP,以及取得外部網路的公網 IP。下面一起來看看具體實作。
要取得裝置的 IP 位址,網路上隨便一搜就能找到一堆結果,但這些程式碼大多是用 C 語言寫的,並未針對 iOS 做過最佳化,使用起來並不方便。既然只是要取個 IP,把它封裝成一個函式,呼叫起來才順手。以下程式碼就是把網路上的範例整理並做 iOS 適配,函式會回傳一個包含所有網卡 IP 的陣列。
程式碼如下:
- (NSArray *)getIpAddresses {
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) return nil;
NSMutableArray *ips = [NSMutableArray array];
int BUFFERSIZE = 4096;
struct ifconf ifc;
char buffer[BUFFERSIZE], *ptr, lastname[IFNAMSIZ], *cptr;
struct ifreq *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 = (struct ifreq *)ptr;
int len = sizeof(struct sockaddr);
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(((struct sockaddr_in *)&ifr->ifr_addr)->sin_addr)];
[ips addObject:ip];
}
}
close(sockfd);
return ips;
}
檔案開頭需加上以下 import:
#import <sys/socket.h>
#import <sys/sockio.h>
#import <sys/ioctl.h>
#import <net/if.h>
#import <arpa/inet.h>
第二種方法則是取得公網 IP:
- (void)getCurrentIP
{
NSURL *url = [NSURL URLWithString:@"https://automation.whatismyip.com/n09230945.asp"];
__block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setCompletionBlock:^{
NSString *responseString = [request responseString];
if (responseString) {
NSString *ip = [NSString stringWithFormat:@"%@", responseString];
NSLog(@"responseString = %@", ip);
};
];
[request setFailedBlock:^{
}];
}
這裡用到了 ASIHTTPRequest 這個網路開源庫。