示例#1
1
const QHostAddress afqt::toQAddress( const af::Address & address)
{
   QHostAddress qaddr;
   switch( address.getFamily())
   {
      case af::Address::IPv4:
      {
         uint32_t ipv4;
         memcpy( &ipv4, address.getAddrData(), 4);
         qaddr.setAddress( htonl(ipv4));
         break;
      }
      case af::Address::IPv6:
         qaddr.setAddress( (quint8*)(address.getAddrData()));
         break;
      default:
         AFERROR("Address::setQAddress: Unknown address family.\n");
   }
   return qaddr;
}
void RemoteInterfaceListener::run() {

	// Init socket
	stopRequested = false;
	QUdpSocket socket;
	if(!socket.bind(QHostAddress(server->ip), server->port, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint)) {
		// Show error
		Debug::print("[RemoteInterfaceListener] could not bind");
		stopRequested = true;
	}

	// Enter processing loop...
	while (stopRequested == false) {

		// Process all pending datagrams
		while(socket.hasPendingDatagrams() && !stopRequested) {
			// Get the data from socket
			QByteArray data;
			data.resize(socket.pendingDatagramSize());
			QHostAddress sender;
			quint16 senderPort;
			socket.readDatagram(data.data(), data.size(), &sender, &senderPort);

			// Extract message and keep track of the pointer in the server
			RemoteInterfaceMessage *message = new RemoteInterfaceMessage(&data);
			message->sourceIp = sender.toString();
			message->sourcePort = senderPort;
			message->destinationIp = server->ip;
			message->destinationPort = server->port;
			server->messages->append(message);

			// Show reception and pass on for processing...
			Debug::print("[RemoteInterfaceListener] received %1 message from %2:%3", message->type, sender.toString(), senderPort);
			server->processMessage(message);
		}

		// Sleep wait
		QThread::msleep(core->intSetting("RemoteInterface_ListenerInterval"));

	}
}
示例#3
1
void NetworkManager::processDatagrams()
{
    while (udpSocket->hasPendingDatagrams())
    {
        QByteArray datagram;
        datagram.resize(udpSocket->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;

        udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);

        QLOG_TRACE() << "Recieved UDP datagramm" << datagram;

        int cmp = std::memcmp(datagram.constData(), UDP_DISCOVER_REQUEST, datagram.length());
        if (cmp == 0)
        {
            QLOG_TRACE() << "Datagramm recognized - sending reply to " + sender.toString();
            udpSocket->writeDatagram(UDP_DISCOVER_REPLY, sizeof(UDP_DISCOVER_REPLY), sender, settings->DiscoverPort());
        }
    }
}
示例#4
0
void TCPServer::incomingConnection(qintptr socketDescriptor)
{
    TcpClientSocket *tcpClientSocket=new TcpClientSocket(this);
    connect(tcpClientSocket,SIGNAL(updateClients(QString,int)),this,SLOT(updateClients(QString,int)));
    connect(tcpClientSocket,SIGNAL(disconnected(int)),this,SLOT(slotDisconnected(int)));
    connect(tcpClientSocket,SIGNAL(readyRead()),this,SLOT(dataReceived()));
    tcpClientSocket->setSocketDescriptor(socketDescriptor);
    QHostAddress	 add = tcpClientSocket->localAddress();
    quint16 port = tcpClientSocket->localPort();
    qDebug() << add.toString() << " port:"<< port;
    tcpClientSocketList.append(tcpClientSocket);

    QString strLog = "IP " + tcpClientSocket->peerAddress().toString() + " connect this server.";
    Log(strLog,0,false);


   // timer = new QTimer(this);
    //connect(timer, SIGNAL(timeout()), this, SLOT(update()));
  //  timer->start(1000);
}
void BacnetUdpTransportLayerHandler::readDatagrams()
{
    Q_ASSERT(0 != _bvllHndlr);
    QHostAddress srcAddr;
    quint16 srcPort;
    qint64 length;
    while (_socket->hasPendingDatagrams()) {
        length = _socket->readDatagram(_datagram.data(), Bacnet::BvllMaxSize, &srcAddr, &srcPort);
        if (length > 0) {
            if ( (_myAddress == srcAddr) && (srcPort == _myPort) ) {
                qDebug("BacnetUdpTransportLayerHandler:readDatagrams() : Discard message received from myself!");
                continue;
            }
            qDebug("Got message from %s, %d. My settings: %s, %d", qPrintable(srcAddr.toString()), srcPort,
                    qPrintable(_myAddress.toString()), _myPort);
            //pass it to the higher layer if any data read
            _bvllHndlr->consumeDatagram((quint8*)(_datagram.data()), length, srcAddr, srcPort);
        }
    }
}
示例#6
0
Ingest::Ingest(QNetworkInterface interface, QHostAddress address, quint32 port, QString mediaDir, QString fileName)
    : m_interface(interface), m_address(address), m_port(port), m_media_dir(mediaDir)
{
    qDebug() << __PRETTY_FUNCTION__ << " " << __LINE__;

    if(fileName.isEmpty())
        m_file_name = mediaDir + "/" + address.toString() + ".ts";
    else
        m_file_name = mediaDir + "/ " + fileName;

}
示例#7
0
QByteArray NetworkManager::ipv6AddressFromHostAddress(const QHostAddress &address)
{
//     Q_ASSERT(address.protocol() == QAbstractSocket::IPv6Protocol);
    Q_IPV6ADDR tmp = address.toIPv6Address();
    QByteArray assembledAddress;
    for (int i = 0; i < 16; ++i) {
        assembledAddress[i] = tmp[i];
    }

    return assembledAddress;
}
示例#8
0
void OS2LPlugin::slotProcessTCPPackets()
{
    QTcpSocket *socket = (QTcpSocket *)sender();
    if (socket == NULL)
        return;

    QHostAddress senderAddress = socket->peerAddress();
    QByteArray message = socket->readAll();
    QJsonDocument json = QJsonDocument::fromJson(message);

    qDebug() << "[TCP] Received" << message.length() << "bytes from" << senderAddress.toString();
    QJsonObject jsonObj = json.object();
    QJsonValue jEvent = jsonObj.value("evt");
    if (jEvent.isUndefined())
        return;

    QString event = jEvent.toString();

    if (event == "btn")
    {
        QJsonValue jName = jsonObj.value("name");
        QJsonValue jState = jsonObj.value("state");
        qDebug() << "Got button event with name" << jName.toString() << "and state" << jState.toString();
        uchar value = jState.toString() == "off" ? 0 : 255;
        emit valueChanged(m_inputUniverse, 0, getHash(jName.toString()), value, jName.toString());
    }
    else if (event == "cmd")
    {
        QJsonValue jId = jsonObj.value("id");
        QJsonValue jParam = jsonObj.value("param");
        qDebug() << "Got CMD message" << jId.toInt() << "with param" << jParam.toDouble();
        quint32 channel = quint32(jId.toInt());
        QString cmd = QString("cmd%1").arg(channel);
        emit valueChanged(m_inputUniverse, 0, quint32(jId.toInt()), uchar(jParam.toDouble()), cmd);
    }
    else if (event == "beat")
    {
       qDebug() << "Got beat message" << message;
       emit valueChanged(m_inputUniverse, 0, 8341, 255, "beat");
    }
}
示例#9
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

}
示例#10
0
void ZTPManager::onRead()
{
    QHostAddress remoteHost;
    quint16 remotePort;
    QByteArray recvBuff(_Socketlistener.pendingDatagramSize(),'\0');
    qint64 pendingLen = _Socketlistener.readDatagram(recvBuff.data(),recvBuff.length(),&remoteHost,&remotePort);
    Fragment* fragment = new Fragment(recvBuff);
//    qDebug()<<"fragment :"<<fragment->identifier<<" "<<fragment->checksum<<" "<<fragment->fragment_count<<" "<<fragment->fragment_offset<<" "<<fragment->len;
//    qDebug()<<"fragment isvalid:"<<fragment->isValid();
    if(!workMap.contains(fragment->identifier))
    {
        workMap.insert(fragment->identifier,new FragmentList(fragment->identifier));
        connect(workMap[fragment->identifier],SIGNAL(timeout(quint16)),this,SLOT(onTimeout(quint16)));
    }
    workMap[fragment->identifier]->timer.start(_timeout);
    workMap[fragment->identifier]->fragment_list.append(fragment);
    if(workMap[fragment->identifier]->fragment_list.length() == fragment->fragment_count)
    {
        qSort(workMap[fragment->identifier]->fragment_list.begin(),workMap[fragment->identifier]->fragment_list.end(),lessThan);
		QByteArray recvBuff;
        for(int i = 0; i < fragment->fragment_count;i++)
        {
            recvBuff.append(workMap[fragment->identifier]->fragment_list[i]->data);
        }
        FragmentList* node = workMap[fragment->identifier];
        workMap.remove(fragment->identifier);
        delete node;
		qint64 len;
    	memcpy(&len,recvBuff.data()+6,8);
        if(recvBuff.length()!=len)
    	{
       		qDebug("recv ZTP data error: has data %lld bytes and actually recv %lld bytes!!\n",
                len,pendingLen);
    	}
        ZTPprotocol* ztp = new ZTPprotocol(recvBuff);
        ztp->addPara("RemoteHost",remoteHost.toString());
        ztp->addPara("RemotePort",QString::number(remotePort));
        ztpList.append(ztp);
		emit readyRead();
    }
}
示例#11
0
int RTP::connectToHost( const QHostAddress & hostAddress, quint16 port, int waitMsecs, QString *errorMessage, Protocol protocol){
    qDebug()<<"-------------------Protocol:"<<protocol;
    int socketID = -1;
    QString err;

    if(protocol != TCP){
        socketID = m_udtProtocol->connectToHost(hostAddress, port, 0, true, waitMsecs);
        if( (socketID == INVALID_SOCK_ID) || (!m_udtProtocol->isSocketConnected(socketID)) ){
            err += tr("Can not connect to host %1:%2 via UDT! %3").arg(hostAddress.toString()).arg(port).arg(m_udtProtocol->getLastErrorMessage());
            qCritical()<<err;
            if(protocol == UDT){
                if(errorMessage){
                    *errorMessage = err;
                }
                return socketID;
            }
        }else{
            qDebug()<<QString("Peer %1:%2 connected via UDT! ").arg(hostAddress.toString()).arg(port);
            return socketID;
        }
    }

//    if( (socketID == INVALID_SOCK_ID) || (!m_udtProtocol->isSocketConnected(socketID)) ){
//        err = tr("Can not connect to host %1:%2 via UDT! %3").arg(hostAddress.toString()).arg(port).arg(m_udtProtocol->getLastErrorMessage());

        socketID = m_tcpServer->connectToHost(hostAddress, port, waitMsecs);
        if(!m_tcpServer->isConnected(socketID) ){
            err += tr("\nCan not connect to host %1:%2 via TCP! %3").arg(hostAddress.toString()).arg(port).arg(m_tcpServer->socketErrorString(socketID));
            qCritical()<<err;
            m_tcpServer->abort(socketID);
            socketID = INVALID_SOCK_ID;
        }
//    }

    if(errorMessage){
        *errorMessage = err;
    }

    return socketID;

}
示例#12
0
void ConnectionInfoDialog::setAddressString(
    const QHostAddress& address,
    quint16 port
)
{
    if( !addressTextBox )
        return;

    addressTextBox->setText(
        QString("%1:%2").arg(address.toString()).arg(port)
    );
}
示例#13
0
	void setup(const QUrl &uri, const HttpHeaders &_headers, const QHostAddress &connectAddr = QHostAddress(), int connectPort = -1, int _maxRedirects = -1)
	{
		assert(!method.isEmpty());

		QUrl tmp = uri;
		if(connectPort != -1)
			tmp.setPort(connectPort);
		else if(tmp.port() == -1)
		{
			if(uri.scheme() == "https")
				tmp.setPort(443);
			else
				tmp.setPort(80);
		}

		curl_easy_setopt(easy, CURLOPT_URL, tmp.toEncoded().data());

		if(!connectAddr.isNull())
		{
			curl_slist_free_all(dnsCache);
			QByteArray cacheEntry = tmp.encodedHost() + ':' + QByteArray::number(tmp.port()) + ':' + connectAddr.toString().toUtf8();
			dnsCache = curl_slist_append(dnsCache, cacheEntry.data());
			curl_easy_setopt(easy, CURLOPT_RESOLVE, dnsCache);
		}

		HttpHeaders headers = _headers;

		bool chunked = false;
		if(headers.contains("Content-Length"))
		{
			curl_off_t content_len = (curl_off_t)headers.get("Content-Length").toLongLong();
			/*if(method == "POST")
				curl_easy_setopt(easy, CURLOPT_POSTFIELDSIZE_LARGE, content_len);
			else*/
				curl_easy_setopt(easy, CURLOPT_INFILESIZE_LARGE, content_len);

			// curl will set this for us
			headers.removeAll("Content-Length");
		}
		else
		{
			if(expectBody)
				chunked = true;
			else if(alwaysSetBody)
				curl_easy_setopt(easy, CURLOPT_INFILESIZE_LARGE, (curl_off_t)0);
		}

		curl_slist_free_all(headersList);
		foreach(const HttpHeader &h, headers)
		{
			QByteArray i = h.first + ": " + h.second;
			headersList = curl_slist_append(headersList, i.data());
		}
示例#14
0
static QByteArray localName()
{
    QByteArray result(QHostInfo::localDomainName().toLatin1());
    if (!result.isEmpty())
        return result;
    QList<QHostAddress> addresses(QNetworkInterface::allAddresses());
    if (addresses.isEmpty())
        return "localhost.localdomain";
    QHostAddress addr;
    // try to find a non-loopback address
    foreach (const QHostAddress &a, addresses) {
        if (!a.isLoopback() && !a.isNull()) {
            addr = a;
            break;
        }
    }
    if (addr.isNull())
        addr = addresses.first();

    return "[" + addr.toString().toLatin1() + "]";
}
  TcpAddress::TcpAddress(const QHostAddress &ip, const int portnum)
  {
    QUrl url("dissent://" + ip.toString());
    int port = portnum;
    if(port < 1) {
      port = DISSENT_PORT;
    }

    url.setPort(port);

    _data = new TcpAddressData(url, ip, port);
  }
示例#16
0
void Server::setListen()
{
    if(ui->pushButtonListen->text() == "Listen")
    {
        ui->pushButtonListen->setText("No Listen");
        ui->lineEditIP->setEnabled(false);
        ui->lineEditPort->setEnabled(false);
        QHostAddress hostAddress;
        hostAddress.setAddress(ui->lineEditIP->text());
        tcpServer->listen(hostAddress,
                          ui->lineEditPort->text().toInt());
    }
    else
    {
        ui->pushButtonListen->setText("Listen");
        if(tcpServer->isListening())
            tcpServer->close();
        ui->lineEditIP->setEnabled(true);
        ui->lineEditPort->setEnabled(true);
    }
}
示例#17
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;
	}
