在c++ (Qt)中设置一个非本地IP地址的服务器

Setting up a server with a non-local IP address in C++ (Qt)

本文关键字:IP 地址 服务器 Qt c++ 设置 一个      更新时间:2023-10-16

我是网络编程的新手,所以我不确定这真的是正确的问题,但我想用c++制作一个服务器程序(我使用Qt.)我使用了"财富服务器"的例子,它创建了一个简单的服务器,您可以通过输入服务器显示的IP地址与客户端连接。如果我输入localhost(127.0.0.1),我可以连接,但是服务器说它运行的地址是169.254.253.67,我发现这是另一个本地地址(我也无法连接到它)。我如何运行服务器,使其不在本地地址上?

下面是我用的例子:http://doc.qt.digia.com/qt/network-fortuneserver.html

服务器实现获得所有发现的ip地址的列表,然后找到第一个非本地ip。否则,默认使用localhost。如果您看到的是本地主机地址,则表明您的网络中没有正确设置,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 onnnIP: %1nport: %2nn"
                        "Run the Fortune Client example now.")
                     .arg(ipAddress).arg(tcpServer->serverPort()));

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