Get Local Ip Address in Qt

Get local IP address in Qt

Use QNetworkInterface::allAddresses()

const QHostAddress &localhost = QHostAddress(QHostAddress::LocalHost);
for (const QHostAddress &address: QNetworkInterface::allAddresses()) {
if (address.protocol() == QAbstractSocket::IPv4Protocol && address != localhost)
qDebug() << address.toString();
}

How to get local IP address of a computer using QT

PCs often have more than one IP address. There's not really such a thing as "the" local IP address; the IP address which would be used when connecting to some remote host depends at least on the local routing table (which may change drastically at any time, e.g. when starting/stopping VPN software).

It seems to me that it makes more sense to think about IPs as valid only in the context of remote networks, e.g. "this is the local IP address I'd use if I were to connect to this host on the Internet; but this is the local IP address I'd use to connect to this host over my company's VPN".

If you want to find out the local IP address which would be used for general-purpose Internet connectivity, the most accurate way I know is simply to do a connection test to a representative host (and a host with high reliability!)

QTcpSocket socket;
socket.connectToHost("8.8.8.8", 53); // google DNS, or something else reliable
if (socket.waitForConnected()) {
qDebug()
<< "local IPv4 address for Internet connectivity is"
<< socket.localAddress();
} else {
qWarning()
<< "could not determine local IPv4 address:"
<< socket.errorString();
}

Note: the above example is blocking, you probably want to rewrite it to use signals and slots if your app has a UI.

How to get your public ip address using Qt c++

I think the class you are looking for is the QNetworkInterface class.

From the man page:

The QNetworkInterface class provides a listing of the host's IP
addresses and network interfaces.

For example, calling QNetworkInterface::allAddresses() is a quick way to get a list of all the IP addresses on your machine. As for which one is the "public IP address", that's not a well-defined concept. On most modern consumer setups, it's arguable that there is no public IP address, as consumer PCs are typically hidden behind a NAT layer, and as such the only public IP address is on the network router, not on the user's computer itself.

How to get the ip address in qt/linux?

This might be a solution for you

IPAddress FindLocalIPAddressOfIncomingPacket( senderAddr )
{
foreach( adapter in EnumAllNetworkAdapters() )
{
adapterSubnet = adapter.subnetmask & adapter.ipaddress;
senderSubnet = adapter.subnetmask & senderAddr;
if( adapterSubnet == senderSubnet )
{
return adapter.ipaddress;
}
}
}

How to get your own (local) IP-Address from an udp-socket (C/C++)


In order to get the incoming peer IP address you can use following solution in C

socklen_t len;
struct sockaddr_storage addr;
char ipstr[INET6_ADDRSTRLEN];
int port;

len = sizeof addr;
getpeername(s, (struct sockaddr*)&addr, &len);

// deal with both IPv4 and IPv6:
if (addr.ss_family == AF_INET) {
struct sockaddr_in *s = (struct sockaddr_in *)&addr;
port = ntohs(s->sin_port);
inet_ntop(AF_INET, &s->sin_addr, ipstr, sizeof ipstr);
} else { // AF_INET6
struct sockaddr_in6 *s = (struct sockaddr_in6 *)&addr;
port = ntohs(s->sin6_port);
inet_ntop(AF_INET6, &s->sin6_addr, ipstr, sizeof ipstr);
}

printf("Peer IP address: %s\n", ipstr);

Getting the source address of an incoming socket connection

How to check if network address is local in Qt

I can use QHostInfo to lookup IP address, but in this case I would have to wait for DNS server's response.

QHostInfo uses the platform-specific name resolution mechanism. It might not use DNS at all. If the hostname of a local interface is in the hosts file, and the name resolution is configured to use it, then QHostInfo will resolve the local interface's address that way. Otherwise, it'll do a name server query, iff the platform is configured to resolve names that way.

The most you can do is to check QHostAddress::isLoopback(), then check if it's one of QNetworkInterface::allAddresses().

If your address is not an IP address, and it's not equal to QHostInfo::localHostName(), then you have to obtain one first using QHostInfo::lookupHost. If it's a local interface's name, listed in the hosts file or a similar local resolution mechanism, it will be returned quickly. You can set a short timeout (say 100ms), and if there's no lookup result available by then, you can assume that it's not a local interface.

Here's an example:

// https://github.com/KubaO/stackoverflown/tree/master/questions/host-lookup-36319049
#include <QtWidgets>
#include <QtNetwork>

