2013-07-06 59 views
1

我已經利用winapi函數inet_ntoa將無符號長整數轉換爲IP地址。我用相反的IP地址獲取IP地址。我使用網站http://www.allredroster.com/iptodec.htm來獲取輸入IP的十進制等效值地址。十進制到IP地址

for ex decimal equivalent of 206.117.16.66 is 3463778370 

,如果我使用的功能INET_NTOA找回它給IP的IP作爲66.16.117.206。下面是相同的代碼,請讓我知道正確的方式去做。

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

    } 

回答

4

inet_ntoa被指定爲以網絡字節順序輸入其輸入。您以主機字節順序提供輸入,這在x86系統上是倒退的(小端與大端)。您首先需要通過htonl傳遞小數地址。

+0

明智的回答你們每個人,感謝您清除概念。+ 1 upvote for each one.Thanks。 –

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



(11001110 01110101 00010000 01000010) = 3463778370 

轉換爲二進制。但他們在一起並轉換爲十進制。

+1

@jayaram:我知道從十進制轉換爲ip,反之亦然,但想知道winapi函數做了正確的轉換。 –

2

使用htonl(代表主機到網絡長)將IP地址從主機字節順序轉換爲網絡字節順序。它適用於小端和大端機器。

ULONG ipnet = htol(ipdec) 
相關問題