首页 > 解决方案 > 如何将 IPv4 地址转换为十进制

问题描述

是否有将点分十进制表示法(例如“192.168.0.1”)的 IPv4 地址转换为十进制值的功能?

有几个与此类似的问题,但都在寻找或拥有涉及编写函数来解决答案的答案。我正在寻找图书馆中的现有功能。

标签: c

解决方案


It turns out that Winsock 2 provides the inet_addr() function, which simply returns the equivalent decimal value for the address.

#include <stdio.h>
#include <winsock2.h>

int main(void)
{
    char* pAddr = "192.168.0.1";

    unsigned long value = inet_addr(pAddr);

    if (value == INADDR_NONE)
        printf("Invalid format of IP address");
    else
        printf("Decimal representation of %s is: %lu", pAddr, value);

    return 0;
}

推荐阅读