192.168.1.49
有没有一种跨平台的方式来获取使用 Qt 的计算机的本地 IP 地址(即看起来像的东西)?
我想为 Symbian 手机制作一个 FTP 服务器,并且我想显示 FTP 客户端应该连接的 IP 地址。
使用QNetworkInterface::allAddresses()
const QHostAddress &localhost = QHostAddress(QHostAddress::LocalHost);
for (const QHostAddress &address: QNetworkInterface::allAddresses()) {
if (address.protocol() == QAbstractSocket::IPv4Protocol && address != localhost)
qDebug() << address.toString();
}
QNetworkInterface::allAddresses()
会给你网络地址。然后,您可以将结果过滤到不是环回地址的 IPv4 地址:
QList<QHostAddress> list = QNetworkInterface::allAddresses();
for(int nIter=0; nIter<list.count(); nIter++)
{
if(!list[nIter].isLoopback())
if (list[nIter].protocol() == QAbstractSocket::IPv4Protocol )
qDebug() << list[nIter].toString();
}
如果您需要的信息不仅仅是 IP 地址(如子网),则必须遍历所有接口。
QList<QNetworkInterface> allInterfaces = QNetworkInterface::allInterfaces();
QNetworkInterface eth;
foreach(eth, allInterfaces) {
QList<QNetworkAddressEntry> allEntries = eth.addressEntries();
QNetworkAddressEntry entry;
foreach (entry, allEntries) {
qDebug() << entry.ip().toString() << "/" << entry.netmask().toString();
}
}
QNetworkInterface 返回很多地址。您必须过滤它们,以获得理想的结果:
foreach (const QNetworkInterface &netInterface, QNetworkInterface::allInterfaces()) {
QNetworkInterface::InterfaceFlags flags = netInterface.flags();
if( (bool)(flags & QNetworkInterface::IsRunning) && !(bool)(flags & QNetworkInterface::IsLoopBack)){
foreach (const QNetworkAddressEntry &address, netInterface.addressEntries()) {
if(address.ip().protocol() == QAbstractSocket::IPv4Protocol)
qDebug() << address.ip().toString();
}
}
}
这是我实现获取的代码:本地主机的名称、IP、网络掩码和 MAC 地址。
QString localhostname = QHostInfo::localHostName();
QString localhostIP;
QList<QHostAddress> hostList = QHostInfo::fromName(localhostname).addresses();
foreach (const QHostAddress& address, hostList) {
if (address.protocol() == QAbstractSocket::IPv4Protocol && address.isLoopback() == false) {
localhostIP = address.toString();
}
}
QString localMacAddress;
QString localNetmask;
foreach (const QNetworkInterface& networkInterface, QNetworkInterface::allInterfaces()) {
foreach (const QNetworkAddressEntry& entry, networkInterface.addressEntries()) {
if (entry.ip().toString() == localhostIP) {
localMacAddress = networkInterface.hardwareAddress();
localNetmask = entry.netmask().toString();
break;
}
}
}
qDebug() << "Localhost name: " << localhostname;
qDebug() << "IP = " << localhostIP;
qDebug() << "MAC = " << localMacAddress;
qDebug() << "Netmask = " << localNetmask;
我想获取eth1
目标机器的 IP 地址。上面提供的答案帮助我得到了我想要的:这就是我编写函数来获取网络接口名称的 IP 地址的方式eth1
。
QNetworkInterface eth1Ip = QNetworkInterface::interfaceFromName("eth1");
QList<QNetworkAddressEntry> entries = eth1Ip.addressEntries();
if (!entries.isEmpty()) {
QNetworkAddressEntry entry = entries.first();
qDebug() << entry.ip();
}