static PyObject *meth_QHostAddress_clear(PyObject *sipSelf, PyObject *sipArgs)
{
    PyObject *sipParseErr = NULL;

    {
        QHostAddress *sipCpp;

        if (sipParseArgs(&sipParseErr, sipArgs, "B", &sipSelf, sipType_QHostAddress, &sipCpp))
        {
            sipCpp->clear();

            Py_INCREF(Py_None);
            return Py_None;
        }
    }

    /* Raise an exception if the arguments couldn't be parsed. */
    sipNoMethod(sipParseErr, sipName_QHostAddress, sipName_clear, doc_QHostAddress_clear);

    return NULL;
}
示例#19
0
void DlgRecord::setData(QHostAddress saddr, quint16 port, quint16 vodport) {
    if(_pctlc == NULL) {
        if(vodport == 0) {
            _vodport = 9001;    //default port
        } else {
            _vodport = vodport;
        }
        _pctlc = new ControlClient(saddr, port);
        connect(_pctlc, SIGNAL(routeOut(QString)), this, SLOT(records(QString)));
        _vodprefix = "http://" + saddr.toString() + ":" + QString::number(_vodport);
    }
}
Camera_UDP_Object::Camera_UDP_Object(QHostAddress ip, quint16 port)
{
    udpSocket = new QUdpSocket(this);
    connect(udpSocket, SIGNAL(readyRead()),this, SLOT(read_image()));

    bool b = udpSocket->bind(ip, port);
    qDebug()<<"udp cam bound: "<< b << " , ip server: "<< ip.toString() << " , port server: "<< port;

    current_frame = -1;
    slicesStored = 0;
    nb_total_frames = 0;
}
示例#21
0
int OSAPIUDPChannel::writeDatagram(const QByteArray &datagram, QHostAddress destAddr, quint16 destPort)
{
    if(listenerSocket==-1 || pListener == NULL)
        return -1;

    inet_pton(AF_INET, destAddr.toString().toStdString().data(),
              &(destination.sin_addr));
    destination.sin_port = htons(destPort);

    return sendto(listenerSocket, datagram.data(), datagram.size(), 0,
                  (struct sockaddr*) &destination, sizeof destination);
}
示例#22
0
QPair<QNetworkRequest, QByteArray> TvDevice::createEndPairingRequest(const QHostAddress &host, const int &port)
{
    QString urlString = "http://" + host.toString() + ":" + QString::number(port) + "/udap/api/pairing";
    QNetworkRequest request;
    request.setUrl(QUrl(urlString));
    request.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("text/xml; charset=utf-8"));
    request.setHeader(QNetworkRequest::UserAgentHeader,QVariant("UDAP/2.0 guh"));
    request.setRawHeader("Connection", "Close");

    QByteArray data = "<?xml version=\"1.0\" encoding=\"utf-8\"?><envelope><api type=\"pairing\"><name>byebye</name><port>8080</port></api></envelope>";
    return QPair<QNetworkRequest, QByteArray>(request, data);
}
示例#23
0
void DuktoProtocol::handleMessage(QByteArray &data, QHostAddress &sender)
{
    char msgtype = data.at(0);

    switch(msgtype)
    {
        case 0x01:  // HELLO (broadcast)
        case 0x02:  // HELLO (unicast)
            data.remove(0, 1);
            if (data != getSystemSignature()) {
                mPeers[sender.toString()] = Peer(sender, QString::fromUtf8(data), DEFAULT_UDP_PORT);
                if (msgtype == 0x01) sayHello(sender, DEFAULT_UDP_PORT);
                emit peerListAdded(mPeers[sender.toString()]);
            }
            break;

        case 0x03:  // GOODBYE
            emit peerListRemoved(mPeers[sender.toString()]);
            mPeers.remove(sender.toString());
            break;

        case 0x04:  // HELLO (broadcast) with PORT
        case 0x05:  // HELLO (unicast) with PORT
            data.remove(0, 1);
            qint16 port = *((qint16*) data.constData());
            data.remove(0, 2);
            if (data != getSystemSignature()) {
                mPeers[sender.toString()] = Peer(sender, QString::fromUtf8(data), port);
                if (msgtype == 0x04) sayHello(sender, port);
                emit peerListAdded(mPeers[sender.toString()]);
            }
            break;
    }

}
示例#24
0
void client_logic::recieve_workers(QVector<QPair<QHostAddress, quint16> > ip_ports)
{
    if (ip_ports.empty())
    {
        return;
    }
    mkvmerge_wrapper splitter;
    QString segments_dir_name = splitter.split(filename_);
    QDir segments_dir(segments_dir_name);
    segments_dir.setFilter(QDir::Files | QDir::NoSymLinks);

    quint32 next_worker = 0;
    quint32 task_id = 0; //think about hash

	auto file_infos = segments_dir.entryInfoList();
	for (QFileInfo & file_info : file_infos)
    {
        QString task_path = file_info.absoluteFilePath();
        map_[task_id] = task_path;

        QPair<QHostAddress, quint16> ip_port = ip_ports[next_worker];
        QHostAddress ip = ip_port.first;
        quint16 port = ip_port.second;

        QFile file(task_path);
        if (file.open(QIODevice::ReadOnly))
        {
            QByteArray data = file.readAll();
            manager_.send_chunk(ip, port, chunk_amount_, data);
            qDebug() << "Chunk №" << task_id << " send to ip = " << ip.toString() << " (size = " << data.size() << ")";
            ++task_id;
            ++chunk_amount_;

        }

        next_worker = (next_worker + 1) % ip_ports.size();
    }

    splitter.remove_dir(segments_dir);
}
示例#25
0
QT_BEGIN_NAMESPACE

