void setPortAndAddress(quint16 port, const QHostAddress &address, QAbstractSocket::NetworkLayerProtocol socketProtocol, qt_sockaddr *aa, int *sockAddrSize)
{
    if (address.protocol() == QAbstractSocket::IPv6Protocol
        || address.protocol() == QAbstractSocket::AnyIPProtocol
        || socketProtocol == QAbstractSocket::IPv6Protocol
        || socketProtocol == QAbstractSocket::AnyIPProtocol) {
        memset(&aa->a6, 0, sizeof(sockaddr_in6));
        aa->a6.sin6_family = AF_INET6;
//#if QT_CONFIG(networkinterface)
//            aa->a6.sin6_scope_id = scopeIdFromString(address.scopeId());
//#endif
        aa->a6.sin6_port = htons(port);
        Q_IPV6ADDR tmp = address.toIPv6Address();
        memcpy(&aa->a6.sin6_addr, &tmp, sizeof(tmp));
        *sockAddrSize = sizeof(sockaddr_in6);
        SetSALen::set(&aa->a, sizeof(sockaddr_in6));
    } else {
        memset(&aa->a, 0, sizeof(sockaddr_in));
        aa->a4.sin_family = AF_INET;
        aa->a4.sin_port = htons(port);
        aa->a4.sin_addr.s_addr = htonl(address.toIPv4Address());
        *sockAddrSize = sizeof(sockaddr_in);
        SetSALen::set(&aa->a, sizeof(sockaddr_in));
    }
}
Beispiel #2
0
// connectRequest
static QByteArray sp_set_request(const QHostAddress &addr, unsigned short port, unsigned char cmd1)
{
    int at = 0;
    QByteArray a;
    a.resize(4);
    a[at++] = 0x05; // socks version 5
    a[at++] = cmd1;
    a[at++] = 0x00; // reserved
    if(addr.protocol() == QAbstractSocket::IPv4Protocol || addr.protocol() == QAbstractSocket::UnknownNetworkLayerProtocol) {
        a[at++] = 0x01; // address type = ipv4
        quint32 ip4 = htonl(addr.toIPv4Address());
        a.resize(at+4);
        memcpy(a.data() + at, &ip4, 4);
        at += 4;
    }
    else {
        a[at++] = 0x04;
        Q_IPV6ADDR ip6 = addr.toIPv6Address();
        a.resize(at+16);
        for(int i = 0; i < 16; ++i)
            a[at++] = ip6[i];
    }

    // port
    a.resize(at+2);
    quint16 p = htons(port);
    memcpy(a.data() + at, &p, 2);

    return a;
}
/*! \internal

    Sets the port and address to a sockaddr. Requires that sa point to the IPv6 struct if the address is IPv6.
*/
static inline void qt_socket_setPortAndAddress(SOCKET socketDescriptor, sockaddr_in * sockAddrIPv4, qt_sockaddr_in6 * sockAddrIPv6,
                                               quint16 port, const QHostAddress & address, sockaddr ** sockAddrPtr, QT_SOCKLEN_T *sockAddrSize)
{
#if !defined(QT_NO_IPV6)
    if (address.protocol() == QAbstractSocket::IPv6Protocol) {
        memset(sockAddrIPv6, 0, sizeof(qt_sockaddr_in6));
        sockAddrIPv6->sin6_family = AF_INET6;
        sockAddrIPv6->sin6_scope_id = address.scopeId().toInt();
        WSAHtons(socketDescriptor, port, &(sockAddrIPv6->sin6_port));
        Q_IPV6ADDR tmp = address.toIPv6Address();
        memcpy(&(sockAddrIPv6->sin6_addr.qt_s6_addr), &tmp, sizeof(tmp));
        *sockAddrSize = sizeof(qt_sockaddr_in6);
        *sockAddrPtr = (struct sockaddr *) sockAddrIPv6;
    } else
#endif
    if (address.protocol() == QAbstractSocket::IPv4Protocol
        || address.protocol() == QAbstractSocket::UnknownNetworkLayerProtocol) {
        memset(sockAddrIPv4, 0, sizeof(sockaddr_in));
        sockAddrIPv4->sin_family = AF_INET;
        WSAHtons(socketDescriptor, port, &(sockAddrIPv4->sin_port));
        WSAHtonl(socketDescriptor, address.toIPv4Address(), &(sockAddrIPv4->sin_addr.s_addr));
        *sockAddrSize = sizeof(sockaddr_in);
        *sockAddrPtr = (struct sockaddr *) sockAddrIPv4;
    } else {
        // unreachable
    }
}
qint64 QNativeSocketEnginePrivate::nativeSendDatagram(const char *data, qint64 len,
                                                   const QHostAddress &host, quint16 port)
{
    struct sockaddr_in sockAddrIPv4;
    struct sockaddr *sockAddrPtr = 0;
    QT_SOCKLEN_T sockAddrSize = 0;

#if !defined(QT_NO_IPV6)
    struct sockaddr_in6 sockAddrIPv6;
    if (host.protocol() == QAbstractSocket::IPv6Protocol) {
        memset(&sockAddrIPv6, 0, sizeof(sockAddrIPv6));
        sockAddrIPv6.sin6_family = AF_INET6;
        sockAddrIPv6.sin6_port = htons(port);

        Q_IPV6ADDR tmp = host.toIPv6Address();
        memcpy(&sockAddrIPv6.sin6_addr.s6_addr, &tmp, sizeof(tmp));
        QString scopeid = host.scopeId();
        bool ok;
        sockAddrIPv6.sin6_scope_id = scopeid.toInt(&ok);
#ifndef QT_NO_IPV6IFNAME
        if (!ok)
            sockAddrIPv6.sin6_scope_id = ::if_nametoindex(scopeid.toLatin1());
#endif
        sockAddrSize = sizeof(sockAddrIPv6);
        sockAddrPtr = (struct sockaddr *)&sockAddrIPv6;
    } else
#endif
    if (host.protocol() == QAbstractSocket::IPv4Protocol) {
        memset(&sockAddrIPv4, 0, sizeof(sockAddrIPv4));
        sockAddrIPv4.sin_family = AF_INET;
        sockAddrIPv4.sin_port = htons(port);
        sockAddrIPv4.sin_addr.s_addr = htonl(host.toIPv4Address());
        sockAddrSize = sizeof(sockAddrIPv4);
        sockAddrPtr = (struct sockaddr *)&sockAddrIPv4;
    }

    // ignore the SIGPIPE signal
    qt_ignore_sigpipe();
    ssize_t sentBytes = qt_safe_sendto(socketDescriptor, data, len,
                                       0, sockAddrPtr, sockAddrSize);

    if (sentBytes < 0) {
        switch (errno) {
        case EMSGSIZE:
            setError(QAbstractSocket::DatagramTooLargeError, DatagramTooLargeErrorString);
            break;
        default:
            setError(QAbstractSocket::NetworkError, SendDatagramErrorString);
        }
    }

#if defined (QNATIVESOCKETENGINE_DEBUG)
    qDebug("QNativeSocketEngine::sendDatagram(%p \"%s\", %lli, \"%s\", %i) == %lli", data,
           qt_prettyDebug(data, qMin<int>(len, 16), len).data(), len, host.toString().toLatin1().constData(),
           port, (qint64) sentBytes);
#endif

    return qint64(sentBytes);
}
Beispiel #5
0
void Worker::targetConnectedHandler(void)
{
	this->m_target = new QTcpSocket(this);
	this->m_connector->assignTo(this->m_target);
	delete this->m_connector;
	this->m_connector = 0;

	union {
		quint32 v4;
		Q_IPV6ADDR v6;
		quint16 port;
		char ptr;
	} data;

	QByteArray response("\x05\x00\x00", 3);
	QHostAddress a;
	if (qobject_cast<QAbstractSocket*>(this->m_peer)) {
		a = (qobject_cast<QAbstractSocket*>(this->m_peer))->peerAddress();
	}

	if (a.protocol() == QAbstractSocket::IPv4Protocol) {
		response.append('\x01');
		data.v4 = qToBigEndian(a.toIPv4Address());
		response.append(QByteArray::fromRawData(&data.ptr, sizeof(data.v4)));
	}
	else if (a.protocol() == QAbstractSocket::IPv6Protocol) {
		response.append('\x04');
		data.v6 = a.toIPv6Address();
		response.append(QByteArray::fromRawData(&data.ptr, sizeof(data.v6)));
	}
	else {
		Q_ASSERT(false);
	}

	if (qobject_cast<QAbstractSocket*>(this->m_peer)) {
		data.port = qToBigEndian<quint16>((qobject_cast<QAbstractSocket*>(this->m_peer))->peerPort());
	}
	else {
		data.port = 0;
	}

	response.append(QByteArray::fromRawData(&data.ptr, sizeof(data.port)));

	QObject::connect(this->m_target, SIGNAL(readyRead()), this, SLOT(targetReadyReadHandler()));
	QObject::connect(this->m_target, SIGNAL(disconnected()), this, SLOT(disconnectHandler()));

	if (this->writeAndFlush(this->m_peer, response) == response.size()) {
		this->m_state = Worker::ConnectionProxiedState;
	}
	else {
		if (this->m_peer) {
			this->m_peer->close();
		}

		this->m_state = Worker::FatalErrorState;
	}
}
Beispiel #6
0
  void SocksConnection::WriteSocksReply(SocksReplyCode reason, 
      const QHostAddress &addr, quint16 port) 
  {
    QHostAddress a = (addr.isNull() || addr.protocol() != QAbstractSocket::IPv4Protocol) 
      ? QHostAddress("8.8.8.8") : addr;

    QByteArray reply(4, 0);
    reply[0] = (uchar)SocksVersion_5; // Protocol version
    reply[1] = reason;  // Reply
    reply[2] = 0x00; // Reserved 
    reply[3] = SocksAddress_IPv4;     // Address type
    // reply[4] IP Octet 1
    // reply[5] IP Octet 2
    // reply[6] IP Octet 3
    // reply[7] IP Octet 3
    // reply[8] Port Octet 1
    // reply[9] Port Octet 1

    QDataStream stream(&reply, QIODevice::Append);
    stream.setByteOrder(QDataStream::BigEndian);

    stream << a.toIPv4Address();
    stream << port;

    for(int i=0;i<reply.count();i++) {
      qDebug() << "SOCKS reply" << i << "|" << (unsigned char)reply[i];
    }

    TryWrite(reply);
  }
