本博客为本人学生时代的技术博客,工作后10年已经不再更新,需要关注可以访问geekpm.com,点击访问!

Qt 中获取本机IP地址

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

 

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越界,可能就是这儿值越界了,更改后问题解决。

posted @ 2013-04-20 14:19  emouse  阅读(14972)  评论(0编辑  收藏  举报