头文件
首先我们需要引入两个头文件。
#import <ifaddrs.h>
#import <arpa/inet.h>
方法实现
然后我们封装一个方法来实现Ip地址的获取,返回的是NSString类型的字符串。
- (NSString *)getDeviceIp
{
NSString *ip = @"Error";
struct ifaddrs *interfaces = nil;
struct ifaddrs *temp_addr = nil;
int success = getifaddrs(&interfaces);
//获取地址成功
if (!success)
{
temp_addr = interfaces;
while (temp_addr != NULL) {
if( temp_addr->ifa_addr->sa_family == AF_INET) {
// Check if interface is en0 which is the wifi connection on the iPhone
if ([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
// Get NSString from C String
ip = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
}
}
temp_addr = temp_addr->ifa_next;
}
}
freeifaddrs(interfaces);
return ip;
}