2013-09-28 158 views

回答

2

这里的一个32位整数570534080可以分成四个8位无符号整数,它们就是IP地址。

int value = 570534080; // which is 0x2201a8c0 (0x22, 0x01, 0xa8, 0xc0) 
unsigned char *ip = &value; 
/* then */ 
ip[0] == 192; 
ip[1] == 168; 
ip[2] == 1; 
ip[3] == 34;  

请注意endian(big endian/little endian),这使@ KerrekSB的答案颠倒了。

编辑:

让我们使它更清晰。

在谈到IP地址和整数,实际上是两种类型的整数我们关注一下:

  1. IP地址的整数表示:192.168.1.34 < ==>(((192 * 256 + 168) * 256 + 1) * 256 + 34
  2. 的实际数据(可能是比特流),你会收到并解释为一个32位整数,就像OP提供的那样:570534080 <==> (0x22, 0x01, 0xa8, 0xc0)(on a little-endian machine) <==> (34.1.168.192)

请注意,这是平台特有的和危险的!由于这依赖于一个整数的字节顺序,这就是所谓的endianess。

再次编辑:

在这里,我会投票给@ DavidHeffernan的评论,这是使用inet_ntoa

+0

见我的答案下的评论。你的解决方案不是我的“逆向”。我总是正确的;你需要知道该平台的字节顺序。 –

+0

@KerrekSB我很抱歉,但我不相信你的'矿总是正确的;'。请看我的更新。 – starrify

+0

是的,你说得对,我没有检查OP的实际价值。我认为这是一个数字IP地址,但实际上它是将线数据解释为一个int。 –

10
#include <stdio.h> 
#include <sys/socket.h> 
#include <netinet/in.h> 
#include <arpa/inet.h> 

int main(void) { 
    int value=570534080; 
    struct in_addr addr = {value}; 
    printf("%s", inet_ntoa(addr)); 
    return 0; 
} 

测试:http://ideone.com/RCDgj4

对于Windows使用#include <winsock2.h>

+0

inet_ntoa函数不会生成“可读”整数。看看http://stackoverflow.com/questions/30153966/why-do-inet-ntoa-and-inet-ntop-reverse-the-bytes –

+0

@ m.r226这不是关于可读的整数 – kotlomoy