通过域名转ip

//根据域名获取ip地址

//

-(NSString*)getIPWithHostName:(const NSString*)hostName

{

    const char *hostN= [hostName UTF8String];

    struct hostent* phot;

    

    @try {

        phot = gethostbyname(hostN);

        

    }

    @catch (NSException *exception) {

        return nil;

    }

    

    struct in_addr ip_addr;

    memcpy(&ip_addr, phot->h_addr_list[0], 4);

    char ip[20] = {0};

    inet_ntop(AF_INET, &ip_addr, ip, sizeof(ip));

    

    NSString* strIPAddress = [NSString stringWithUTF8String:ip];

    return strIPAddress;

}

 

 

- (NSArray *)getIP{

    NSString *hostname = @"www.baidu.com";

    CFHostRef hostRef = CFHostCreateWithName(kCFAllocatorDefault, (__bridge CFStringRef)hostname);

    if (hostRef)

    {

        Boolean result = CFHostStartInfoResolution(hostRef, kCFHostAddresses, NULL);

        if (result == TRUE)

        {

            NSArray *addresses = (__bridge NSArray*)CFHostGetAddressing(hostRef, &result);

            

            NSMutableArray *tempDNS = [[NSMutableArray alloc] init];

            for(int i = 0; i < addresses.count; i++)

            {

                struct sockaddr_in* remoteAddr;

                CFDataRef saData = (CFDataRef)CFArrayGetValueAtIndex((__bridge CFArrayRef)addresses, i);

                remoteAddr = (struct sockaddr_in*)CFDataGetBytePtr(saData);

                if(remoteAddr != NULL)

                {

                    const char *strIP41 = inet_ntoa(remoteAddr->sin_addr);

                    NSString *strDNS =[NSString stringWithCString:strIP41 encoding:NSASCIIStringEncoding];

                    [tempDNS addObject:strDNS];

                }

            }

            return tempDNS;

        }

    }

    return nil;

}

 

posted @ 2016-05-27 11:48  提灯走夜路  阅读(324)  评论(1编辑  收藏  举报