void InternalCoreConnection::tryToConnectToTheNextAddress()
{
   if (this->addressesToTry.isEmpty())
      return;

   QHostAddress address;

   // Search for an IPv6 address first.
   for (QMutableListIterator<QHostAddress> i(this->addressesToTry); i.hasNext();)
   {
      QHostAddress currentAddress = i.next();
      if (currentAddress.protocol() == QAbstractSocket::IPv6Protocol)
      {
         address = currentAddress;
         i.remove();
         break;
      }
   }

   if (address.isNull())
      address = this->addressesToTry.takeFirst();

#ifndef DEBUG
   // If the address is local check if the core is launched, if not try to launch it.
   if (Global::isLocal(address))
      this->coreStatus = CoreController::StartCore();
#endif

   connect(this->socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(stateChanged(QAbstractSocket::SocketState)));
   this->socket->connectToHost(address, this->connectionInfo.port);
}
Beispiel #8
0
/*!
    Connects to the IP address and port specified by \a address and \a
    port. If the connection is established, this function returns true
    and the socket enters ConnectedState. Otherwise, false is
    returned.

    If false is returned, state() should be called to see if the
    socket is in ConnectingState. If so, a delayed TCP connection is
    taking place, and connectToHost() must be called again later to
    determine if the connection was established successfully or
    not. The second connection attempt must be made when the socket is
    ready for writing. This state can be determined either by
    connecting a QSocketNotifier to the socket descriptor returned by
    socketDescriptor(), or by calling the blocking function
    waitForWrite().

    Example:
    \snippet doc/src/snippets/code/src_network_socket_qnativesocketengine.cpp 0

    Otherwise, error() should be called to determine the cause of the
    error.
*/
bool QNativeSocketEngine::connectToHost(const QHostAddress &address, quint16 port)
{
    Q_D(QNativeSocketEngine);
    Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::connectToHost(), false);

