我是网络编程的新手,所以我不确定这是否是正确的问题,但是我想使用C ++编写服务器程序(我使用的是Qt。)我使用了“财富服务器”示例创建一个简单的服务器,您可以通过输入服务器显示的IP地址来与客户端连接。如果输入本地主机(127.0.0.1),则可以连接,但是服务器说正在运行的地址是169.254.253.67,我发现它是另一个本地地址(也无法连接到它)。我运行服务器,所以它不在本地地址上吗?

这是我使用的示例:
http://doc.qt.digia.com/qt/network-fortuneserver.html

最佳答案

服务器实现获取所有发现的IP地址的列表,然后找到第一个非本地IP。否则,它默认使用本地主机。如果您看到本地主机地址,则表明您的网络中未设置正确的内容,并且Qt无法确定LAN ip。

正如@drescherjm在注释中建议的那样,您可以通过0.0.0.0显式侦听所有接口。要查看此操作的实际效果,您只需要在通过ipAddress字符串设置状态标签之前添加一行即可:

// add this to force the socket to listen on all interfaces
ipAddress = QHostAddress("0.0.0.0").toString();
// or if you have a local static ip and want to be explicit
// ipAddress = QHostAddress("192.168.xxx.xxx").toString();

// followed by the already existing line for setting the text
statusLabel->setText(tr("The server is running on\n\nIP: %1\nport: %2\n\n"
                        "Run the Fortune Client example now.")
                     .arg(ipAddress).arg(tcpServer->serverPort()));


现在,如果您的网络设置正确,则任何其他可以看到运行服务器应用程序的计算机都应该可以在给定的端口上进行连接。

10-08 08:17
查看更多