为什么inet_ntoa总是返回错误的IP地址(套接字编程公司)

时间:2019-04-08 11:24:00

标签: c sockets server ip client

我有一个带有套接字的简单客户端/服务器应用程序,因此客户端使用服务器ip连接到服务器,我想返回具有inet_ntoa的已连接客户端的ip,但它始终返回已连接客户端的错误ip。为什么呢?以及解决方法。

我希望服务器返回连接的机器的真实IP,以便稍后扫描打开的端口

1 个答案:

答案 0 :(得分:2)

struct sockaddr_in addr_remote;
...
connfd = accept(sockfd, (SA*)&cli, &len); 
...
printf( " Welcome %s " , inet_ntoa(addr_remote.sin_addr));

您将inet_ntoaaddr_remote一起使用。 addr_remote从未在您的代码中设置,因此其内容是无法预测的。您可能打算在addr_remote中使用accept,但是在那里使用了cli