获取设备IP地址

作者: 小木___Boy | 来源:发表于2015-12-03 15:20 被阅读728次

建议使用工厂方法,一步搞定。

include <ifaddrs.h>

include <arpa/inet.h>

.h文件声明方法
/*
* 获取IP
*/
+ (NSString *)deviceIPAdress;

.m文件
+ (NSString *)deviceIPAdress{

NSString *address = @"an error occurred when obtaining ip address";
struct ifaddrs *interfaces = NULL;
struct ifaddrs *temp_addr = NULL;
int success = 0;

success = getifaddrs(&interfaces);

if (success == 0) { // 0 表示获取成功
    
    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
                address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
            }
        }
        
        temp_addr = temp_addr->ifa_next;
    }
}

freeifaddrs(interfaces);

NSLog(@"手机的IP是:%@", address);
return address;
}

相关文章

网友评论

    本文标题:获取设备IP地址

    本文链接:https://www.haomeiwen.com/subject/nulshttx.html