/*

  最近要用到网络编程的东西,差一点自己去山寨已有的函数。基础不好,不知道已有函数可以满足需要,呵呵。   这个示例程序说的是ip地址的数字形式和字符串形式之间的相互转换。   从字符串形式转换到数字形式: inet_pton -- presentation to numeric    从数字形式转换到字符串形式: inet_ntop -- numeric to presentation      #include <arpa/inet.h>   int inet_pton(int af, const char *src, void *dst);   参数af指的是地址族,取值AF_INET,如果是IPV4; 或AF_INET6,如果是IPV6      src指向是要转换的字符串的指针。      dst是存放转换后的数字形式的地址存放的地方。   返回值: 当成功时返回1,错误时返回0     #include <arpa/inet.h>   const char *inet_ntop(int af, const void *src,                         char *dst, socklen_t size);   参数af的意义同上,      src指向要转换的数字形式的指针。      dst指向存放結果空间的指针      size,如果要转换ipv4地址,由宏INET_ADDRSTRLEN定义,取值16。                             因为最长的ipv4地址的字符串形式就是16字节。                             例如"255.255.255.255"就是15个字符加一个'\0'结束符。            如果要转换ipv6地址,由宏INET6_ADDRSTRLEN定义,取46。                             至于为什么取46而不取40,我也搞不清楚。                             最长的IPV6地址的字符串形式是40字节。                             例如"2001:2001:2001:2001:2001:2001:2001:2001"就是40字节。 */
 
 
#include <arpa/inet.h>
#include <stdio.h>
 
int main()
{
    int i = 0;
    char *ipv4 = "10.3.6.123";
    char *ipv6 = "2001:db8:0:1234:0:567:1:1";
    unsigned char bufipv4[4] = {0};
    unsigned char bufipv6[16] = {0};
    char to_ipv4[INET_ADDRSTRLEN] = {0};
    char to_ipv6[INET6_ADDRSTRLEN] = {0};
 
    //把字符串10.3.6.123转换成数字的形式,并存储在bufipv4中。并输出验证是否转换成功
    if( inet_pton(AF_INET, ipv4, bufipv4) == 1) 
        for(i=0; i<sizeof(bufipv4); ++i)
            printf("%d ", bufipv4[i]);
 
    printf("\n");
 
    //把字符串ipv6转换成数字的形式,并存储在bufipv6中。并输出验证是否成功。
    if( inet_pton(AF_INET6, ipv6, bufipv6)==1 ) 
        for(i=0; i<sizeof(bufipv6); ++i)
            printf("%x ", bufipv6[i]);
 
    printf("\n");
 
    //把数字形式的地址转换成字符串的形式
    printf("%s\n", inet_ntop(AF_INET, bufipv4, to_ipv4, INET_ADDRSTRLEN));
    printf("%s\n", inet_ntop(AF_INET6, bufipv6, to_ipv6, INET6_ADDRSTRLEN));
 
    return 0;
}
/* 输出如下: 10 3 6 123  20 1 d b8 0 0 12 34 0 0 5 67 0 1 0 1  10.3.6.123 2001:db8:0:1234:0:567:1:1 */