美文网首页ios 学习
iOS根据域名获取IP

iOS根据域名获取IP

作者: Fendouzhe | 来源:发表于2023-06-28 11:43 被阅读0次
#include <netdb.h>
#include <arpa/inet.h>

- (NSString *)getIPWithHostName:(NSString *)hostName {
    const char *hostN = [hostName UTF8String];
    struct hostent* phot;
    @try {
        phot = gethostbyname(hostN);
    }
    @catch (NSException *exception) {
        return nil;
    }
    if (!phot) {
        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;
}

//连外网获取
NSLog(@"域名转 ip = %@",[self getIPWithHostName:@"www.baidu.com"]);//157.148.69.74
//连内网获取
NSLog(@"域名转 ip = %@",[self getIPWithHostName:@"dmcss-pv-gn.sdc.cs.icbc"]);//122.71.8.208
NSLog(@"域名转 ip = %@",[self getIPWithHostName:@"cmcss-pv-gn.sdc.cs.icbc"]);//122.28.248.37
NSLog(@"域名转 ip = %@",[self getIPWithHostName:@"cmcss-app-mobileapp-dcpp.sdc.cs.icbc"]);//122.30.216.61
NSLog(@"域名转 ip = %@",[self getIPWithHostName:@"dmcss-app-mobileapp-dcpp.sdc.cs.icbc"]);//122.30.216.60
NSLog(@"域名转 ip = %@",[self getIPWithHostName:@"mcss-app-mobileapp-dccp.sdc.cs.icbc"]);//122.71.11.67

相关文章

网友评论

    本文标题:iOS根据域名获取IP

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