### How to convert IP to hex using C++

Pages: 12
Hi guy .
I don`t known how to convert IP to hex .
In this link http://www.mustat.com/50.22.100.250 (Ip host www.cplusplus.com) . I see hex IP : Hex IP 0x321664fa
I want to convert IP "50.22.100.250" to "0x321664fa"
 ``12345678910111213141516`` ``````#include #include #include UINT32 ip_to_hex(UINT32 ip_add) { UINT32 ip_hex; /////code how to convert ?? return ip_hex; } void main() { //ip_to_hex(50.22.100.250); system("pause"); }``````

Can you help me ?
Thank guy.
Just print it as hex as in:
 `` `` ``printf("0x%x", ip_add);``
No no , It`s wrong
Did you try IP "123.30.128.10" , IP hex : 0x7b1e800a
When i try "%x" , it`s wrong
 ``12345`` ``````printf("%x \n", 123); printf("%x \n", 30); printf("%x \n", 128); printf("%x \n", 10); ``````

And this is result
7b 1e 80 and a
further we must separate each octect by a dot., Then convert decimal to hexa
Last edited on
When i try "%x" , it`s wrong
 ``1234`` `````` printf("%x \n", 123); printf("%x \n", 30); printf("%x \n", 128); printf("%x \n", 10);``````

And this is result
7b 1e 80 and a

Looks right to me. Just because your presentation is a little bit off doesn't make the results wrong.
 ``12345678910`` ``````#include #include int main() { int addr = inet_addr("127.0.0.1"); printf("0x%08x\n", addr); return 0; }``````
Or, as the original post, can use the WinSock 2 version, though it should be winsock2.h rather than winsock.h

 ``12345678910111213141516171819202122232425262728293031`` ``````#define WIN32_LEAN_AND_MEAN #include #include #include // need link with Ws2_32.lib #pragma comment(lib, "Ws2_32.lib") int main() { unsigned long ulAddr = INADDR_NONE; ulAddr = inet_addr("50.22.100.250"); if ( ulAddr == INADDR_NONE ) { printf("inet_addr failed and returned INADDR_NONE\n"); return 1; } if (ulAddr == INADDR_ANY) { printf("inet_addr failed and returned INADDR_ANY\n"); return 1; } printf("inet_addr returned success\n"); printf("\n"); printf("address = %lu\n", ulAddr); printf("\n"); return 0; }``````

Andy

PS also see

http://msdn.microsoft.com/en-us/library/windows/desktop/ms738563%28v=vs.85%29.aspx

(inc. sample code and comment near the end.)

Andy
Hi kbw
I try with your code
Ip 127.0.0.1 -> hex IP : 0x0100007f when i get hex ip from http://www.mustat.com/127.0.0.1 is 0x7f000001 . Result not correct .
Can you fix it ?

And hi andywestken , thank for your help , but use code from you , it`s wrong .

Thank
Why all those complications when there's asio?

 ``123456789`` ``````#include #include #include int main() { std::string str = "50.22.100.250"; auto ip = boost::asio::ip::address_v4::from_string(str); std::cout << std::hex << std::showbase << ip.to_ulong() << '\n'; }``````

online demo: http://liveworkspace.org/code/d742b41b06b8fe925e4a3f95e62c4cd2
oh Hi Cubbi . It`s work in online
But in my C++ , not found file
`#include <boost/asio.hpp> `

, and i get errors at line
 ``12`` ``````auto ip = boost::asio::ip::address_v4::from_string(str); std::cout << std::hex << std::showbase << ip.to_ulong() << '\n';``````

I use window 7 , VS C++ 2005 ,2010
Thank you
Quote from the page andywestken posted.
 Internet Addresses Values specified using the ".'' notation take one of the following forms: a.b.c.d a.b.c a.b a When four parts are specified, each is interpreted as a byte of data and assigned, from left to right, to the 4 bytes of an Internet address. When an Internet address is viewed as a 32-bit integer quantity on the Intel architecture, the bytes referred to above appear as "d.c.b.a''. That is, the bytes on an Intel processor are ordered from right to left.
 No no , It`s wrong
 Result not correct .
 Can you fix it ?
 thank for your help , but use code from you , it`s wrong .

I guess, you know best.
 But in my C++ , not found file #include I use window 7 , VS C++ 2005 ,2010

