(转载)Linux网络编程-inet_ntoa问题记录

(转载)http://blog.chinaunix.net/uid-1771330-id-2863811.html

今天在写代码时遇到一个问题并于在一个函数传递参数时连续调用inet_ntoa时出现的,下面是问题的模拟代码:

int main()
{
    char* pIp1;
    char* pIp2;
    char ip_addr1[] = "192.168.1.20";
    char ip_addr2[] = "192.168.1.40";

    struct in_addr addr1;
    struct in_addr addr2;

    char ip1[16] = {0};
    char ip2[16] = {0};

    bzero(&addr1, sizeof(struct in_addr));
    bzero(&addr2, sizeof(struct in_addr));

    inet_aton(ip_addr1, &addr1);
    inet_aton(ip_addr2, &addr2);

    printf("IP address1: %s\nIP address2: %s\n", inet_ntoa(addr1), inet_ntoa(addr2));

    printf("+++IP address1: %s\n", inet_ntoa(addr1));
    printf("+++IP address2: %s\n", inet_ntoa(addr2));

    pIp1 = inet_ntoa(addr1);
    pIp2 = inet_ntoa(addr2);
    printf("---IP address1: %s\n", pIp1);
    printf("---IP address2: %s\n", pIp2);

    return 0;
}

程序输出:

[root@robot ~]# ./a.out
IP address1: 192.168.1.20
IP address2: 192.168.1.20
+++IP address1: 192.168.1.20
+++IP address2: 192.168.1.40
---IP address1: 192.168.1.40
---IP address2: 192.168.1.40
[root@robot ~]#

 

注意:inet_ntoa()返回的字符串是临时装在一个“静态分配的缓冲”区里面,下一次调用此函数的时候缓冲区会被重写

posted @ 2013-05-03 00:47  robotke1  阅读(222)  评论(0编辑  收藏  举报