连续调用inet_ntoa打印出错的问题

近日写程序,在打印信息的时候调用了inet_ntoa函数,出现了打印一直出错的情况。google了一下,是因为inet_ntoa这类函数没有保证线程安全,其实现原理是在静态内容中申请一块内存,每次调用后返回该静态内存的指针,若是在同一个printf语句中连续调用两次inet_ntoa函数会导致后调用的覆盖先覆盖的那个。

举个例子(参考了某位前辈的blogs):

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <netinet/in.h>
 4 int main()
 5 {
 6         struct sockaddr_in ra = {0};
 7         struct sockaddr_in sa = {0};
 8         ra.sin_addr.s_addr = -217732928; //192.168.5.243    
 9         sa.sin_addr.s_addr = -939415360; //192.168.5.200  
10         printf("ip of recv:%s
ip of send:%s
",
11                         inet_ntoa(ra.sin_addr),inet_ntoa(sa.sin_addr));
12         printf("ip of send:%s
",inet_ntoa(sa.sin_addr));
13         printf("ip of recv:%s
",inet_ntoa(ra.sin_addr));
14 }

执行结果:

1 [root@host-b lab]# gcc test_ntoa.c 
2 [root@host-b lab]# ./a.out 
3 ip of recv:192.168.5.243
4 ip of send:192.168.5.243
5 ip of send:192.168.1.200
6 ip of recv:192.168.5.243

结果的3、4两行对应code中的11行,结果的5、6两行对用code中的12、13两行,3、4两行的结果明显不正确,原因就是在inet_ntoa(ra.sin_addr)返回的地址将inet_ntoa(sa.sin_addr)的返回地址

原文地址:https://www.cnblogs.com/lovemyspring/p/3330040.html