//---------------------------------------------
//-----------------DHCP PACKET-----------------
//---------------------------------------------
dhcp_packet::dhcp_packet(QHostAddress ip, QHostAddress netmask, QNetworkInterface inter)
{
    this->op = 0x01;

    this->htype = 0x01;

    this->hlen = 0x06;

    this->hops = 0x00;

    this->xid[0] = 0x63;
    this->xid[1] = 0x9F;
    this->xid[2] = 0xC0;
    this->xid[3] = 0x4B;

    this->secs[0] = 0x00;
    this->secs[1] =0x00;

    this->flags[0] = 0x00;
    this->flags[1] = 0x00;

    this->ciaddr = ip.toIPv4Address();

    this->yiaddr = 0x00000000;

    this->siaddr = ip.toIPv4Address() & netmask.toIPv4Address();

    for (int i = 0; i < 4; i++)
        this->giaddr[i] = 0x00;


    qDebug() << inter.hardwareAddress();
    bool ok;
    this->chaddr[0] = QString::fromStdString(inter.hardwareAddress().toStdString().substr(0, 2)).toInt(&ok, 16);
    this->chaddr[1] = QString::fromStdString(inter.hardwareAddress().toStdString().substr(3, 2)).toInt(&ok, 16);
    this->chaddr[2] = QString::fromStdString(inter.hardwareAddress().toStdString().substr(6, 2)).toInt(&ok, 16);
    this->chaddr[3] = QString::fromStdString(inter.hardwareAddress().toStdString().substr(9, 2)).toInt(&ok, 16);
    this->chaddr[4] = QString::fromStdString(inter.hardwareAddress().toStdString().substr(12, 2)).toInt(&ok, 16);
    this->chaddr[5] = QString::fromStdString(inter.hardwareAddress().toStdString().substr(15, 2)).toInt(&ok, 16);
    for (int i = 0; i < 5; i++)
        qDebug() << chaddr[i];
    for (int i = 0; i < 10; i++)
        this->chaddr[i+6] = 0x00;

    for (int i = 0; i < 64; i++)
        this->sname[i] = 0x00;

    for (int i = 0; i < 128; i++)
        this->file[i] = 0x00;

    //DHCP protocols
    options.append(0x63);
    options.append(0x82);
    options.append(0x53);
    options.append(0x63);
}
Пример #2
0
ZTPManager::ZTPManager(quint16 port,
           QHostAddress groupAddress, QObject *parent):
    QObject(parent)
{
    _Socketlistener.bind(QHostAddress::Any,port,QUdpSocket::ShareAddress);
    if(groupAddress.toIPv4Address()>0xe0000000 && groupAddress.toIPv4Address()<0xf0000000)
    {
        _Socketlistener.joinMulticastGroup(groupAddress);
        //_Socketlistener.setSocketOption(QAbstractSocket::MulticastTtlOption, 5);
    }
    connect(&_Socketlistener,SIGNAL(readyRead()),this,SLOT(onRead()),Qt::AutoConnection);
    MTU = 60000;
    _timeout = 3000;

}
Пример #3
0
bool Server::SendData(QHostAddress ip_to, QString message)
{
    bool result = false;
    QTcpSocket* tcpSocket = sockets->value(ip_to.toIPv4Address(), 0);
    if (tcpSocket && tcpSocket->state()==QAbstractSocket::ConnectedState && tcpSocket->isWritable()) {
        emit write_message(tr("Sending data (size=%1) to %2. Content: \"%3\"").arg(message.length()).arg(ip_to.toString()).arg(message));
        tcpSocket->write(message.toUtf8());
        result = tcpSocket->waitForBytesWritten();
    } else {
        tcpSocket = new QTcpSocket();
        tcpSocket->connectToHost(ip_to, remote_port, QIODevice::ReadWrite);
        tcpSocket->waitForConnected(5000);

        if (tcpSocket->state()==QAbstractSocket::ConnectedState) {
            emit write_message(tr("Sending data (size=%1) from new socket to %2. Content: \"%3\"").arg(message.length()).arg(ip_to.toString()).arg(message));
            tcpSocket->write(message.toUtf8());
            result = tcpSocket->waitForBytesWritten(5000);
        } else {
            emit error(tr("Client \"%1\" not found").arg(ip_to.toString()));
        }

        tcpSocket->abort();
        delete tcpSocket;
    }
    return result;
}
Пример #4
0
bool LwIPTcpServer::listen(const QHostAddress &address, quint16 port) {
	Q_D(LwIPTcpServer);

	if(d->conn == 0) {
		d->conn = LwIPDispatcher::createConn(NETCONN_TCP, this);

		if(d->conn == 0) {
			return false;
		}

		struct ip_addr addr;

		addr.addr = qToBigEndian(address.toIPv4Address());

		if(netconn_bind(d->conn, &addr, port) != ERR_OK)
			goto failure;

		if(netconn_listen(d->conn) != ERR_OK)
			goto failure;

		d->serverAddress = address;
		d->serverPort = port;

		return true;
	} else
		return false;

failure:
	LwIPDispatcher::disposeConn(d->conn);

	d->conn = 0;
	return false;

}
Пример #5
0
/*! \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
    }
}
Пример #6
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;
}
Пример #7
0
void Discovery::readyRead() {

    QHostAddress metisAddress;
    quint16 metisPort;
    unsigned char buffer[1024];

    if(server->getSocket()->readDatagram((char*)&buffer,(qint64)sizeof(buffer),&metisAddress,&metisPort)<0) {
        qDebug()<<"Error: Discovery: readDatagram failed "<<server->getSocket()->errorString();
        return;
    }

    if(buffer[0]==0xEF && buffer[1]==0xFE) {
        switch(buffer[2]) {
            case 3:  // reply
                // should not happen on this port
                break;
            case 2:  // response to a discovery packet
                if(metisAddress.toString()!=server->getInterfaceIPAddress(server->getInterface())) {
                    Metis* metis=new Metis(metisAddress.toIPv4Address(),&buffer[3]);
                    server->addMetis(*metis);
                }
                break;
            case 1:  // a data packet
               // should not happen on this port
               break;
        }
    } else {
        qDebug() << "received invalid response to discovery";
    }

}
Пример #8
0
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;
}
QHostAddress internetAddress()
{
	hostent* hostinfo;
	char name[256];
	QHostAddress result;

	if ( !gethostname( name, sizeof( name ) ) )
	{
		hostinfo = gethostbyname( name );

		if ( hostinfo )
		{
			Q_UINT32 i = 0;

			while ( hostinfo->h_addr_list[i] )
			{
				// Check if it's an INTERNET ADDRESS
				char* hIp = inet_ntoa( *( struct in_addr* ) hostinfo->h_addr_list[i++] );
				result.setAddress( hIp );
				Q_UINT32 ip = result.toIPv4Address();
				Q_UINT8 part1 = ( ip & 0xFF000000 ) >> 24;
				Q_UINT8 part2 = ( ip & 0x00FF0000 ) >> 16;

				if ( ( part1 == 127 ) || 	//this one is class A too.
					( part1 == 10 ) || ( ( part1 == 192 ) && ( part2 == 168 ) ) || ( ( part1 == 172 ) && ( part2 >= 16 ) && ( part2 <= 31 ) ) || ( ( part1 == 169 ) && ( part2 == 254 ) ) // DHCP Space Stuff
					)
				{
					continue;
				}

				// We are now certain that it's a valid INET ip
				break;
			}
		}
	}
Пример #10
0
/**
 Link Local address should be in the range
 169.254.1.0 to 169.254.254.255
 Refer :http://en.wikipedia.org/wiki/Private_network
 */
