How Qt obtains the local IP address

Use QHostInfo in Qt to get the local IP address

	QString hostNme = QHostInfo::localHostName();
	QHostInfo hostInfo = QHostInfo::fromName(hostNme);
	auto addList = hostInfo.addresses();
	if (addList.isEmpty())
	{
    
    
		Q_ASSERT(false);
	}
	for (int i = 0;i < addList.count();++i)
	{
    
    
		QHostAddress hostAddress = addList.at(i);
		auto ipAddr = hostAddress.toString();
	
	}

note

  • VS needs to check the network module and
    right-click the VS project. Select Qt Project Settings. Switch to the Qt Modules page and check NetWork
    Insert picture description here
  • The
    QString hostNme = QHostInfo::localHostName();
    hostName variable in the above code is the computer name. And when the computer name is Chinese , the IP address cannot be resolved.

Guess you like

Origin blog.csdn.net/weixin_39308337/article/details/106451152