PDA

View Full Version : Get current ip address



Trok
16th March 2009, 16:49
Hi, I have problem with ip address.
How can i get current ip address on my pc? I tried used this code:



QHostInfo info;
QNetworkInterface ifObj = QNetworkInterface::interfaceFromName(info.hostName ());
qDebug() << ifObj;

It was returned:


QNetworkInterface( name = "", hardware address = "", flags = , entrise = () )

also I used function: QNetworkAddressEntry::ip () , but without results.

So, I wait for yours propositions to solve my problem.

Lykurg
16th March 2009, 18:26
Hi, nice to have you here. In this forum is a wonderful function: the search engine: Look here (http://www.qtcentre.org/forum/f-qt-programming-2/t-ip-address-find-18953.html/?highlight=address) for example.

Trok
16th March 2009, 21:52
Hi, i saw that topic, Lykurg. First method is for Linux system, whilst second is wrong. I search functions to use for Windows. :)

I wait for more suggestions about my problem.

Lykurg
16th March 2009, 23:05
QList<QHostAddress> list = QNetworkInterface::allAddresses();
gives you all addresses on your computer. if you also want bcst and mask use QNetworkAddressEntry with its functions broadcast and netmask.

Trok
16th March 2009, 23:52
That's good, but I have next problem. I don't see my general address whilst I see addresses to my router. I don't know how I can solve this problem. Do you have some ideas?

PS. Functions in class QNetworkAddressEntry are useless, because return 0. I don't know why?

BastiBense
17th March 2009, 00:08
That's good, but I have next problem. I don't see my general address whilst I see addresses to my router. I don't know how I can solve this problem. Do you have some ideas?

PS. Functions in class QNetworkAddressEntry are useless, because return 0. I don't know why?

There is no such thing as a "main address". There is just a default route that specifies a device to use (on all operating systems). I think one way to find out which your "primary" device is, is to use use a QTcpSocket and have it "connect" to a possibly non-existing address that is not on the local network, then use QAbstractSocket's localAddress() which returns a QHostAddress, which in turn contains the IP of the local interface. After that you can then find ouch wich interface has the said IP by searching through the list of QNetworkInterfaces.

I think there might be a easier way to find out which is your default network interface, but those approaches possibly require a linux/windows shell and are not platform independent.