static QHostAddress addressFromSockaddr(sockaddr *sa, int ifindex = 0, const QString &ifname = QString())
{
    QHostAddress address;
    if (!sa)
        return address;

    if (sa->sa_family == AF_INET)
        address.setAddress(htonl(((sockaddr_in *)sa)->sin_addr.s_addr));
    else if (sa->sa_family == AF_INET6) {
        address.setAddress(((sockaddr_in6 *)sa)->sin6_addr.s6_addr);
        int scope = ((sockaddr_in6 *)sa)->sin6_scope_id;
        if (scope && scope == ifindex) {
            // this is the most likely scenario:
            // a scope ID in a socket is that of the interface this address came from
            address.setScopeId(ifname);
        } else  if (scope) {
#ifndef QT_NO_IPV6IFNAME
            char scopeid[IFNAMSIZ];
            if (::if_indextoname(scope, scopeid)) {
                address.setScopeId(QLatin1String(scopeid));
            } else
#endif
                address.setScopeId(QString::number(uint(scope)));
        }
    }
    return address;

}
示例#26
0
void DuktoProtocol::handleMessage(QByteArray &data, QHostAddress &sender)
{
    char msgtype = data.at(0);

    switch(msgtype)
    {
    case MSG_HELLO_BROADCAST:
    case MSG_HELLO_UNICAST:
        data.remove(0, 1);
        if (data != getSystemSignature()) {
            mPeers[sender.toString()] = Peer(sender, QString::fromUtf8(data), DEFAULT_UDP_PORT);
            if (msgtype == MSG_HELLO_BROADCAST) sayHello(sender, DEFAULT_UDP_PORT);
            emit peerListAdded(mPeers[sender.toString()]);
        }
        break;

    case MSG_GOODBYE:
        emit peerListRemoved(mPeers[sender.toString()]);
        mPeers.remove(sender.toString());
        break;

    case MSG_HELLO_PORT_BROADCAST:
    case MSG_HELLO_PORT_UNICAST:
        data.remove(0, 1);
        qint16 port = *((qint16*) data.constData());
        data.remove(0, 2);
        if (data != getSystemSignature()) {
            mPeers[sender.toString()] = Peer(sender, QString::fromUtf8(data), port);
            if (msgtype == MSG_HELLO_PORT_BROADCAST) sayHello(sender, port);
            emit peerListAdded(mPeers[sender.toString()]);
        }
        break;
    }

}
示例#27
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
    }
}
示例#28
0
static QList<UnixIface> get_linux_ipv6_ifaces()
{
	QList<UnixIface> out;

	QStringList lines = read_proc_as_lines("/proc/net/if_inet6");
	for(int n = 0; n < lines.count(); ++n)
	{
		const QString &line = lines[n];
		QStringList parts = line.simplified().split(' ', QString::SkipEmptyParts);
		if(parts.count() < 6)
			continue;

		QString name = parts[5];
		if(name.isEmpty())
			continue;
		QHostAddress addr = linux_ipv6_to_qaddr(parts[0]);
		if(addr.isNull())
			continue;

		QString scopestr = parts[3];
		bool ok;
		unsigned int scope = parts[3].toInt(&ok, 16);
		if(!ok)
			continue;

		// IPV6_ADDR_LOOPBACK    0x0010U
		// IPV6_ADDR_SCOPE_MASK  0x00f0U
		bool loopback = false;
		if((scope & 0x00f0U) == 0x0010U)
			loopback = true;

		UnixIface i;
		i.name = name;
		i.loopback = loopback;
		i.address = addr;
		out += i;
	}

	return out;
}
示例#29
0
void SSDP::PerformSearch(const QString &sST, uint timeout_secs)
{
    timeout_secs = std::max(std::min(timeout_secs, 5U), 1U);
    QString rRequest = QString("M-SEARCH * HTTP/1.1\r\n"
                               "HOST: 239.255.255.250:1900\r\n"
                               "MAN: \"ssdp:discover\"\r\n"
                               "MX: %1\r\n"
                               "ST: %2\r\n"
                               "\r\n")
        .arg(timeout_secs).arg(sST);

    LOG(VB_UPNP, LOG_DEBUG, QString("\n\n%1\n").arg(rRequest));

    QByteArray sRequest = rRequest.toUtf8();

    MSocketDevice *pSocket = m_Sockets[ SocketIdx_Search ];
    if ( !pSocket->isValid() )
    {
        pSocket->setProtocol(MSocketDevice::IPv4);
        pSocket->setSocket(pSocket->createNewSocket(), MSocketDevice::Datagram);
    }

    QHostAddress address;
    address.setAddress( SSDP_GROUP );

    int nSize = sRequest.size();

    if ( pSocket->writeBlock( sRequest.data(),
                              sRequest.size(), address, SSDP_PORT ) != nSize)
        LOG(VB_GENERAL, LOG_INFO,
            "SSDP::PerformSearch - did not write entire buffer.");

    usleep( random() % 250000 );

    if ( pSocket->writeBlock( sRequest.data(),
                              sRequest.size(), address, SSDP_PORT ) != nSize)
        LOG(VB_GENERAL, LOG_INFO,
            "SSDP::PerformSearch - did not write entire buffer.");
}
示例#30
-1
	void ensurePermission(const QHostAddress &addr)
	{
		if(!desiredPerms.contains(addr))
		{
			if(debugLevel >= TurnClient::DL_Info)
				emit q->debugLine(QString("Setting permission for peer address %1").arg(addr.toString()));

			desiredPerms += addr;
			allocate->setPermissions(desiredPerms);
		}
	}