在不使用socket函数的基础上,编写一个C语言程序实现将以字符串形式表现的IP地址转换为以32位

2025-04-28 10:02:23
推荐回答(1个)
回答1:

#include 

unsigned int ip_addr(const char *ip)
{
int a, b, c, d;
if (sscanf(ip, "%d.%d.%d.%d", &a, &b, &c, &d) == 4)
{
return (a << 24) | (b << 16) | (c << 8) | d;
}

return 0;
}

int main()
{
printf("0x%08X\n", ip_addr("192.168.1.100"));

return 0;
}

Linux 下编译及测试结果:

[root@localhost err_log]# g++ test.cpp -g3 -Wall -o test
[root@localhost err_log]# ./test 
0xC0A80164