#if defined (QT_NO_IPV6)
    if (address.protocol() == QAbstractSocket::IPv6Protocol) {
        d->setError(QAbstractSocket::UnsupportedSocketOperationError,
                    QNativeSocketEnginePrivate::NoIpV6ErrorString);
        return false;
    }
#endif
    if (!d->checkProxy(address))
        return false;

    Q_CHECK_STATES(QNativeSocketEngine::connectToHost(),
                   QAbstractSocket::UnconnectedState, QAbstractSocket::ConnectingState, false);

    d->peerAddress = address;
    d->peerPort = port;
    bool connected = d->nativeConnect(address, port);
    if (connected)
        d->fetchConnectionParameters();

    return connected;
}
Beispiel #9
0
void MainWindow::showCurrentIP()
{
    int count = 0;
    QString addrs = "";
    QList<QHostAddress> ips = QNetworkInterface::allAddresses();
    QListIterator<QHostAddress> i(ips);
    while (i.hasNext())
    {
        QHostAddress addr = i.next();
        if ((addr.protocol() == 0) && (addr.toString() != "127.0.0.1"))
        {
            count++;
            addrs += addr.toString() + ", ";
        }
    }
    if (count == 0)
        QMessageBox::critical(0, "", "Currently you don't have any IP address assigned");
    else {
        addrs = addrs.left(addrs.length() - 2);
        if (count == 1)
            QMessageBox::information(0, "", "Your current IP address is " + addrs);
        else
            QMessageBox::information(0, "", "Your current IP addresses are " + addrs);
    }
}
bool LimitedSocket::bindSocket(QAbstractSocket* sock, QHostAddress addr)
{
	if(addr.isNull())
		return true;
	
	int error;
	
	if(addr.protocol() == QAbstractSocket::IPv4Protocol)
	{
		sockaddr_in in;
		
		memset(&in, 0, sizeof(in));
		in.sin_addr.s_addr = addr.toIPv4Address();
		in.sin_family = AF_INET;
		
		error = ::bind(sock->socketDescriptor(), (sockaddr*) &in, sizeof(in));
	}
	else
	{
		sockaddr_in6 in6;
		
		Q_IPV6ADDR a = addr.toIPv6Address();
		memset(&in6, 0, sizeof(in6));
		memcpy(in6.sin6_addr.s6_addr, a.c, 16);
		in6.sin6_family = AF_INET6;
		
		error = ::bind(sock->socketDescriptor(), (sockaddr*) &in6, sizeof(in6));
	}
	
	return !error;
}
Beispiel #11
0
int listenReuse(const QHostAddress &address, quint16 port, bool startListening)
{
    QAbstractSocket::NetworkLayerProtocol proto = address.protocol();

    int socket = createNewSocket(proto);
    if (socket < 0) {
        qCCritical(CWSGI_BALANCER) << "Failed to create new socket";
        return -1;
    }

    int optval = 1;
    if (::setsockopt(socket, SOL_SOCKET, SO_REUSEPORT, &optval, sizeof(optval))) {
        qCCritical(CWSGI_BALANCER) << "Failed to set SO_REUSEPORT on socket" << socket;
        return -1;
    }

    if (!nativeBind(socket, address, port)) {
        qCCritical(CWSGI_BALANCER) << "Failed to bind to socket" << socket;
        return -1;
    }

    if (startListening && ::listen(socket, 100) < 0) {
        qCCritical(CWSGI_BALANCER) << "Failed to listen to socket" << socket;
        return -1;
    }

    return socket;
}
Beispiel #12
0
  bool SocksConnection::SerializeSocksAddress(const QString &host,
      quint16 port, QByteArray &socks_addr)
  {
    socks_addr.clear();
    QDataStream stream(&socks_addr, QIODevice::WriteOnly);

    QHostAddress addr;
    if(addr.setAddress(host)) {
      switch(addr.protocol()) {
        case QAbstractSocket::IPv4Protocol:
          stream << static_cast<quint8>(SocksAddress_IPv4);
          stream << addr.toIPv4Address();
          break;
        case QAbstractSocket::IPv6Protocol:
          stream << static_cast<quint8>(SocksAddress_IPv6);
          stream.writeRawData(reinterpret_cast<const char *>
              (addr.toIPv6Address().c), 16);
          break;
        default:
          stream << static_cast<quint8>(SocksAddress_Illegal);
      }
    } else {
      stream << static_cast<quint8>(SocksAddress_DomainName);
      stream << static_cast<quint8>(host.size());
      stream.writeRawData(host.toUtf8().constData(), host.size());
    }

    stream << port;
    return true;
  }