bool NetworkHelper::isLinkLocalAddress(const QHostAddress &addr)
{
    quint32 hostIpv4Addr = addr.toIPv4Address();
    quint32 rangeMin = QHostAddress("169.254.1.0").toIPv4Address();
    quint32 rangeMax = QHostAddress("169.254.254.255").toIPv4Address();
    return (hostIpv4Addr >= rangeMin && hostIpv4Addr <= rangeMax);
}
Пример #11
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;
  }
Пример #12
0
 GaduAccount::GaduAccount( Kopete::Protocol* parent, const QString& accountID,const char* name )
: Kopete::PasswordedAccount( parent, accountID, 0, name )
{
	QHostAddress ip;
	p = new GaduAccountPrivate;

	p->pingTimer_ = NULL;
	p->saveListDialog = NULL;
	p->loadListDialog = NULL;
	p->forFriends = false;

	p->textcodec_ = QTextCodec::codecForName( "CP1250" );
	p->session_ = new GaduSession( this, "GaduSession" );

	KGlobal::config()->setGroup( "Gadu" );

	setMyself( new GaduContact( accountId().toInt(), accountId(), this, Kopete::ContactList::self()->myself() ) );

	p->status = GaduProtocol::protocol()->convertStatus( GG_STATUS_NOT_AVAIL );
	p->lastDescription = QString::null;

	for ( unsigned int i = 0; i < NUM_SERVERS ; i++ ) {
		ip.setAddress( QString( servers_ip[i] ) );
		p->servers.append( htonl( ip.toIPv4Address() ) );
		kdDebug( 14100 ) << "adding IP: " <<  p->servers[ i ] << " to cache" << endl;
	}
	p->currentServer = -1;
	p->serverIP = 0;

	// initialize KGaduLogin structure to default values
	p->loginInfo.uin		= accountId().toInt();
	p->loginInfo.useTls		= false;
	p->loginInfo.status		= GG_STATUS_AVAIL;
	p->loginInfo.server		= 0;
	p->loginInfo.client_port	= 0;
	p->loginInfo.client_addr	= 0;

	p->pingTimer_ = new QTimer( this );
	p->exportTimer_ = new QTimer( this );

	p->exportUserlist = false;
	p->gaduDcc_ = NULL;

	p->config = configGroup();

	p->ignoreAnons = ignoreAnons();
	p->forFriends = loadFriendsMode();

	initConnections();
	initActions();

	QString nick = p->config->readEntry( QString::fromAscii( "nickName" ) );
	if ( !nick.isNull() ) {
		myself()->setProperty( Kopete::Global::Properties::self()->nickName(), nick );
	}
	else {
		myself()->setProperty( Kopete::Global::Properties::self()->nickName(), accountId() );
		p->config->writeEntry( QString::fromAscii( "nickName" ), accountId() );
	}
}
Пример #13
0
QT_BEGIN_NAMESPACE

