OC实现域名转IP

来源:互联网 发布:手机淘宝排名规则 编辑:程序博客网 时间:2024/06/04 18:01
#include <stdio.h>#include <netdb.h>#include <sys/socket.h>#include <arpa/inet.h>#include <string.h>#include <ifaddrs.h>+(NSArray *)getIPWithHostName:(NSString *)current_hostname{    struct hostent *hs;    struct sockaddr_in server;    const char *hostname = current_hostname.UTF8String;    NSMutableArray *OC_IP_ARRAY = [NSMutableArray array];    if ((hs = gethostbyname(hostname)) != NULL){        server.sin_addr = *((struct in_addr*)hs -> h_addr_list[0]);        inet_ntoa(*(struct in_addr *)hs->h_addr_list[0]);        int i = 0;        while (hs->h_addr_list[i]) {            printf("%s+++\n", inet_ntoa(*(struct in_addr *)hs->h_addr_list[i]));            char* IP = inet_ntoa(*(struct in_addr *)hs->h_addr_list[i]);            NSString *OC_IP = [NSString stringWithCString:IP encoding:NSUTF8StringEncoding];            [OC_IP_ARRAY addObject:OC_IP];            i++;        }        return OC_IP_ARRAY;    }    return nil;}

使用的时候直接传给他一个域名就可以,返回的值有可能是nil使用的时候需要判断一下,在swift里建立桥接文件也能正常使用

0 0
原创粉丝点击