ios之域名转IP和获取IP

之前的项目有域名转IP这需求,所以查了这方面的资料,然后站在一些大牛的肩膀上写了一个网络工具类,感觉还可用,就把一些代码分享下,让有这方面需要的人参考参考。

1.要引入的头文件

//域名转IP
#include 
#include 
#include 
#include 
//获取IP
#include 
#include 
#include 
#include 
#import 
#import 

2.域名转IP:需有网络才能进行

+ (NSString *)queryIpWithDomain:(NSString *)domain
{
    struct hostent *hs;
    struct sockaddr_in server;
    if ((hs = gethostbyname([domain UTF8String])) != NULL)     
    {
        server.sin_addr = *((struct in_addr*)hs->h_addr_list[0]);
        return [NSString stringWithUTF8String:inet_ntoa(server.sin_addr)];
    }
    return nil;
}

调用代码:

[NetUtil queryIpWithDomain:@"www.baidu.com"];

3.通过查询网址,解析html得到ip地址

+ (NSString *)whatismyipdotcom
{
    NSError *error;
    NSURL *ipURL = [NSURL URLWithString:@"http://iframe.ip138.com/ic.asp"];
    NSString *ip = [NSString stringWithContentsOfURL:ipURL encoding:1 error:&error];
    
    NSRange range = [ip rangeOfString:@"
ÄúµÄIPÊÇ£º["]; NSString *str = @"
ÄúµÄIPÊÇ£º["; if (range.location > 0 && range.location < ip.length) { range.location += str.length ; range.length = 17; ip = [ip substringWithRange:range]; range = [ip rangeOfString:@"]"]; range.length = range.location; range.location = 0; ip = [ip substringWithRange:range]; } return ip ? ip : nil; }


4.查询内网地址ip方法1
+ (NSString *)queryIPAddress
{
    BOOL success;
    struct ifaddrs * addrs;
    const struct ifaddrs * cursor;
    
    success = getifaddrs(&addrs) == 0;
    if (success) {
        cursor = addrs;
        while (cursor != NULL) {
            // the second test keeps from picking up the loopback address
            if (cursor->ifa_addr->sa_family == AF_INET && (cursor->ifa_flags & IFF_LOOPBACK) == 0)
            {
                NSString *name = [NSString stringWithUTF8String:cursor->ifa_name];
                if ([name isEqualToString:@"en0"])  // Wi-Fi adapter
                    return [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)cursor->ifa_addr)->sin_addr)];
            }
            cursor = cursor->ifa_next;
        }
        freeifaddrs(addrs);
    }
    return nil;
}

5.查询内网地址ip方法2

+ (NSString *)localIPAddress
{
    char baseHostName[256] = {0}; // Thanks, Gunnar Larisch
    int success = gethostname(baseHostName, 255);
    if (success != 0) return nil;
    //    baseHostName[255] = '0';
    NSString *hostname=nil;
#if TARGET_IPHONE_SIMULATOR
     hostname=[NSString stringWithFormat:@"%s", baseHostName];
#else
     hostname=[NSString stringWithFormat:@"%s.local", baseHostName];
#endif
    
    struct hostent *host = gethostbyname([hostname UTF8String]);
    if (!host) {herror("resolv"); return nil;}
    struct in_addr **list = (struct in_addr **)host->h_addr_list;
    return [NSString stringWithCString:inet_ntoa(*list[0]) encoding:NSUTF8StringEncoding];
}




你可能感兴趣的:(ios,ios,域名,ip,socket)