Qt 中获取本机IP地址


想在Qt界面上显示获取的ip地址,查了一下Qt的帮助资料,实现也相对简单,帮助文档中说明如下,还有其他更多的函数也没有细看,先用着再说。

Qt 的详细介绍:请点这里
Qt 的下载地址:请点这里

推荐阅读:

Ubuntu 环境下Gtk与QT编译环境安装与配置

Linux系统下QT环境搭建

Ubuntu下QT控制台程序无法运行的解决方案以及XTerm的配置方法

Ubuntu 10.04下QT4.7.4移植详解

Linux下为刚安装好的Qt Creator 创建桌面启动图标

Ubuntu 11.04安装QT Creator 2.5.0

Qt creator for PlayBook安装过程

 

QList<QHostAddress> QNetworkInterface::allAddresses () [static]
This convenience function returns all IP addresses found on the host machine. It is equivalent to calling addressEntries() on all the objects returned by allInterfaces() to obtain lists of QHostAddress objects then calling QHostAddress::ip() on each of these.

程序中使用一个label来显示获取的ip,程序如下:

#include <QNetworkInterface>

ui->iplabel->setText(QNetworkInterface().allAddresses().at(0).toString());

编译出错,需要在工程pro文件中添加,在

QT += core gui network

后添加network,正常运行,这是显示的ip可能不一定是你想要的网卡,如显示的是127.0.0.1,可以更改QNetworkInterface().allAddresses().at(1).toString() 中 at 括号中的值,最开始在开发板上用at(2)调试时,出现如下错误:

ASSERT failure in QList<T>::at: "index out of range", file /usr/local/Trolltech/QtEmbedded-4.8.4-arm/include/QtCore/qlist.h, line 469

本来以为我移植的4.8.4的库不全,重新弄了遍还是不对,后来想想QLinst越界,可能就是这儿值越界了,更改后问题解决。

相关内容