简体   繁体   English

将整数值转换为ip-address

[英]Convert integer value to ip-address

How to convert a 32-bit integer value to an ip-address? 如何将32位整数值转换为ip-address?

I am having int value=570534080 and want to convert it to 192.168.1.34 . 我有int value=570534080并想将其转换为192.168.1.34

#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;
}

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

For Windows use #include <winsock2.h> 对于Windows,请使用#include <winsock2.h>

A 32-bit integer here, 570534080 , can be splitted into four 8-bit unsigned integers, which are exact the IP address. 这里的32位整数570534080可以分成4个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;    

Please notice the endian (big endian / little endian), which makes @KerrekSB's answer reversed. 请注意endian(big endian / little endian),这使得@ KerrekSB的答案发生逆转。

EDITED: 编辑:

Let's making it clearer. 让我们更清楚。

When talking about IP address and integers, there're actually TWO types of integers we concern about: 在谈论IP地址和整数时,我们关注的实际上有两种类型的整数:

  1. The integer representation of the IP address: 192.168.1.34 <==> (((192 * 256 + 168) * 256 + 1) * 256 + 34 IP地址的整数表示形式: 192.168.1.34 <==> (((192 * 256 + 168) * 256 + 1) * 256 + 34
  2. The actual data (bit stream maybe) you receive and interpreted in an 32-bit integer, like what this OP provides: 570534080 <==> (0x22, 0x01, 0xa8, 0xc0)(on a little-endian machine) <==> (34.1.168.192) . 您收到并以32位整数解释的实际数据(可能是位流),如此OP提供的内容: 570534080 <==> (0x22, 0x01, 0xa8, 0xc0)(on a little-endian machine) <==> (34.1.168.192)

PLEASE NOTICE THIS IS PLATFORM SPECIFIC AND DANGEROUS! 请注意,这是特定和危险的平台! Since this relies on the byte order of an integer number, which is called endianess. 因为这依赖于整数的字节顺序,这称为endianess。

AGAIN EDITED: 再次编辑:

Here I'd vote for @DavidHeffernan's comment, which is to use inet_ntoa . 在这里,我投票给@ DavidHeffernan的评论,即使用inet_ntoa

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM