Santhosh Pai
Santhosh Pai

Reputation: 2625

decimal to ip address

I have made use of winapi function inet_ntoa to convert the unsigned long decimal number to ip address .I'm getting the ip address in reverse .I used the website http://www.allredroster.com/iptodec.htm to get the decimal equivalent of the input ip address.

for ex decimal equivalent of 206.117.16.66 is 3463778370

and if i use the function inet_ntoa to get back the ip its giving the ip as 66.16.117.206.Below is the code for the same , please let me know the correct way to do it.

  #include<stdio.h>
  #include<WinSock2.h>
  #pragma comment(lib, "Ws2_32.lib")

  int main()
  {

       ULONG ipdec=0;
       struct in_addr ipadr;
       char ip[50];
       printf("\n Enter the ip address in decimal equivalent of ip address : ");
       scanf_s("%ld",&ipdec);
   ipadr.S_un.S_addr=ipdec;
       strcpy_s(ip,inet_ntoa(ipadr));
   printf("\n The ip address in dotted format is :  %s \n" ,ip);

  }

Upvotes: 1

Views: 877

Answers (3)

Yu Hao
Yu Hao

Reputation: 122493

Use htonl (stands for host to network long) to convert ip address from host byte order to network byte order. It works for both little-endian and big-endian machines.

ULONG ipnet = htol(ipdec)

Upvotes: 2

Jayram
Jayram

Reputation: 19588

206 = 11001110
117 = 01110101
16  = 00010000
66  = 01000010



(11001110 01110101 00010000 01000010) = 3463778370

Convert to binary. But them together and convert to Decimal.

Upvotes: 3

John Zwinck
John Zwinck

Reputation: 249502

inet_ntoa is specified as taking its input in network byte order. You are providing the input in host byte order, which on x86 systems is backward (little endian vs. big endian). You need to pass the decimal address through htonl first.

Upvotes: 4

Related Questions