static QList<QNetworkInterfacePrivate *> postProcess(QList<QNetworkInterfacePrivate *> list)
{
    // Some platforms report a netmask but don't report a broadcast address
    // Go through all available addresses and calculate the broadcast address
    // from the IP and the netmask
    //
    // This is an IPv4-only thing -- IPv6 has no concept of broadcasts
    // The math is:
    //    broadcast = IP | ~netmask

    QList<QNetworkInterfacePrivate *>::Iterator it = list.begin();
    const QList<QNetworkInterfacePrivate *>::Iterator end = list.end();
    for ( ; it != end; ++it) {
        QList<QNetworkAddressEntry>::Iterator addr_it = (*it)->addressEntries.begin();
        const QList<QNetworkAddressEntry>::Iterator addr_end = (*it)->addressEntries.end();
        for ( ; addr_it != addr_end; ++addr_it) {
            if (addr_it->ip().protocol() != QAbstractSocket::IPv4Protocol)
                continue;

            if (!addr_it->netmask().isNull() && addr_it->broadcast().isNull()) {
                QHostAddress bcast = addr_it->ip();
                bcast = QHostAddress(bcast.toIPv4Address() | ~addr_it->netmask().toIPv4Address());
                addr_it->setBroadcast(bcast);
            }
        }
    }

    return list;
}
Пример #14
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);
  }