Beispiel #13
0
/*!
    Sets the netmask that this QNetworkAddressEntry object contains to
    \a newNetmask. Setting the netmask also sets the prefix length to
    match the new netmask.

    \sa setPrefixLength()
*/
void QNetworkAddressEntry::setNetmask(const QHostAddress &newNetmask)
{
    if (newNetmask.protocol() != ip().protocol()) {
        d->netmask = QNetmaskAddress();
        return;
    }

    d->netmask.setAddress(newNetmask);
}
Beispiel #14
0
///\brief Returns true if the address is accessible from other devices.
bool TorcNetwork::IsExternal(const QHostAddress &Address, bool IncludeLinkLocal /* = false*/)
{
    if (Address.isNull() || Address.isLoopback())
        return false;

    if (Address.isInSubnet(Address.protocol() == QAbstractSocket::IPv4Protocol ? gIPv4LinkLocal : gIPv6LinkLocal))
        return IncludeLinkLocal;

    return true;
}
Beispiel #15
0
QString Global::formatIP(const QHostAddress& address, quint16 port)
{
   QString formatedIP;
   if (address.protocol() == QAbstractSocket::IPv4Protocol)
      formatedIP.append(address.toString());
   else
      formatedIP.append("[").append(address.toString()).append("]");
   formatedIP.append(":").append(QString::number(port));
   return formatedIP;
}
Beispiel #16
0
HostAddress::HostAddress(const QHostAddress &address) {
	if (address.protocol() == QAbstractSocket::IPv6Protocol) {
		const Q_IPV6ADDR &a = address.toIPv6Address();
		memcpy(qip6.c, a.c, 16);
	} else {
		addr[0] = 0ULL;
		shorts[4] = 0;
		shorts[5] = 0xffff;
		hash[3] = htonl(address.toIPv4Address());
	}
}
Beispiel #17
0
    static bool contains(QNetworkAddressEntry host, QHostAddress addr)
    {
#if !defined(QT_NO_IPV6)
        if (addr.protocol() == QAbstractSocket::IPv6Protocol &&
            addr.isInSubnet(kLinkLocal6) &&
            host.ip().scopeId() != addr.scopeId())
        {
            return false;
        }
#endif
        return addr.isInSubnet(host.ip(), host.prefixLength());
    }
