美文网首页
iOS 根据域名动态获取ip

iOS 根据域名动态获取ip

作者: 奋斗的小马达 | 来源:发表于2021-01-11 13:39 被阅读0次

首先需要用到系统的几个框架

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

代码如下:

- (NSString*)getIPWithHostName:(const NSString*)hostName
{
    const char *hostName= [hostName UTF8String];
    struct hostent* phot;
    
    @try {
        phot = gethostbyname(hostName);
        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;
}

相关文章

网友评论

      本文标题:iOS 根据域名动态获取ip

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