美文网首页
iOS获取应用IP

iOS获取应用IP

作者: 123_4567_8910 | 来源:发表于2020-03-31 18:28 被阅读0次

    1.获取本机局域网地址

    • 头文件
    //首先导入头文件信息
    #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.获取互联网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

    相关文章

      网友评论

          本文标题:iOS获取应用IP

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