1.獲取本機局域網(wǎng)地址
//首先導入頭文件信息
#include <ifaddrs.h>
#include <arpa/inet.h>
#include <net/if.h>
+ (NSString *)IPAddress;{
NSString *address = @"0.0.0.0";
struct ifaddrs *interfaces = NULL;
struct ifaddrs *XZHDX_addr = NULL;
int success = 0;
// retrieve the current interfaces - returns 0 on success
success = getifaddrs(&interfaces);
if (success == 0) {
// Loop through linked list of interfaces
XZHDX_addr = interfaces;
while (XZHDX_addr != NULL) {
if( XZHDX_addr->ifa_addr->sa_family == AF_INET) {
// Check if interface is en0 which is the wifi connection on the iPhone
if ([[NSString stringWithUTF8String:XZHDX_addr->ifa_name] isEqualToString:@"en0"]) {
// Get NSString from C String
address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)XZHDX_addr->ifa_addr)->sin_addr)];
}
}
XZHDX_addr = XZHDX_addr->ifa_next;
}
}
// Free memory
freeifaddrs(interfaces);
return address;
}
2.獲取互聯(lián)網(wǎng)IP地址
+ (NSString *)IPAddress
{
NSURL *ipURL = [NSURL URLWithString:@"http://ip.taobao.com/service/getIpInfo.php?ip=myip"];
NSData *data = [NSData dataWithContentsOfURL:ipURL];
NSDictionary *ipDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSString *ipStr = nil;
if (ipDic && [ipDic[@"code"] integerValue] == 0) { //獲取成功
ipStr = ipDic[@"data"][@"ip"];
}
return (ipStr ? ipStr : @"");
}
參考:https://blog.csdn.net/txz_gray/article/details/53217293