#include <winsock2.h>
#include <stdio.h>
#pragma comment( lib, "ws2_32.lib" )
struct sockaddr_in server_addr;
struct sockaddr_in client_addr;
int main(void)
{
long a = 0x102030FF;
long b = 0x405060FF;
memcpy((char *)&server_addr.sin_addr, (char *)&a, sizeof(server_addr.sin_addr));
memcpy((char *)&client_addr.sin_addr, (char *)&b, sizeof(client_addr.sin_addr));
printf("server:%s\n", inet_ntoa(server_addr.sin_addr));
printf("client:%s\n", inet_ntoa(client_addr.sin_addr));
printf("server:%s\nclient:%s\n",
inet_ntoa(server_addr.sin_addr), inet_ntoa(client_addr.sin_addr));
printf("server:%s\nclient:%s\n",
inet_ntoa(client_addr.sin_addr), inet_ntoa(server_addr.sin_addr));
return 0;
}
#include <stdio.h>
#pragma comment( lib, "ws2_32.lib" )
struct sockaddr_in server_addr;
struct sockaddr_in client_addr;
int main(void)
{
long a = 0x102030FF;
long b = 0x405060FF;
memcpy((char *)&server_addr.sin_addr, (char *)&a, sizeof(server_addr.sin_addr));
memcpy((char *)&client_addr.sin_addr, (char *)&b, sizeof(client_addr.sin_addr));
printf("server:%s\n", inet_ntoa(server_addr.sin_addr));
printf("client:%s\n", inet_ntoa(client_addr.sin_addr));
printf("server:%s\nclient:%s\n",
inet_ntoa(server_addr.sin_addr), inet_ntoa(client_addr.sin_addr));
printf("server:%s\nclient:%s\n",
inet_ntoa(client_addr.sin_addr), inet_ntoa(server_addr.sin_addr));
return 0;
}
运行结果如下
server:255.48.32.16
client:255.96.80.64
server:255.48.32.16
client:255.48.32.16
server:255.96.80.64
client:255.96.80.64
分别打印server和client的地址,得到正确的值,但是使用同一条printf语句打印却出现错误。
其中的原因是inet_ntoa返回值存储在一块静态空间中,第二次调用的返回值会覆盖第一次的结果,printf的是从右往左计算参数,所以会出现打印相同地址的情况。