整数到IP地址 - C.

Kri*_*rds 23 c string ip-address

我正在准备一个测验,我怀疑我可能会负责实现这样的功能.基本上,给定一个网络符号的IP地址,我们如何从一个32位整数到它的点分十进制表示法(如155.247.182.83)...?显然我们也不能使用任何类型的inet函数......我很难过!

Ros*_*one 95

你实际上可以使用inet函数.观察.

main.c中:

#include <arpa/inet.h>

main() {
    uint32_t ip = 2110443574;
    struct in_addr ip_addr;
    ip_addr.s_addr = ip;
    printf("The IP address is %s\n", inet_ntoa(ip_addr));
}
Run Code Online (Sandbox Code Playgroud)

结果gcc main.c -ansi; ./a.out

IP地址是54.208.202.125

请注意,评论者说这不适用于Windows.

  • 这显然是最好的答案.它为什么没有绿色标记?无需重新发明轮子. (18认同)

Wer*_*sey 62

下面是一个简单的方法来做到这一点:在(ip >> 8),(ip >> 16)(ip >> 24)移动第二,第三和第四个字节到低位字节,而& 0xFF隔离在每一步至少显著字节.

void print_ip(unsigned int ip)
{
    unsigned char bytes[4];
    bytes[0] = ip & 0xFF;
    bytes[1] = (ip >> 8) & 0xFF;
    bytes[2] = (ip >> 16) & 0xFF;
    bytes[3] = (ip >> 24) & 0xFF;   
    printf("%d.%d.%d.%d\n", bytes[3], bytes[2], bytes[1], bytes[0]);        
}
Run Code Online (Sandbox Code Playgroud)

bytes[0] = (ip >> 0) & 0xFF;第一步有暗示.

用于snprintf()将其打印到字符串.


Nic*_*kis 6

另一种方法:

union IP {
    unsigned int ip;
    struct {
      unsigned char d;
      unsigned char c;
      unsigned char b;
      unsigned char a;
    } ip2;
};

...
char  ips[20];
IP ip;
ip.ip = 0xAABBCCDD;

sprintf(ips, "%x.%x.%x.%x", ip.ip2.a, ip.ip2.b, ip.ip2.c, ip.ip2.d);
printf("%s\n", ips);
Run Code Online (Sandbox Code Playgroud)

  • 这不便携; 它取决于sizeof(无符号)是4(像其他答案一样)和int中的字节顺序. (2认同)

Yuv*_*dam 5

提示:将32位整数分解为4个8位整数,并将其打印出来.

有些事情(未编译,YMMV):

int i = 0xDEADBEEF; // some 32-bit integer
printf("%i.%i.%i.%i",
          (i >> 24) & 0xFF,
          (i >> 16) & 0xFF,
          (i >> 8) & 0xFF,
          i & 0xFF);
Run Code Online (Sandbox Code Playgroud)

  • 呃......这不编译,是否缺少函数调用?并且移位计数都是错误的,他们似乎认为两个十六进制数字等于四位.此外,最好先移动并稍后屏蔽,就像iWerner一样. (3认同)
  • 好家伙!永远不要写像0xDEADBEEF,除非你想要自己调试几个小时等.见http://stackoverflow.com/questions/1556672/most-horrifying-line-of-code-you-have-ever-seen/1556731# 1556731 (2认同)