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

• September 27th, 2012, 11:13 AM
How to convert IP to hex using C++ ?
Hi guy .
I don`t known how to convert IP to hex .
In this link http://www.mustat.com/70.42.23.121 (Ip host codeguru.com) . I see hex IP : Hex IP 0x462a1779
I want to convert IP "70.42.23.121" to "0x462a1779"

Code:

```#include <winsock.h> #include <windows.h> #include <stdio.h> UINT32 ip_to_hex(UINT32 ip_add) {   UINT32 ip_hex;   //code convert ip to hex   return ip_hex; } void main() {   //ip_to_hex(70.42.23.121);   system("pause"); }```
Did you try IP "123.30.128.10" , IP hex : 0x7b1e800a
When i try "%x" , it`s wrong

Code:

```        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 , not 0a
further i think we must separate each octect by a (dot) . , Then convert decimal to hexa
Can you help me ?
Thank guy.
• September 27th, 2012, 11:59 AM
Clark_Kent_SuperCodr
Re: How to convert IP to hex using C++ ?
Do this:
Code:

`printf("0%x \n", 10);`
But if it's greater than decimal 16 ( hex 10) then the 0%x is not needed.
• September 27th, 2012, 12:18 PM
S_M_A
Re: How to convert IP to hex using C++ ?
• September 27th, 2012, 04:48 PM
cilu
Re: How to convert IP to hex using C++ ?
I don't understand your ip_to_hex() function. If you want to convert a string with the ip in this format "70.42.23.121" then your function should take a string and not an integer.
• September 27th, 2012, 09:05 PM
Re: How to convert IP to hex using C++ ?
Hi S_M_A , I have tried that code , but it`s wrong . Did you try http://www.mustat.com/127.0.0.1 . you can see ip hex.

Hi Clark_Kent_SuperCodr and cilu
Can you demo some of code for me ?

Code:

```UINT32  ip_to_hex(char ip_add) {         UINT32 ip_hex;         ip_hex =inet_addr(( ip_add).ToChar);         //printf("0x%08x\n", ip_hex);         return ip_hex; }```
Thank for you.
• September 28th, 2012, 01:03 AM
cilu
Re: How to convert IP to hex using C++ ?
headshot, you don't seem to understand the difference between integers, characters or strings. I think you need to start with the basics and then get to more complicated things.

Code:

```unsigned int ip_to_hex(const char* strip) {   unsigned int ip = 0;   char* str = _strdup(strip);   char delimiters[] = ".";   char* token = strtok(str, delimiters);   int tokencount = 0;   while(token != NULL)   {       if(tokencount < 4)       {         int n = atoi(token);         ip = ip | n << 8 * (3 - tokencount);       }       tokencount++;       token = strtok(NULL, delimiters);   }   free(str);   if(tokencount != 4)       ip = 0;   return ip; } int _tmain(int argc, _TCHAR* argv[]) {   int ip = ip_to_hex("127.0.0.1");   return 0; }```
• September 28th, 2012, 03:12 AM