[C]将十进制IP转换为虚线十进制表示法

时间:2011-11-16 22:08:56

标签: c endianness

我得到了以下十进制IP:" 3232235876"它代表" 192.168.1.100"

我通过以下方式得到它:

   //GET IP
        if (gethostname(hostname, sizeof(hostname)) == SOCKET_ERROR) {
            printf("%s","host not found");
        }

        struct hostent *phe = gethostbyname(hostname);
        memcpy(&addr, phe->h_addr_list[0], sizeof(struct in_addr));

        //Convert IP to Decimal notation
        sprintf(decResult,"%u", addr);
        sprintf(decResult,"%u", htonl(atoi(decResult))); 

But now is my question how do I reconvert it to the Dotted Decimal Notation?

我知道' inet_ntoa'功能,但我首先需要得到' 3232235876'转换了其他东西,然后我需要将其转换为addr。

对于这两个问题,我都不知道答案:/

亲切的问候。

1 个答案:

答案 0 :(得分:4)

使用inet_ntoa将地址转换为字符串:

if (gethostname(hostname, sizeof(hostname)) == -1) {
    printf("host not found");
    return;
}

struct hostent *phe = gethostbyname(hostname);
if (phe == NULL) {
    printf("Could resolve %s!", hostname);
    return;
}

struct in_addr **addr_list = (struct in_addr **)phe->h_addr_list;
char *addr_str = inet_ntoa(*addr_list[0]);

你也可以像这样迭代地址列表:

for (int i = 0; addr_list[i] != NULL; i++) {
    printf("%s ", inet_ntoa(*addr_list[i]));
}

请参阅this gethostbyname man page中的示例代码。请注意,gethostbyname已弃用,因为它不适用于IPv6。您应该使用getaddrinfo代替。再次,see the man page for example code

相关问题