iOS, 根据域名获取IP

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_31177681/article/details/85062262

#include <netdb.h>
#include <sys/socket.h>
#include <arpa/inet.h>

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

{

    const char *hostN= [hostName UTF8String];

    struct hostent* phot;

    

    @try {

        phot = gethostbyname(hostN);

        if (phot == nil) {

            return nil;

        }

    }

    @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;

}

猜你喜欢

转载自blog.csdn.net/sinat_31177681/article/details/85062262