Пример #15
0
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));
    }
}
Пример #16
0
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);
}
Пример #17
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;
	}
}
Пример #18
0
void ZTPManager::commonInit(const QHostAddress& groupAddress)
{
    #if QT_VERSION < QT_VERSION_CHECK(5,0,0)
    QThreadPool::globalInstance()->setMaxThreadCount(QThreadPool::globalInstance()->maxThreadCount()+1);
    #endif
    ztpThreadPool = new QThreadPool;
    ztpThreadPool->setMaxThreadCount(1);
    if(groupAddress.toIPv4Address()>0xe0000000 && groupAddress.toIPv4Address()<0xf0000000)
    {
        _Socketlistener.joinMulticastGroup(groupAddress);
        //_Socketlistener.setSocketOption(QAbstractSocket::MulticastTtlOption, 5);
    }
    connect(&_Socketlistener,SIGNAL(readyRead()),this,SLOT(onRead()),Qt::DirectConnection);
    MTU = 60000;
    _timeout = 3000;

    moveToThread(&ztpTask);
    connect(this,SIGNAL(registTask(const QByteArray &,const QString &,quint16)),this,
            SLOT(procPkg(const QByteArray &,const QString &,quint16)),Qt::QueuedConnection);
}
Пример #19
0
unsigned int qstringAddressToUint(QString inputAddress)         ///this function converts an IPv4
{                                                               ///address in string format
                                                                ///to unsigned int format
                                                                ///this is used in databse to
                                                                ///check overlapping intervals
    unsigned int address;
    QHostAddress addressBuffer;
    addressBuffer.setAddress(inputAddress);
    address=addressBuffer.toIPv4Address();
    return address;
}
Пример #20
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());
	}
}
Пример #21
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();
	}
}
Пример #22
0
bool MulticastSocket::joinMulticastGroup(const QHostAddress& groupAddress, const QNetworkInterface& iface)
{
    bool success = false;

    foreach (const QNetworkAddressEntry& addressEntry, iface.addressEntries()) {
        const QHostAddress interfaceAddress = addressEntry.ip();

        if (interfaceAddress.protocol() == IPv4Protocol) {
            ip_mreq mreq;
            mreq.imr_multiaddr.s_addr = htonl(groupAddress.toIPv4Address());
            mreq.imr_interface.s_addr = htonl(interfaceAddress.toIPv4Address());

            const bool error = setsockopt(socketDescriptor(), IPPROTO_IP, IP_ADD_MEMBERSHIP, (const char*) &mreq, sizeof(mreq)) == -1;
            if (error)
                setErrorString(strerror(errno));
            else
                success = true;
        }
    }

    return success;
}
Пример #23
0
QByteArray Dispatcher::assembleSearchPacket(QHostAddress &searchingHost, quint64 &searchID, QByteArray &searchData, bool appendBucket)
{
    QByteArray datagram;
    datagram.reserve(300);
    datagram.append(toQByteArray(searchingHost.toIPv4Address()));
    datagram.append(toQByteArray(searchID));
    datagram.append(fixedCIDLength(CID));  // moet seker wees lengte is reg, anders bevark hy die indekse wat kom
    datagram.append(toQByteArray((quint16)searchData.length()));
    datagram.append(searchData);
    if (appendBucket)
        datagram.append(networkTopology->getOwnBucket());
    return datagram;
}
Пример #24
0
void DiscoverClient::readyRead()
{
    while (m_socket->hasPendingDatagrams())
    {
        QByteArray data;
        data.resize(int(m_socket->pendingDatagramSize()));

        QHostAddress host;
        quint16 port;

        m_socket->readDatagram(data.data(), data.size(), &host, &port);

        if (data.size() != 128 + MAX_ID_LENGTH)
            continue;

        QByteArray negotiation_string = data.mid(0, 128);
        data.remove(0, 128);

        QString id = QLatin1String(data.mid(0, MAX_ID_LENGTH));
        data.remove(0, MAX_ID_LENGTH);

        QList<quint32> ip_black_list;

        for (const QHostAddress &host : QNetworkInterface::allAddresses())
        {
            if (host != QHostAddress::LocalHost)
                ip_black_list.append(host.toIPv4Address());
        }

        if (!ip_black_list.contains(host.toIPv4Address()) &&
                !m_got_list.contains(host.toIPv4Address())
                && negotiation_string == m_negotiation_string)
        {
            m_got_list.append(host.toIPv4Address());
            emit peerFound(host, id);
        }
    }
}
Пример #25
0
QString GeoIP::lookupCountryCode(QHostAddress addr)
{
    static const char *countryCode[] = { "--","AP","EU","AD","AE","AF","AG","AI","AL","AM","CW","AO","AQ","AR","AS","AT","AU","AW","AZ","BA","BB","BD","BE","BF","BG","BH","BI","BJ","BM","BN","BO","BR","BS","BT","BV","BW","BY","BZ","CA","CC","CD","CF","CG","CH","CI","CK","CL","CM","CN","CO","CR","CU","CV","CX","CY","CZ","DE","DJ","DK","DM","DO","DZ",
                                    "EC","EE","EG","EH","ER","ES","ET","FI","FJ","FK","FM","FO","FR","FX","GA","GB","GD","GE","GF","GH","GI","GL","GM","GN","GP","GQ","GR","GS","GT","GU","GW","GY","HK","HM","HN","HR","HT","HU","ID","IE","IL","IN","IO","IQ","IR","IS","IT","JM","JO","JP","KE","KG","KH","KI","KM","KN","KP","KR","KW","KY","KZ",
                                    "LA","LB","LC","LI","LK","LR","LS","LT","LU","LV","LY","MA","MC","MD","MG","MH","MK","ML","MM","MN","MO","MP","MQ","MR","MS","MT","MU","MV","MW","MX","MY","MZ","NA","NC","NE","NF","NG","NI","NL","NO","NP","NR","NU","NZ","OM","PA","PE","PF","PG","PH","PK","PL","PM","PN","PR","PS","PT","PW","PY","QA",
                                    "RE","RO","RU","RW","SA","SB","SC","SD","SE","SG","SH","SI","SJ","SK","SL","SM","SN","SO","SR","ST","SV","SY","SZ","TC","TD","TF","TG","TH","TJ","TK","TM","TN","TO","TL","TR","TT","TV","TW","TZ","UA","UG","UM","US","UY","UZ","VA","VC","VE","VG","VI","VN","VU","WF","WS","YE","YT","RS","ZA","ZM","ME","ZW","A1","A2",
                                         "O1","AX","GG","IM","JE","BL","MF", "BW"
                                       };
    static const quint32 sizeCountryCode = sizeof(countryCode) / sizeof(countryCode[0]);
    quint32 countryPos = seekCountry(0, addr.toIPv4Address(), 31);
    if (countryPos >= sizeCountryCode)
        countryPos = 0;
    return(countryCode[countryPos]);
}
Пример #26
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()));
}
Пример #27
0
/**
 Refer: http://en.wikipedia.org/wiki/Private_network
 Private Ipv4 address ranges:
  1. 10.0.0.0 - 10.255.255.255
  2. 172.16.0.0 - 172.31.255.255
  3. 192.168.0.0 - 192.168.255.255
 */
bool NetworkHelper::isLocalIpAddress(const QHostAddress &addr)
{
    quint32 hostIpv4Addr = addr.toIPv4Address();
    quint32 range1Min = QHostAddress("10.0.0.0").toIPv4Address();
    quint32 range1Max = QHostAddress("10.255.255.255").toIPv4Address();

    quint32 range3Min = QHostAddress("172.16.0.0").toIPv4Address();
    quint32 range3Max = QHostAddress("172.31.255.255").toIPv4Address();

    quint32 range2Min = QHostAddress("192.168.0.0").toIPv4Address();
    quint32 range2Max = QHostAddress("192.168.255.255").toIPv4Address();

    return ((hostIpv4Addr >= range1Min && hostIpv4Addr <= range1Max)
            || (hostIpv4Addr >= range2Min && hostIpv4Addr <= range2Max)
            || (hostIpv4Addr >= range3Min && hostIpv4Addr <= range3Max));
}
Пример #28
0
  void SocksConnection::WriteSocksReply(SocksReplyCode reason, 
      const QHostAddress &addr, quint16 port) 
  {
    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

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

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

    WriteToSocket(reply);
  }
Пример #29
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 "";
            }
        }
Пример #30
0
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;
}