Getting Host's IP addresses and Interfaces

From Qt Wiki
Jump to navigation Jump to search

Template:Abstract

Template:ArticleMetaData

Functions[edit | edit source]

  • This convenience function returns all IP addresses found on the host machine.

QNetworkInterface *inter=new QNetWorkInterface();
inter->allAddresses();

  • Returns a listing of all the network interfaces found on the host machine.

QNetworkInterface *inter=new QNetWorkInterface();
inter->allInterfaces();

Source Code[edit | edit source]

Header File[edit | edit source]

  1. ifndef NET_H
  2. define NET_H
  1. include <QtGui/QWidget>
  2. include<QNetworkInterface>
  3. include<QList>
  4. include<QLabel>
  5. include<QHBoxLayout>
  6. include<QString>
  7. include<QHostAddress>
  8. include<QListWidget>

namespace Ui {

   class netClass;

}

class net : public QWidget {

   Q_OBJECT

public:

   net(QWidget *parent = 0);
   ~net();

private:

   QNetworkInterface *inter;
   QLabel *lbl;
   QHBoxLayout *lay;
   QListWidget *item;

};

  1. endif // NET_H

Source File[edit | edit source]

  1. include "net.h"
  2. include "ui_net.h"

net::net(QWidget *parent)

   : QWidget(parent)

{

 QList<QHostAddress> list;
  lbl=new QLabel(this);
  lay=new QHBoxLayout(this);
  item=new QListWidget(this);
 inter=new QNetworkInterface();
  list=inter->allAddresses();
   QString str;

for (int i = 0; i < list.size(); ++i) {

 str = list.at(i).toString();
 item->addItem(str);

}

  lay->addWidget(item);
  setLayout(lay);

}

net::~net() {

// No need to delete any object that got a parent that is properly deleted.
delete inter;

}

Source File for getting network Interface[edit | edit source]

  1. include "net.h"
  2. include "ui_net.h"

net::net(QWidget *parent)

   : QWidget(parent)

{

 QList<QNetworkInterface> list;
  lbl=new QLabel(this);
  lay=new QHBoxLayout(this);
  item=new QListWidget(this);
 inter=new QNetworkInterface();
  list=inter->allInterfaces();
   QString str;

for (int i = 0; i < list.size(); ++i) {

 str = list.at(i).name();
 item->addItem(str);

}

  lay->addWidget(item);
  setLayout(lay);

}

net::~net() {

delete inter;

}

Screenshot[edit | edit source]

  • Showing Host IP's

File:Network.JPG

  • Showing Network Interface

File:Interface.JPG

The code example could be found at: File:Net.zip