Then you can install boost from http://www.boostpro.com/download/
Here, this work.

 ``1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889`` ``````void Get_IPv4_Hex(string IP_Address,char Separator,bool Header,string& IP_Address_Result) { // Variables Temps int* Sections = new int[4]; char* Hash = new char[2](); char* Hex_Values = new char[17]; // Fill Hex Values Hex_Values[0] = '0'; Hex_Values[1] = '1'; Hex_Values[2] = '2'; Hex_Values[3] = '3'; Hex_Values[4] = '4'; Hex_Values[5] = '5'; Hex_Values[6] = '6'; Hex_Values[7] = '7'; Hex_Values[8] = '8'; Hex_Values[9] = '9'; Hex_Values[10] = 'A'; Hex_Values[11] = 'B'; Hex_Values[12] = 'C'; Hex_Values[13] = 'D'; Hex_Values[14] = 'E'; Hex_Values[15] = 'F'; Hex_Values[16] = '\0'; // Tokenizer IP Numbers string* Current_Value = new string(); int* Current_Quantity = new int(); for (unsigned int i = 0; i < IP_Address.length(); i++) { if (IP_Address[i] != Separator) { (*Current_Value) += IP_Address[i]; } else { if ((*Current_Quantity) == 0) { Sections[0] = atoi((*Current_Value).c_str()); // Section 1 IP } if ((*Current_Quantity) == 1) { Sections[1] = atoi((*Current_Value).c_str()); // Section 2 IP } if ((*Current_Quantity) == 2) { Sections[2] = atoi((*Current_Value).c_str()); // Section 3 IP } Current_Value->clear(); (*Current_Quantity)++; } } Sections[3] = atoi((*Current_Value).c_str()); // Section 4 IP // Free Memory Tokenizer delete Current_Value; delete Current_Quantity; // Add Header if (Header) { IP_Address_Result = "0x"; } // Convert Int To Hexadecimal Values Hash[0] = Hex_Values[((Sections[0] >> 4) & 0xF)]; Hash[1] = Hex_Values[(Sections[0]) & 0x0F]; IP_Address_Result.append(Hash,2); Hash[0] = Hex_Values[((Sections[1] >> 4) & 0xF)]; Hash[1] = Hex_Values[(Sections[1]) & 0x0F]; IP_Address_Result.append(Hash,2); Hash[0] = Hex_Values[((Sections[2] >> 4) & 0xF)]; Hash[1] = Hex_Values[(Sections[2]) & 0x0F]; IP_Address_Result.append(Hash,2); Hash[0] = Hex_Values[((Sections[3] >> 4) & 0xF)]; Hash[1] = Hex_Values[(Sections[3]) & 0x0F]; IP_Address_Result.append(Hash,2); // Free Memory delete[] Sections; delete[] Hash; delete[] Hex_Values; }``````

Example:
 ``12345`` ``````string Result; Get_IPv4_Hex("50.22.100.250",'.',true,Result); cout << Result << endl; // 0x321664FA ``````
That seems a little overly complicated, Jal.

 ``1234567891011121314151617181920212223242526272829303132333435363738`` ``````#include #include #include #include #include // caution: Does no error checking to ensure ip_address is // valid ip address. std::uint32_t to_uint32_t( const std::string & ip_address ) { const unsigned bits_per_term = 8 ; const unsigned num_terms = 4 ; std::istringstream ip(ip_address) ; uint32_t packed = 0 ; for ( unsigned i=0 ; i> term ; ip.ignore() ; packed += term << (bits_per_term * (num_terms-i-1)) ; } return packed ; } int main() { std::string ips[] = { "50.22.100.250", "123.30.128.10", "127.0.0.1" }; for ( unsigned i=0; i
@cire

As the original poster appears to be using Windows (from the winsock.h), I thought I'd better mention that your code is Linux specific: WinSock uses network byte order (big endian, the same as Linux) rather than host byte order (little endian).

Tweaking your code to output the value from inet_addr as well, you can see the byte order is reversed.

 ``123456789101112131415`` ``````... int main() { std::string ips[] = { "50.22.100.250", "123.30.128.10", "127.0.0.1" }; std::cout << std::showbase << std::hex; for ( unsigned i=0; i

(where the to_uint32_t() value precedes the inet_addr() value)

 ```50.22.100.250 is 0x321664fa cf. 0xfa641632 123.30.128.10 is 0x7b1e800a cf. 0xa801e7b 127.0.0.1 is 0x7f000001 cf. 0x100007f```

Andy

PS @Jal - I'n curious where your code comes from. Is it your? It's rather unusual to see a single integer allocated on the heap! (or string!)

`int* Current_Quantity = new int();`
Last edited on
 As the original poster appears to be using Windows (from the winsock.h), I thought I'd better mention that your code is Linux specific: WinSock uses network byte order (big endian, the same as Linux) rather than host byte order (little endian).

Actually it's OP specific, since he was unsatisfied with the byte order returned by inet_addr and was apparently unable to figure out how to reorder it. After all, he only wanted to get the same string he was shown by the website he cited.
@cire

oops!

Sorry, I lost the thread at some point...

Andy
@andywestken

Yes, it is mine, in fact i often work as well.
@Jal

Well, as I already kind of mentioned, you do seem to be putting (tiny) stuff on the heap that is usually left on the stack. In this code, I would have put none of the variables on the heap.

So I'm curious where the habit comes from? Java?? Or???

Andy
@andywestken

My habit does not come from Java, i only work with C and C++.

I have always preferred allocate dynamic memory on the heap regardless of its size because it enables me to gain a thorough control of the memory consumption of the program. The memory on the stack offers a high performance but cannot be liberated when one wants to difference of the allocated on the heap as you know.

My obsession to reduce memory consumption when i doing work that turn this into my habit hence the small temporary variables such as i have written before the has allocated on the heap inside a function. This obsession happens to me also when i make structures, abuse of the bit fields to gain performance and decrease memory consumption of the structure.

Example:
 ``1234567`` ``````struct PIXEL { unsigned int A:8; unsigned int R:8; unsigned int G:8; unsigned int B:8; };``````
Pages: 12