Beispiel #18
0
///Fonction auxiliaire pour appliquer les masques
QHostAddress operator&(const QHostAddress& network, const QHostAddress& netmask)
{
	if(network.isNull() || netmask.isNull() || network.protocol() != netmask.protocol())
		return QHostAddress();

	switch(network.protocol())
	{
		case QAbstractSocket::IPv4Protocol:
			return QHostAddress(network.toIPv4Address() & netmask.toIPv4Address());
		case QAbstractSocket::IPv6Protocol:
		{
			Q_IPV6ADDR networkValue = network.toIPv6Address();
			Q_IPV6ADDR netmaskValue = netmask.toIPv6Address();
			for(int i = 0 ; i < 16 ; i++)
				networkValue[i] &= netmaskValue[i];
			return QHostAddress(networkValue);
		}
		default:
			return QHostAddress();
	}
}
Beispiel #19
0
///\brief Returns true if the address is globally accessible (i.e. exposed to the real world!)
bool TorcNetwork::IsGlobal(const QHostAddress &Address)
{
    // internal/loopback and link local
    if (!IsExternal(Address))
        return false;

    // private
    if (Address.protocol() == QAbstractSocket::IPv4Protocol)
        if (Address.isInSubnet(gIPv4PrivateA) || Address.isInSubnet(gIPv4PrivateB) || Address.isInSubnet(gIPv4PrivateC))
            return false;

    return true;
}
void tst_QHostAddress::setAddress_QString()
{
    QFETCH(QString, address);
    QFETCH(bool, ok);
    QFETCH(int, protocol);

    QHostAddress hostAddr;
    QVERIFY(hostAddr.setAddress(address) == ok);

    if (ok)
        QTEST(hostAddr.toString(), "resAddr");

    if ( protocol == 4 ) {
        QVERIFY( hostAddr.protocol() == QAbstractSocket::IPv4Protocol || hostAddr.protocol() == QAbstractSocket::UnknownNetworkLayerProtocol );
        QVERIFY( hostAddr.protocol() != QAbstractSocket::IPv6Protocol );
    } else if ( protocol == 6 ) {
        QVERIFY( hostAddr.protocol() != QAbstractSocket::IPv4Protocol && hostAddr.protocol() != QAbstractSocket::UnknownNetworkLayerProtocol );
        QVERIFY( hostAddr.protocol() == QAbstractSocket::IPv6Protocol );
    } else {
        QVERIFY( hostAddr.isNull() );
        QVERIFY( hostAddr.protocol() == QAbstractSocket::UnknownNetworkLayerProtocol );
    }
}
Beispiel #21
0
QScriptValue NetworkAutomaticProxy::isInNet(QScriptContext *context, QScriptEngine *engine)
{
	Q_UNUSED(engine);

	if (context->argumentCount() != 3)
	{
		return context->throwError(QLatin1String("Function isInNet takes three arguments!"));
	}

	const QHostAddress address(context->argument(0).toString());
	const QHostAddress netaddress(context->argument(1).toString());
	const QHostAddress netmask(context->argument(2).toString());

	return (address.protocol() == QAbstractSocket::IPv4Protocol && (netaddress.toIPv4Address() & netmask.toIPv4Address()) == (address.toIPv4Address() & netmask.toIPv4Address()));
}
Beispiel #22
0
QByteArray Common::packAddress(const QHostAddress &addr, const quint16 &port)
{
    QByteArray type_bin, address_bin;
    QByteArray address_str = addr.toString().toLocal8Bit();
    quint16 port_net = htons(port);
    QByteArray port_ns = QByteArray::fromRawData(reinterpret_cast<char *>(&port_net), 2);
    if (addr.protocol() == QAbstractSocket::IPv4Protocol) {
        type_bin.append(static_cast<char>(Address::ADDRTYPE_IPV4));
        address_bin.resize(INET_ADDRSTRLEN);
        inet_pton(AF_INET, address_str.constData(), reinterpret_cast<void *>(address_bin.data()));
    } else {
        type_bin.append(static_cast<char>(Address::ADDRTYPE_IPV6));
        address_bin.resize(INET6_ADDRSTRLEN);
        inet_pton(AF_INET6, address_str.constData(), reinterpret_cast<void *>(address_bin.data()));
    }
    return type_bin + address_bin + port_ns;
}
Beispiel #23
0
void StartView::startMain(){
    QString p = ui->partnerIP->text();
    QHostAddress me(ui->myIPlist->currentText());
    QHostAddress partner;
    if (p.isEmpty())
        partner = me;
    else
        partner = QHostAddress(p);
    if (partner.protocol() != QAbstractSocket::IPv4Protocol) {
        QMessageBox mb;
        mb.setText("Invalid IP address");
        mb.exec();
        exit(QDialog::Rejected);
    } else {
        m->setIP(me, partner);
    }
}
std::string Common::packAddress(const QHostAddress &addr,
                                const uint16_t &port)
{
    std::string addrBin;
    char typeChar;
    std::string portNs(2, '\0');
    qToBigEndian(port, reinterpret_cast<uchar*>(&portNs[0]));
    if (addr.protocol() == QAbstractSocket::IPv4Protocol) {
        uint32_t ipv4Address = qToBigEndian(addr.toIPv4Address());
        typeChar = static_cast<char>(Address::IPV4);
        addrBin = std::string(reinterpret_cast<char*>(&ipv4Address), 4);
    } else {
        typeChar = static_cast<char>(Address::IPV6);
        Q_IPV6ADDR ipv6Address = addr.toIPv6Address();
        addrBin = std::string(reinterpret_cast<char*>(ipv6Address.c), 16);
    }
    return typeChar + addrBin + portNs;
}
Beispiel #25
0
        //TODO: IPv6 support, CHECK ME
        QString DccCommon::textIpToNumericalIp( const QString& ipString )
        {
            QHostAddress ip;
            ip.setAddress( ipString );
            switch (ip.protocol())
            {
            case QAbstractSocket::IPv4Protocol:
                return QString::number( ip.toIPv4Address() );

            case QAbstractSocket::IPv6Protocol:
            //ipv6 is not numerical, it is just normal text, "0:c00:0:0:1f::" for example
                return ip.toString();

            default:
                kDebug() << "unspported protocol: " << ipString;
                return "";
            }
        }
