今天在调试网络时,发现一个奇怪的现象:
网络是连通的,但是输出日志中的服务端和客户端的IP地址是一样的。
通过调试,发现读取配置文件时,服务端的IP和客户端的IP分别是192.168.1.65和 192.168.1.227,但是输出日志时却都显示192.168.1.65。
gdb调试信息如下:
ina2
.
sin_addr和
ina1
.
sin_addr值不同,但是调用
inet_ntoa函数后的结果竟然是一样的。
输出日志的结果如下:
我们看到
inet_ntoa函数返回一个字符指针,它指向一个定义在函数inet_ntoa中的static 类型字符串。
也就是说,每次调用inet_ntoa函数,都会改变最后一次调用inet_ntoa函数时得到的结果。
原来如此。
做个简单的测试
输出结果如下:
修改输出日志的代码,如下:
输出日志的 结果如下:
~~~~~~~ the end~~~~~~~~~
hoegh
2017.10.27
通过调试,发现读取配置文件时,服务端的IP和客户端的IP分别是192.168.1.65和 192.168.1.227,但是输出日志时却都显示192.168.1.65。
1.现象
输出日志的代码如下:点击(此处)折叠或打开
- TraceLog::Trace(TLL_DEBUG, "svrIp:%s svrport:%d clientIp:%s clientport:%d send data to net",
- inet_ntoa(ina1.sin_addr), udpConnInfo[pos].peerPort, inet_ntoa(ina2.sin_addr),udpConnInfo[pos].localPort);
点击(此处)折叠或打开
- gdb)
- (gdb) p ina2.sin_addr
- $7 = {s_addr = 3808536768}
- (gdb) p ina1.sin_addr
- $8 = {s_addr = 1090627776}
- (gdb) p inet_ntoa(ina2.sin_addr)
- $9 = -134342936
- (gdb) p inet_ntoa(ina1.sin_addr)
- $10 = -134342936
输出日志的结果如下:
点击(此处)折叠或打开
- svrIp:192.168.1.65 svrport:11151 clientIp:192.168.1.65 clientport:8080 send data to net
2.原因
先查了一下inet_ntoa函数的官方定义点击(此处)折叠或打开
- inet_ntoa function
- The inet_ntoa function converts an (Ipv4) Internet network address into an ASCII string in Internet standard dotted-decimal format.
-
- Syntax
- C++
-
- char* FAR inet_ntoa(
- _In_ struct in_addr in
- );
-
- Parameters
-
- in [in]
- An in_addr structure that represents an Internet host address.
- Return value
-
- If no error occurs, inet_ntoa returns a character pointer to a static buffer containing the text address in standard ".'' notation. Otherwise, it returns NULL.
- Remarks
-
- The inet_ntoa function takes an Internet address structure specified by the in parameter and returns a NULL-terminated ASCII string that represents the address in "." (dot) notation as in "192.168.16.0
也就是说,每次调用inet_ntoa函数,都会改变最后一次调用inet_ntoa函数时得到的结果。
原来如此。
做个简单的测试
点击(此处)折叠或打开
- char *a1, a2;
- a1 = inet_ntoa(ina1.sin_addr); /* this is 192.168.1.65 */
- a2 = inet_ntoa(ina2.sin_addr); /* this is 192.168.1.227 */
-
- printf(“address 1: %s”,a1);
- printf(“address 2: %s”,a2);
点击(此处)折叠或打开
- address 1: 166.111.69.227
- address 2: 166.111.69.227
3.解决方案
接下来就好办了,如果需要把结果保存下来,那么可以在每次调用inet_ntoa函数后调用strcpy函数将结果存到自定义的字符串中。修改输出日志的代码,如下:
点击(此处)折叠或打开
- char *a1;
- char *a2;
- strcpy(a1,inet_ntoa(udpConnInfo[pos].destAddr.sin_addr));
- strcpy(a2,inet_ntoa(myAddrIn));
- TraceLog::Trace(TLL_DEBUG, "svrIp:%s svrport:%d clientIp:%s clientport:%d send data to net",
- a1, udpConnInfo[pos].peerPort, a2,udpConnInfo[pos].localPort);
输出日志的 结果如下:
点击(此处)折叠或打开
- svrIp:192.168.1.65 svrport:11151 clientIp:192.168.1.227 clientport:8080 send data to net
~~~~~~~ the end~~~~~~~~~
hoegh
2017.10.27
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/30162081/viewspace-2146519/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/30162081/viewspace-2146519/