class IfLookup : public QObject {
Q_OBJECT
int m_id;
QTimer m_timer;
void abort() {
if (m_timer.isActive())
QHostInfo::abortHostLookup(m_id);
m_timer.stop();
}
Q_SLOT void lookupResult(const QHostInfo & host) {
m_timer.stop();
if (host.error() != QHostInfo::NoError)
return hasResult(Error);
for (auto ifAddr : QNetworkInterface::allAddresses())
if (host.addresses().contains(ifAddr))
return hasResult(Local);
return hasResult(NonLocal);
}
public:
enum Result { Local, NonLocal, TimedOut, Error };
IfLookup(QObject * parent = 0) : QObject(parent) {
connect(&m_timer, &QTimer::timeout, this, [this]{
abort();
emit hasResult(TimedOut);
});
}
Q_SIGNAL void hasResult(Result);
Q_SLOT void lookup(QString name) {
abort();
name = name.trimmed().toUpper();
QHostAddress addr(name);
if (!addr.isNull()) {
if (addr.isLoopback() || QNetworkInterface::allAddresses().contains(addr))
return hasResult(Local);
return hasResult(NonLocal);
}
if (QHostInfo::localHostName() == name)
return hasResult(Local);
m_id = QHostInfo::lookupHost(name, this, SLOT(lookupResult(QHostInfo)));
m_timer.start(500);
}
};

int main(int argc, char ** argv) {
QApplication app{argc, argv};
QWidget w;
QFormLayout layout{&w};
QLineEdit address;
layout.addRow("Address to look up", &address);
QLabel result;
layout.addRow("Result", &result);
QPushButton lookup{"Lookup"};
layout.addRow(&lookup);
lookup.setDefault(true);
w.show();

IfLookup ifLookup;
QObject::connect(&lookup, &QPushButton::clicked, [&]{
result.clear();
ifLookup.lookup(address.text());
});
QObject::connect(&ifLookup, &IfLookup::hasResult, [&](IfLookup::Result r){
static const QMap<IfLookup::Result, QString> msgs = {
{ IfLookup::Local, "Local" }, { IfLookup::NonLocal, "Non-Local" },
{ IfLookup::TimedOut, "Timed Out" }, { IfLookup::Error, "Lookup Error" }
};
result.setText(msgs.value(r));
});

return app.exec();
}

#include "main.moc"

Qt get external IP address using QNetworkReply

The problem is that you are sending a POST request, while ipify.org expects only GET requests. You seem to have the misconception that you need to be sending a POST request in order to be able to send parameters (format=json) along with your request, this is not true. In your code, you are sending the parameters as POST data, this is the same technique that is used when you submit a web form in your browser (because you are setting the content type header to application/x-www-form-urlencoded).

You absolutely don't need to mimic the request of a web browser sending a form in order to be able to talk to the API ipify.org provides. ipify.org provides a much simpler interface; you just need to send your query string in your get request. Qt makes the job even easier by providing the class QUrlQuery that provides a way to build url queries. Here is a working example:

#include <QtCore>
#include <QtNetwork>

int main(int argc, char *argv[]) {
QCoreApplication a(argc, argv);

QNetworkAccessManager networkManager;

QUrl url("https://api.ipify.org");
//the query used to add the parameter "format=json" to the request
QUrlQuery query;
query.addQueryItem("format", "json");
//set the query on the url
url.setQuery(query);

//make a *get* request using the above url
QNetworkReply* reply = networkManager.get(QNetworkRequest(url));

QObject::connect(reply, &QNetworkReply::finished,
[&](){
if(reply->error() != QNetworkReply::NoError) {
//failure
qDebug() << "error: " << reply->error();
} else { //success
//parse the json reply to extract the IP address
QJsonObject jsonObject= QJsonDocument::fromJson(reply->readAll()).object();
QHostAddress ip(jsonObject["ip"].toString());
//do whatever you want with the ip
qDebug() << "external ip: " << ip;
}
//delete reply later to prevent memory leak
reply->deleteLater();
a.quit();
});
return a.exec();
}

C++ / Qt: How can I detect when a hostname or IP address refers to the current system?

QNetworkInterface class should provide the most information you may need.
You can obtain a list of IP addresses using QNetworkInterface::allAddresses() static function.

You can also get a list of all interfaces using QNetworkInterface::allInterfaces().

Calling QNetworkInterface::addressEntries() for each QNetworkInterface returned by QNetworkInterface::allInterfaces() will give you more information about address entries for each interface.

auto ifs = QNetworkInterface::allInterfaces();
foreach (auto interface , ifs){
auto addresses = interface.addressEntries();
foreach ( auto addy , addresses){
///play with the addy here.
}
}

You can also test hostnames against those ip addresses which you are going to ban, using QDnsLookup class.



Related Topics



Leave a reply



Submit