Beispiel #26
0
UPNPSubscription::UPNPSubscription(const QString &share_path, int port)
    : HttpServerExtension("UPnPSubscriptionManager", share_path),
      m_subscriptionLock(QMutex::Recursive), m_callback(QString("NOTSET"))
{
    QHostAddress addr;
    if (!UPnp::g_IPAddrList.isEmpty())
        addr = UPnp::g_IPAddrList.at(0);

    QString host;
    // taken from MythCoreContext
    if (addr.protocol() == QAbstractSocket::IPv6Protocol)
        host = "[" + addr.toString() + "]";
    else
        host = addr.toString();

    m_callback = QString("http://%1:%2/Subscriptions/event?usn=")
                 .arg(host).arg(QString::number(port));
}
Beispiel #27
0
//I'm in a new network, let's be polite and introduce myself
void LanLinkProvider::broadcastToNetwork()
{

    if (!mServer->isListening()) {
        //Not started
        return;
    }

    Q_ASSERT(mTcpPort != 0);

    qCDebug(KDECONNECT_CORE()) << "Broadcasting identity packet";

    QHostAddress destAddress = mTestMode? QHostAddress::LocalHost : QHostAddress(QStringLiteral("255.255.255.255"));

    NetworkPackage np(QLatin1String(""));
    NetworkPackage::createIdentityPackage(&np);
    np.set(QStringLiteral("tcpPort"), mTcpPort);

#ifdef Q_OS_WIN
    //On Windows we need to broadcast from every local IP address to reach all networks
    QUdpSocket sendSocket;
    for (const QNetworkInterface &iface : QNetworkInterface::allInterfaces()) {
        if ( (iface.flags() & QNetworkInterface::IsUp)
          && (iface.flags() & QNetworkInterface::IsRunning)
          && (iface.flags() & QNetworkInterface::CanBroadcast)) {
            for (const QNetworkAddressEntry &ifaceAddress : iface.addressEntries()) {
                QHostAddress sourceAddress = ifaceAddress.ip();
                if (sourceAddress.protocol() == QAbstractSocket::IPv4Protocol && sourceAddress != QHostAddress::LocalHost) {
                    qCDebug(KDECONNECT_CORE()) << "Broadcasting as" << sourceAddress;
                    sendSocket.bind(sourceAddress, PORT);
                    sendSocket.writeDatagram(np.serialize(), destAddress, PORT);
                    sendSocket.close();
                }
            }
        }
    }
#else
    mUdpSocket.writeDatagram(np.serialize(), destAddress, PORT);
#endif

}
Beispiel #28
0
        bool isIPInRange(const QHostAddress &addr, const QList<Subnet> &subnets)
        {
            QHostAddress protocolEquivalentAddress;
            bool addrConversionOk = false;

            if (addr.protocol() == QAbstractSocket::IPv4Protocol) {
                // always succeeds
                protocolEquivalentAddress = QHostAddress(addr.toIPv6Address());
                addrConversionOk = true;
            }
            else {
                // only succeeds when addr is an ipv4-mapped ipv6 address
                protocolEquivalentAddress = QHostAddress(addr.toIPv4Address(&addrConversionOk));
            }

            for (const Subnet &subnet : subnets)
                if (addr.isInSubnet(subnet) || (addrConversionOk && protocolEquivalentAddress.isInSubnet(subnet)))
                    return true;

            return false;
        }
