Windows 下IP点分十进制和网络字节序的转换

来源:互联网 发布:淘宝直播卖的翡翠a货 编辑:程序博客网 时间:2024/05/22 06:24


博客http://blog.csdn.net/unimen/article/details/6844456给出相关实现,我根据C库的代码,也给出一个:

[cpp] view plaincopy
  1. #include   
  2. #include   
  3. #include   
  4. #include   
  5. #include   
  6. #include   
  7.   
  8. /* 
  9.  * Ascii internet address interpretation routine. 
  10.  * The value returned is in network order. 
  11.  */  
  12. unsigned int  
  13. __inet_aton(const char *cp)  
  14. {  
  15.     unsigned int val = 0;  
  16.     unsigned int tmp = 0;  
  17.     char c;  
  18.     int base = 10;  
  19.     int shift = 32;  
  20.   
  21.     c = *cp;  
  22.     for (;;) {//可以给出一个任意长度的字符串;  
  23.         tmp = 0;  
  24.         for (;;) {//获得'.'分割的每一个字符串的数值;  
  25.             if (isdigit(c)) {  
  26.                 tmp = (tmp * base) + (c - '0');  
  27.                 c = *++cp;  
  28.             } else break;  
  29.         }  
  30.   
  31.         shift -= 8;  
  32.         tmp <<= shift;  
  33.         val += tmp;   
  34.           
  35.         if (c == '.') {  
  36.             c = *++cp;  
  37.         } else  
  38.             break;  
  39.     }  
  40.   
  41.     /* 
  42.      * Check for trailing characters. 
  43.      */  
  44.     if (c != '\0' && (!isspace(c)))  
  45.         goto ret_0;  
  46.   
  47.     return (htonl (val));//返回网络字节序  
  48. ret_0:  
  49.     return (0);  
  50. }  
  51.   
  52. /* The interface of this function is completely stupid, it requires a 
  53.    static buffer.  We relax this a bit in that we allow one buffer for 
  54.    each thread.  */  
  55. static char buffer[18];//作为库函数,正式这个函数不能重入的原因;  
  56. char *  
  57. __inet_ntoa (unsigned int in)  
  58. {  
  59.   unsigned char *bytes = (unsigned char *) ∈  
  60.   snprintf (buffer, sizeof (buffer), "%d.%d.%d.%d",  
  61.           bytes[0], bytes[1], bytes[2], bytes[3]);//网络字节序是小端表示,第一个是byte[0];  
  62.   
  63.   return buffer;  
  64. }  
  65.   
  66. int main()  
  67. {  
  68.     printf("ip :%lu\n",__inet_aton("192.168.1.105 "));    
  69.     printf("str:%s\n",__inet_ntoa(__inet_aton("192.168.1.105")));  
  70.     return 0;     
  71. }  
也可以使用Windows socket API
(1)inet_ntoa() //将网络字节序转换为十分点进制字符串
(2)inet_addr() //将十分点进制字符串转换为网络字节序
例:
unsigned  long  addr=inet_addr("127.0.0.1");
char * Apddr=inet_ntoa(*(in_addr*)&addr);

in_addr 为网络地址结构体大小为4个字节



0 0