mirror of
https://github.com/JulianGro/overte.git
synced 2025-04-25 18:35:04 +02:00
use Qt to query interfaces for correct local address
This commit is contained in:
parent
e40ab5d13f
commit
330e78920a
1 changed files with 27 additions and 25 deletions
|
@ -22,6 +22,8 @@
|
|||
#endif
|
||||
|
||||
#include <QtCore/QDebug>
|
||||
#include <QtNetwork/QNetworkInterface>
|
||||
#include <QtNetwork/QHostAddress>
|
||||
|
||||
#include "Logging.h"
|
||||
#include "UDPSocket.h"
|
||||
|
@ -88,35 +90,35 @@ void copySocketToEmptySocketPointer(sockaddr** destination, const sockaddr* sour
|
|||
}
|
||||
|
||||
int getLocalAddress() {
|
||||
// get this node's local address so we can pass that to DS
|
||||
struct ifaddrs* ifAddrStruct = NULL;
|
||||
struct ifaddrs* ifa = NULL;
|
||||
|
||||
int family;
|
||||
int localAddress = 0;
|
||||
|
||||
#ifndef _WIN32
|
||||
getifaddrs(&ifAddrStruct);
|
||||
|
||||
for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) {
|
||||
family = ifa->ifa_addr->sa_family;
|
||||
if (family == AF_INET) {
|
||||
localAddress = ((sockaddr_in *)ifa->ifa_addr)->sin_addr.s_addr;
|
||||
static int localAddress = 0;
|
||||
|
||||
if (localAddress == 0) {
|
||||
foreach(const QNetworkInterface &interface, QNetworkInterface::allInterfaces()) {
|
||||
if (interface.flags() & QNetworkInterface::IsUp
|
||||
&& interface.flags() & QNetworkInterface::IsRunning
|
||||
&& interface.flags() & ~QNetworkInterface::IsLoopBack) {
|
||||
// we've decided that this is the active NIC
|
||||
// enumerate it's addresses to grab the IPv4 address
|
||||
foreach(const QNetworkAddressEntry &entry, interface.addressEntries()) {
|
||||
// make sure it's an IPv4 address that isn't the loopback
|
||||
if (entry.ip().protocol() == QAbstractSocket::IPv4Protocol && !entry.ip().isLoopback()) {
|
||||
qDebug("Node's local address is %s\n", entry.ip().toString().toLocal8Bit().constData());
|
||||
|
||||
// set our localAddress and break out
|
||||
localAddress = htonl(entry.ip().toIPv4Address());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (localAddress != 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
freeifaddrs(ifAddrStruct);
|
||||
#else
|
||||
// Get the local hostname
|
||||
char szHostName[255];
|
||||
gethostname(szHostName, 255);
|
||||
struct hostent *host_entry;
|
||||
host_entry = gethostbyname(szHostName);
|
||||
char * szLocalIP;
|
||||
szLocalIP = inet_ntoa (*(struct in_addr *)*host_entry->h_addr_list);
|
||||
localAddress = inet_addr(szLocalIP);
|
||||
#endif
|
||||
|
||||
// return the looked up local address
|
||||
return localAddress;
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in a new issue