Beispiel #29
0
Transport::Transport(JingleContent *content)
    : JingleTransport(content)
{
	QList<QHostAddress> addresses;
	foreach (const QNetworkInterface &networkInterface, QNetworkInterface::allInterfaces()) {
		if (networkInterface.flags() & QNetworkInterface::IsLoopBack)
			continue;
		foreach (const QNetworkAddressEntry &addressEntry, networkInterface.addressEntries()) {
			QHostAddress address = addressEntry.ip();
			if(address.protocol() == QAbstractSocket::IPv6Protocol && XMPP::Ice176::isIPv6LinkLocalAddress(address))
				address.setScopeId(networkInterface.name());
			addresses << address;
		}
	}
	qSort(addresses.begin(), addresses.end(), addressLessThen);
	QList<XMPP::Ice176::LocalAddress> localAddresses;
	foreach (const QHostAddress &address, addresses) {
		XMPP::Ice176::LocalAddress localAddress;
		localAddress.addr = address;
		localAddresses << localAddress;
	}
Beispiel #30
0
/*!
    \since 4.8
*/
bool QNativeSocketEngine::joinMulticastGroup(const QHostAddress &groupAddress,
                                             const QNetworkInterface &iface)
{
    Q_D(QNativeSocketEngine);
    Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::joinMulticastGroup(), false);
    Q_CHECK_STATE(QNativeSocketEngine::joinMulticastGroup(), QAbstractSocket::BoundState, false);
    Q_CHECK_TYPE(QNativeSocketEngine::joinMulticastGroup(), QAbstractSocket::UdpSocket, false);

    // if the user binds a socket to an IPv6 address (or QHostAddress::Any) and
    // then attempts to join an IPv4 multicast group, this won't work on
    // Windows. In order to make this cross-platform, we warn & fail on all
    // platforms.
    if (groupAddress.protocol() == QAbstractSocket::IPv4Protocol &&
        (d->socketProtocol == QAbstractSocket::IPv6Protocol ||
         d->socketProtocol == QAbstractSocket::AnyIPProtocol)) {
        qWarning("QAbstractSocket: cannot bind to QHostAddress::Any (or an IPv6 address) and join an IPv4 multicast group;"
                 " bind to QHostAddress::AnyIPv4 instead if you want to do this");
        return false;
    }

    return d->nativeJoinMulticastGroup(groupAddress, iface);
}