当前位置: 首页>>代码示例>>C++>>正文


C++ QHostAddress函数代码示例

本文整理汇总了C++中QHostAddress函数的典型用法代码示例。如果您正苦于以下问题:C++ QHostAddress函数的具体用法?C++ QHostAddress怎么用?C++ QHostAddress使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了QHostAddress函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: send

void ReceiveThread::send(const char* buffer,int length) {
    if(socket.writeDatagram(buffer,length,QHostAddress(metisip),1024)<0) {
        qDebug()<<"Error: Discovery: writeDatagram failed "<<socket.errorString();
        return;
    }
}
开发者ID:8cH9azbsFifZ,项目名称:ghpsdr3-alex,代码行数:6,代码来源:ReceiveThread.cpp

示例2: on_le_ip_gyro_data_returnPressed

void GyroDataWidget::on_le_ip_gyro_data_returnPressed()
{
	if(!m_model)
		return;
	m_model->set_address(QHostAddress(ui->le_ip_gyro_data->text()), ui->sb_gyro_data->value());
}
开发者ID:artthirt,项目名称:glsamp,代码行数:6,代码来源:gyrodatawidget.cpp

示例3: tr


//.........这里部分代码省略.........
   QCommandLineOption clOptCountT("n", 
         tr("Terminate after reception of <count> CAN frames"),
         tr("count"));
   clCmdParserP.addOption(clOptCountT);
   
   //-----------------------------------------------------------
   // command line option: -t 
   //
   QCommandLineOption clOptTimeStampT("t", 
         tr("Show time-stamp"));
   clCmdParserP.addOption(clOptTimeStampT);

   //-----------------------------------------------------------
   // command line option: -T 
   //
   QCommandLineOption clOptTimeOutT("T", 
         tr("Terminate after <msec> without reception"),
         tr("msec"),
         "0");
   clCmdParserP.addOption(clOptTimeOutT);


   //----------------------------------------------------------------
   // Process the actual command line arguments given by the user
   //
   clCmdParserP.process(*pclAppP);
   const QStringList clArgsT = clCmdParserP.positionalArguments();
   if (clArgsT.size() != 1) 
   {
      fprintf(stderr, "%s\n", 
              qPrintable(tr("Error: Must specify CAN interface.\n")));
      clCmdParserP.showHelp(0);
   }

   
   //----------------------------------------------------------------
   // test format of argument <interface>
   //
   QString clInterfaceT = clArgsT.at(0);
   if(!clInterfaceT.startsWith("can"))
   {
      fprintf(stderr, "%s %s\n", 
              qPrintable(tr("Error: Unknown CAN interface ")),
              qPrintable(clInterfaceT));
      clCmdParserP.showHelp(0);
   }
   
   //-----------------------------------------------------------
   // convert CAN channel to uint8_t value
   //
   QString clIfNumT = clInterfaceT.right(clInterfaceT.size() - 3);
   bool btConversionSuccessT;
   int32_t slChannelT = clIfNumT.toInt(&btConversionSuccessT, 10);
   if((btConversionSuccessT == false) ||
      (slChannelT == 0) )
   {
      fprintf(stderr, "%s \n\n", 
              qPrintable(tr("Error: CAN interface out of range")));
      clCmdParserP.showHelp(0);
   }
   
   //-----------------------------------------------------------
   // store CAN interface channel (CAN_Channel_e)
   //
   ubChannelP = (uint8_t) (slChannelT);

   
   //----------------------------------------------------------------
   // check for time-stamp
   //
   btTimeStampP = clCmdParserP.isSet(clOptTimeStampT);

   
   //----------------------------------------------------------------
   // check for termination options
   //
   btQuitNeverP = true;
   ulQuitCountP = clCmdParserP.value(clOptCountT).toInt(Q_NULLPTR, 10);    
   ulQuitTimeP  = clCmdParserP.value(clOptTimeOutT).toInt(Q_NULLPTR, 10);      
   if ((ulQuitCountP > 0) || (ulQuitTimeP > 0))
   {
      btQuitNeverP = false; 
   }
   
   
   //----------------------------------------------------------------
   // set host address for socket
   //
   if(clCmdParserP.isSet(clOptHostT))
   {
      QHostAddress clAddressT = QHostAddress(clCmdParserP.value(clOptHostT));
      clCanSocketP.setHostAddress(clAddressT);
   }
   
   //----------------------------------------------------------------
   // connect to CAN interface
   //
   clCanSocketP.connectNetwork((CAN_Channel_e) ubChannelP);

}
开发者ID:canpie,项目名称:CANpie,代码行数:101,代码来源:qcan_dump.cpp

示例4: QToxKit

void Tunnelc::init()
{
    m_toxkit = new QToxKit("toxcli", true);
    QObject::connect(m_toxkit, &QToxKit::selfConnectionStatus, this,
                     &Tunnelc::onToxnetSelfConnectionStatus, Qt::QueuedConnection);
    QObject::connect(m_toxkit, &QToxKit::friendConnectionStatus, this,
                     &Tunnelc::onToxnetFriendConnectionStatus, Qt::QueuedConnection);
    QObject::connect(m_toxkit, &QToxKit::friendMessage, this,
                     &Tunnelc::onToxnetFriendMessage, Qt::QueuedConnection);
    QObject::connect(m_toxkit, &QToxKit::friendLossyPacket, this,
                     &Tunnelc::onToxnetFriendLossyPacket, Qt::QueuedConnection);
    QObject::connect(m_toxkit, &QToxKit::friendLosslessPacket, this,
                     &Tunnelc::onToxnetFriendLosslessPacket, Qt::QueuedConnection);
    m_toxkit->start();

    m_enpoll = new ENetPoll();
    QObject::connect(m_enpoll, &ENetPoll::connected, this, &Tunnelc::onENetPeerConnected, Qt::QueuedConnection);
    QObject::connect(m_enpoll, &ENetPoll::disconnected, this, &Tunnelc::onENetPeerDisconnected, Qt::QueuedConnection);
    QObject::connect(m_enpoll, &ENetPoll::packetReceived, this, &Tunnelc::onENetPeerPacketReceived, Qt::QueuedConnection);
    m_enpoll->start();

    ENetAddress enaddr = {ENET_HOST_ANY, 7766};
    enet_address_set_host(&enaddr, "127.0.0.1");
    enaddr.vaddr = SELF_FRIEND_NUMBER;
    ENetHost *encli = NULL;

    // m_encli = encli = enet_host_create(&enaddr, 932, 2, 0, 0);
    m_encli = encli = enet_host_create_notp(&enaddr, 932, 2, 0, 0);
    // encli->mtu = 1261;  // 在这设置无效 // ENET_HOST_DEFAULT_MTU=1400
    // m_encli = encli = enet_host_create(NULL, 1, 2, 0, 0);
    qDebug()<<encli<<encli->peerCount<<encli->mtu;
    encli->toxkit = this;
    encli->enet_socket_send = toxenet_socket_send;
    encli->enet_socket_receive = toxenet_socket_receive;
    // encli->compressor.context = (void*)0x1;
    // encli->compressor.compress = enet_simple_compress;
    // encli->compressor.decompress = enet_simple_decompress;
    // encli->compressor.destroy = enet_simple_destroy;
    // enet_host_compress(encli, this->createCompressor());

    
    // transport
    const ENetTransport *transport = this->createToxTransport();
    // m_transport.send = toxenet_socket_send;
    // m_transport.recv = toxenet_socket_receive;
    m_transport.enet_transport_send = toxenet_socket_send;
    m_transport.enet_transport_recv = toxenet_socket_receive;
    enet_host_transport(encli, transport);
    
    m_enpoll->addENetHost(encli);

    int idx = 0;
    foreach (const ToxTunRecord &rec, this->m_cfg->m_recs) {
        QTcpServer *tcpsrv = new QTcpServer();
        QObject::connect(tcpsrv, &QTcpServer::newConnection, this, &Tunnelc::onNewTcpConnection, Qt::QueuedConnection);

        tcpsrv->listen(QHostAddress("127.0.0.1"), rec.m_local_port);
        // tcpsrv->listen(QHostAddress::Any, 7766);
        this->m_tcpsrvs[tcpsrv] = idx++;
    }
}
开发者ID:kitech,项目名称:toxsh,代码行数:61,代码来源:tunnelc.cpp

示例5: memset

QT_BEGIN_NAMESPACE

void QDnsLookupRunnable::query(const int requestType, const QByteArray &requestName, const QHostAddress &nameserver, QDnsLookupReply *reply)
{
    // Perform DNS query.
    PDNS_RECORD dns_records = 0;
    const QString requestNameUtf16 = QString::fromUtf8(requestName.data(), requestName.size());
    IP4_ARRAY srvList;
    memset(&srvList, 0, sizeof(IP4_ARRAY));
    if (!nameserver.isNull()) {
        if (nameserver.protocol() == QAbstractSocket::IPv4Protocol) {
            // The below code is referenced from: http://support.microsoft.com/kb/831226
            srvList.AddrCount = 1;
            srvList.AddrArray[0] = htonl(nameserver.toIPv4Address());
        } else if (nameserver.protocol() == QAbstractSocket::IPv6Protocol) {
            // For supoprting IPv6 nameserver addresses, we'll need to switch
            // from DnsQuey() to DnsQueryEx() as it supports passing an IPv6
            // address in the nameserver list
            qWarning() << Q_FUNC_INFO << "IPv6 addresses for nameservers is currently not supported";
            reply->error = QDnsLookup::ResolverError;
            reply->errorString = tr("IPv6 addresses for nameservers is currently not supported");
            return;
        }
    }
    const DNS_STATUS status = DnsQuery_W(reinterpret_cast<const wchar_t*>(requestNameUtf16.utf16()), requestType, DNS_QUERY_STANDARD, &srvList, &dns_records, NULL);
    switch (status) {
    case ERROR_SUCCESS:
        break;
    case DNS_ERROR_RCODE_FORMAT_ERROR:
        reply->error = QDnsLookup::InvalidRequestError;
        reply->errorString = tr("Server could not process query");
        return;
    case DNS_ERROR_RCODE_SERVER_FAILURE:
        reply->error = QDnsLookup::ServerFailureError;
        reply->errorString = tr("Server failure");
        return;
    case DNS_ERROR_RCODE_NAME_ERROR:
        reply->error = QDnsLookup::NotFoundError;
        reply->errorString = tr("Non existent domain");
        return;
    case DNS_ERROR_RCODE_REFUSED:
        reply->error = QDnsLookup::ServerRefusedError;
        reply->errorString = tr("Server refused to answer");
        return;
    default:
        reply->error = QDnsLookup::InvalidReplyError;
        reply->errorString = QSystemError(status, QSystemError::NativeError).toString();
        return;
    }

    // Extract results.
    for (PDNS_RECORD ptr = dns_records; ptr != NULL; ptr = ptr->pNext) {
        const QString name = QUrl::fromAce( QString::fromWCharArray( ptr->pName ).toLatin1() );
        if (ptr->wType == QDnsLookup::A) {
            QDnsHostAddressRecord record;
            record.d->name = name;
            record.d->timeToLive = ptr->dwTtl;
            record.d->value = QHostAddress(ntohl(ptr->Data.A.IpAddress));
            reply->hostAddressRecords.append(record);
        } else if (ptr->wType == QDnsLookup::AAAA) {
            Q_IPV6ADDR addr;
            memcpy(&addr, &ptr->Data.AAAA.Ip6Address, sizeof(Q_IPV6ADDR));

            QDnsHostAddressRecord record;
            record.d->name = name;
            record.d->timeToLive = ptr->dwTtl;
            record.d->value = QHostAddress(addr);
            reply->hostAddressRecords.append(record);
        } else if (ptr->wType == QDnsLookup::CNAME) {
            QDnsDomainNameRecord record;
            record.d->name = name;
            record.d->timeToLive = ptr->dwTtl;
            record.d->value = QUrl::fromAce(QString::fromWCharArray(ptr->Data.Cname.pNameHost).toLatin1());
            reply->canonicalNameRecords.append(record);
        } else if (ptr->wType == QDnsLookup::MX) {
            QDnsMailExchangeRecord record;
            record.d->name = name;
            record.d->exchange = QUrl::fromAce(QString::fromWCharArray(ptr->Data.Mx.pNameExchange).toLatin1());
            record.d->preference = ptr->Data.Mx.wPreference;
            record.d->timeToLive = ptr->dwTtl;
            reply->mailExchangeRecords.append(record);
        } else if (ptr->wType == QDnsLookup::NS) {
            QDnsDomainNameRecord record;
            record.d->name = name;
            record.d->timeToLive = ptr->dwTtl;
            record.d->value = QUrl::fromAce(QString::fromWCharArray(ptr->Data.Ns.pNameHost).toLatin1());
            reply->nameServerRecords.append(record);
        } else if (ptr->wType == QDnsLookup::PTR) {
            QDnsDomainNameRecord record;
            record.d->name = name;
            record.d->timeToLive = ptr->dwTtl;
            record.d->value = QUrl::fromAce(QString::fromWCharArray(ptr->Data.Ptr.pNameHost).toLatin1());
            reply->pointerRecords.append(record);
        } else if (ptr->wType == QDnsLookup::SRV) {
            QDnsServiceRecord record;
            record.d->name = name;
            record.d->target = QUrl::fromAce(QString::fromWCharArray(ptr->Data.Srv.pNameTarget).toLatin1());
            record.d->port = ptr->Data.Srv.wPort;
            record.d->priority = ptr->Data.Srv.wPriority;
            record.d->timeToLive = ptr->dwTtl;
//.........这里部分代码省略.........
开发者ID:venkatarajasekhar,项目名称:Qt,代码行数:101,代码来源:qdnslookup_win.cpp

示例6: while

void MainWindow::readyRead()
{

    char data[128];
    QHostAddress addr;
    quint16 port;
    while(_udpSocket->bytesAvailable())
    {
        _udpSocket->readDatagram(data, udpDataSize, &addr, &port);
        char ch = data[4];
        switch(ch)
        {
        case RSP::QUERY_OUTPUT:
        {
            char buff[128];
            RSP::QueryOutput queryOutput(data+5);
            createRowDownloader(QString::fromStdString(queryOutput.getFileName()),
                                QString::fromStdString(queryOutput.getIpAddr()),queryOutput.getPort());
            RSP::AckFromServer ackFromServer(queryOutput.getSeq(),CMD::ACK_CONTENT_FROM_SERVER);
            ackFromServer.dump();
            ackFromServer.serialize(buff);
            qDebug()<<"Bytes written for Query Output Ack:"<<_udpSocket->writeDatagram(buff,udpDataSize,QHostAddress(_serverInfo->getServerIp()),
                                      _serverInfo->getServerPort());
            _udpSocket->waitForBytesWritten();
        }
            break;
        case RSP::ACK_INFORM_AND_UPDATE_SERVER:
        {
            RSP::AckFromServer ackFromServer(data+5);
            if(!_ackSeqList.contains(ackFromServer.getSeq()))
            {
                _ackSeqList.append(ackFromServer.getSeq());
                if(_timerAckMap.contains(ackFromServer.getSeq()))
                {
                 setSampleRtt(_timerAckMap[ackFromServer.getSeq()]->getTimeElapsed());
                _timerAckMap[ackFromServer.getSeq()]->stopTimer();
                }
                qDebug()<<"timer for ACK "+ QString::number(ackFromServer.getSeq()) +" stopped";

            }
        }
            break;
        default:
            qDebug()<<"UNKNOWN COMMAND";
        }
    }
}
开发者ID:openArrow,项目名称:PeerToPeerClient,代码行数:47,代码来源:mainwindow.cpp

示例7: i18n


//.........这里部分代码省略.........
            break;
        case 1:
            data.insert(NM_VPNC_KEY_XAUTH_PASSWORD"-flags", QString::number(NetworkManager::Setting::AgentOwned));
            break;
        case 2:
            data.insert(NM_VPNC_KEY_XAUTH_PASSWORD"-flags", QString::number(NetworkManager::Setting::NotRequired));
            break;
        }

        // group password
        if (!decrPlugin->readStringKeyValue(cg,"GroupPwd").isEmpty()) {
            secretData.insert(NM_VPNC_KEY_SECRET, decrPlugin->readStringKeyValue(cg,"GroupPwd"));
            data.insert(NM_VPNC_KEY_SECRET"-flags", QString::number(NetworkManager::Setting::AgentOwned));
        } else if (!decrPlugin->readStringKeyValue(cg,"enc_GroupPwd").isEmpty() && !ciscoDecryptBinary.isEmpty()) {
            //Decrypt the password and insert into map
            decrPlugin->ciscoDecrypt->setProgram(ciscoDecryptBinary);
            decrPlugin->ciscoDecrypt->start();
            decrPlugin->ciscoDecrypt->waitForStarted();
            decrPlugin->ciscoDecrypt->write(decrPlugin->readStringKeyValue(cg,"enc_GroupPwd").toUtf8());
            if (decrPlugin->ciscoDecrypt->waitForFinished()) {
                secretData.insert(NM_VPNC_KEY_SECRET, decrPlugin->decryptedPasswd);
                data.insert(NM_VPNC_KEY_SECRET"-flags", QString::number(NetworkManager::Setting::AgentOwned));
            }
        }

        // Auth Type
        if (!cg.readEntry("AuthType").isEmpty() && cg.readEntry("AuthType").toInt() == 5) {
            data.insert(NM_VPNC_KEY_AUTHMODE, QLatin1String("hybrid"));
        }

        // Optional settings
        // username
        if (!decrPlugin->readStringKeyValue(cg,"Username").isEmpty()) {
            data.insert(NM_VPNC_KEY_XAUTH_USER, decrPlugin->readStringKeyValue(cg,"Username"));
        }
        // domain
        if (!decrPlugin->readStringKeyValue(cg,"NTDomain").isEmpty()) {
            data.insert(NM_VPNC_KEY_DOMAIN, decrPlugin->readStringKeyValue(cg,"NTDomain"));
        }
        // encryption
        if (!cg.readEntry("SingleDES").isEmpty() && cg.readEntry("SingleDES").toInt() != 0) {
            data.insert(NM_VPNC_KEY_SINGLE_DES, QLatin1String("yes"));
        }
        /* Disable all NAT Traversal if explicit EnableNat=0 exists, otherwise
         * default to NAT-T which is newer and standardized.  If EnableNat=1, then
         * use Cisco-UDP like always; but if the key "X-NM-Use-NAT-T" is set, then
         * use NAT-T.  If the key "X-NM-Force-NAT-T" is set then force NAT-T always
         * on.  See vpnc documentation for more information on what the different
         * NAT modes are.
         */
        // enable NAT
        if (cg.readEntry("EnableNat").toInt() == 1) {
            data.insert(NM_VPNC_KEY_NAT_TRAVERSAL_MODE, QLatin1String(NM_VPNC_NATT_MODE_CISCO));
            // NAT traversal
            if (!cg.readEntry("X-NM-Use-NAT-T").isEmpty()) {
                if (cg.readEntry("X-NM-Use-NAT-T").toInt() == 1) {
                    data.insert(NM_VPNC_KEY_NAT_TRAVERSAL_MODE, QLatin1String(NM_VPNC_NATT_MODE_NATT));
                }
                if (cg.readEntry("X-NM-Force-NAT-T").toInt() == 1) {
                    data.insert(NM_VPNC_KEY_NAT_TRAVERSAL_MODE, QLatin1String(NM_VPNC_NATT_MODE_NATT_ALWAYS));
                }
            }
        } else {
            data.insert(NM_VPNC_KEY_NAT_TRAVERSAL_MODE, QLatin1String(NM_VPNC_NATT_MODE_NONE));
        }
        // dead peer detection
        data.insert(NM_VPNC_KEY_DPD_IDLE_TIMEOUT, cg.readEntry("PeerTimeout"));
        // UseLegacyIKEPort=0 uses dynamic source IKE port instead of 500.
        if (cg.readEntry("UseLegacyIKEPort").isEmpty() || cg.readEntry("UseLegacyIKEPort").toInt() != 0) {
            data.insert(NM_VPNC_KEY_LOCAL_PORT, QString::number(NM_VPNC_LOCAL_PORT_DEFAULT));
        }
        // DH Group
        data.insert(NM_VPNC_KEY_DHGROUP, decrPlugin->readStringKeyValue(cg,"DHGroup"));
        // Tunneling Mode - not supported by vpnc
        if (cg.readEntry("TunnelingMode").toInt() == 1) {
            KMessageBox::error(0, i18n("The VPN settings file '%1' specifies that VPN traffic should be tunneled through TCP which is currently not supported in the vpnc software.\n\nThe connection can still be created, with TCP tunneling disabled, however it may not work as expected.", fileName), i18n("Not supported"), KMessageBox::Notify);
        }
        // EnableLocalLAN and X-NM-Routes are to be added to IPv4Setting
        if (!cg.readEntry("EnableLocalLAN").isEmpty()) {
            ipv4Data.insert("never-default", cg.readEntry("EnableLocalLAN"));
        }
        if (!decrPlugin->readStringKeyValue(cg,"X-NM-Routes").isEmpty()) {
            QList<NetworkManager::IpRoute> list;
            Q_FOREACH (const QString &route, decrPlugin->readStringKeyValue(cg,"X-NM-Routes").split(' ')) {
                NetworkManager::IpRoute ipRoute;
                ipRoute.setIp(QHostAddress(route.split('/').first()));
                ipRoute.setPrefixLength(route.split('/').at(1).toInt());
                list << ipRoute;
            }
            QList<QList<uint> > dbusRoutes;
            Q_FOREACH (const NetworkManager::IpRoute &route, list) {
                QList<uint> dbusRoute;
                dbusRoute << htonl(route.ip().toIPv4Address())
                        << route.prefixLength()
                        << htonl(route.nextHop().toIPv4Address())
                        << route.metric();
                dbusRoutes << dbusRoute;
            }
            ipv4Data.insert("routes", QVariant::fromValue(dbusRoutes));
        }
开发者ID:KDE,项目名称:plasma-nm,代码行数:101,代码来源:vpnc.cpp

示例8: values

Response::ResponseCode ServerSocketInterface::cmdBanFromServer(const Command_BanFromServer &cmd, ResponseContainer & /*rc*/)
{
    if (!sqlInterface->checkSql())
        return Response::RespInternalError;

    QString userName = QString::fromStdString(cmd.user_name());
    QString address = QString::fromStdString(cmd.address());
    QString trustedSources = settingsCache->value("server/trusted_sources","127.0.0.1,::1").toString();
    int minutes = cmd.minutes();
    if (trustedSources.contains(address,Qt::CaseInsensitive))
        address = "";

    QSqlQuery *query = sqlInterface->prepareQuery("insert into {prefix}_bans (user_name, ip_address, id_admin, time_from, minutes, reason, visible_reason, clientid) values(:user_name, :ip_address, :id_admin, NOW(), :minutes, :reason, :visible_reason, :client_id)");
    query->bindValue(":user_name", userName);
    query->bindValue(":ip_address", address);
    query->bindValue(":id_admin", userInfo->id());
    query->bindValue(":minutes", minutes);
    query->bindValue(":reason", QString::fromStdString(cmd.reason()));
    query->bindValue(":visible_reason", QString::fromStdString(cmd.visible_reason()));
    query->bindValue(":client_id", QString::fromStdString(cmd.clientid()));
    sqlInterface->execSqlQuery(query);

    servatrice->clientsLock.lockForRead();
    QList<ServerSocketInterface *> userList = servatrice->getUsersWithAddressAsList(QHostAddress(address));

    if (!userName.isEmpty()) {
        ServerSocketInterface *user = static_cast<ServerSocketInterface *>(server->getUsers().value(userName));
        userList.append(user);
    }

    if (userName.isEmpty() && address.isEmpty()) {
        QSqlQuery *query = sqlInterface->prepareQuery("select name from {prefix}_users where clientid = :client_id");
        query->bindValue(":client_id", QString::fromStdString(cmd.clientid()));
        sqlInterface->execSqlQuery(query);
        if (!sqlInterface->execSqlQuery(query)){
            qDebug("ClientID username ban lookup failed: SQL Error");
        } else {
            while (query->next()) {
                userName = query->value(0).toString();
                ServerSocketInterface *user = static_cast<ServerSocketInterface *>(server->getUsers().value(userName));
                if (user && !userList.contains(user))
                   userList.append(user);
            }
        }
    }

    if (!userList.isEmpty()) {
        Event_ConnectionClosed event;
        event.set_reason(Event_ConnectionClosed::BANNED);
        if (cmd.has_visible_reason())
            event.set_reason_str(cmd.visible_reason());
        if (minutes)
            event.set_end_time(QDateTime::currentDateTime().addSecs(60 * minutes).toTime_t());
        for (int i = 0; i < userList.size(); ++i) {
            SessionEvent *se = userList[i]->prepareSessionEvent(event);
            userList[i]->sendProtocolItem(*se);
            delete se;
            QMetaObject::invokeMethod(userList[i], "prepareDestroy", Qt::QueuedConnection);
        }
    }
    servatrice->clientsLock.unlock();

    return Response::RespOk;
}
开发者ID:GuiSaiz,项目名称:Cockatrice,代码行数:64,代码来源:serversocketinterface.cpp

示例9: qDebug

//当PeopVSPeop tcp监听成功时,触发该槽
//向FindServer发送指令,让其连接TCP
void BuildServer::onListenSuccess()
{
    qDebug() << "BuildServer recieved listenSuccess() signal, command PleaseConnect to FindServer";
    QByteArray datagram = "PleaseConnect" ;
    udpServer->writeDatagram( datagram.data() , datagram.size() , QHostAddress( IP ) , 7758 ) ;
}
开发者ID:Allen-smith,项目名称:Renju,代码行数:8,代码来源:buildserver.cpp

示例10: main

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

        //help output
        if(a.arguments().contains("help"))
        {
            MSG("### OSCGrabber HELP ###");
            MSG(" ");
            MSG("The following Arguments are available:");
            MSG("   osc-server-address (address to send osc messages to) [default: 127.0.0.1]");
            MSG("   osc-send-port      (port to send osc messages to) [default: 7000]");
            MSG("   osc-listen-port    (port on wich OSCGrabber is listening for incomming osc messages) [default: 9001]");
            MSG("   udp-send-address   (address to send udp converted messages to) [default: 127.0.0.1]");
            MSG("   udp-send-port      (port to send udp converted messages to) [default: 7799]");
            MSG("   udp-listen-port    (port on wich OSCGrabber is listening for incomming udp messages) [default: 7788]");
            MSG(" ");
            MSG("examaple calls:");
            MSG("   OSCGrabber osc-listen-port 7000 osc-server-address 1.2.3.4");
            MSG(" ");
            MSG("Type 'help' for this message.");
            a.exit();
            return a.exec();
        }

        //read command line arguments
        int oscListenPort = 9001;
        if(a.arguments().contains("osc-listen-port"))
            oscListenPort = a.arguments().at(a.arguments().indexOf(QRegExp("osc-listen-port"))+1).toInt();

        QString oscServerAddress = "127.0.0.1";
        if(a.arguments().contains("osc-server-address"))
            oscServerAddress = a.arguments().at(a.arguments().indexOf(QRegExp("osc-server-address"))+1);

        int oscSendPort = 9000;
        if(a.arguments().contains("osc-send-port"))
            oscSendPort = a.arguments().at(a.arguments().indexOf(QRegExp("osc-send-port"))+1).toInt();

        int udpSendPort = 7799;
        if(a.arguments().contains("udp-send-port"))
            udpSendPort = a.arguments().at(a.arguments().indexOf(QRegExp("udp-send-port"))+1).toInt();

        QString udpSendAddress = "127.0.0.1";
        if(a.arguments().contains("udp-send-address"))
            udpSendAddress = a.arguments().at(a.arguments().indexOf(QRegExp("udp-send-address"))+1);

        int udpListenPort = 7788;
        if(a.arguments().contains("udp-listen-port"))
            udpListenPort = a.arguments().at(a.arguments().indexOf(QRegExp("udp-listen-port"))+1).toInt();


        //start creating the services
        MSG("### [Creating] UDP service at Port "<<udpListenPort);
        MSG("### Sending to "<<udpSendAddress.toStdString());
        QUdpSocket *listenSocket = new QUdpSocket(&a);
        listenSocket->bind(QHostAddress::AnyIPv4, udpListenPort);

        if(!listenSocket->isValid())
        {
            MSG("Couldn't creat udp service at port "<<udpSendPort<<" . Port already occupied?");
            a.exit();
            return 0; //a.exec();
        }

        MSG("### [Launching] OSC Bridge to address "<<oscServerAddress.toStdString()<<" "<<oscListenPort)
        lo::ServerThread * server = new lo::ServerThread(oscListenPort);
        server->start();

        if (!server->is_valid()) { //this check isn't working. why?
            MSG("Couldn't creat osc service listening to port "<<oscListenPort<<" . Port already occupied?");
            a.exit();
            return 0; //a.exec();
        }
        MSG("### --> Listening to Port: "<<oscListenPort);

        lo::string_type address(oscServerAddress.toStdString());
        lo::Address * oscSender = new lo::Address(address, oscSendPort);

//        lo::Address * oscSender = new lo::Address("localhost", oscSendPort);
        MSG("### --> Writing on Port: "<<oscSendPort);


        //####################################################################################
        //####################################################################################
        //  OSC to UDP
        //####################################################################################
        //####################################################################################

        QUdpSocket *senderSocket = new QUdpSocket(&a);

        server->add_method(NULL, NULL, [=](const char *path, const lo::Message& msg)
        {
//            msg.print();
            QString type = QString::fromStdString(msg.types());
            QString data(path);
            data.append("%");
            data.append(type);
            data.append("%");

            for (int i = 0; i < msg.argc(); i++) {
//.........这里部分代码省略.........
开发者ID:fassnacht,项目名称:OSCGrabber,代码行数:101,代码来源:main.cpp

示例11: isLoopbackAddress

 bool isLoopbackAddress(const QHostAddress &addr)
 {
     return (addr == QHostAddress::LocalHost)
             || (addr == QHostAddress::LocalHostIPv6)
             || (addr == QHostAddress(QLatin1String("::ffff:127.0.0.1")));
 }
开发者ID:zywo,项目名称:qBittorrent,代码行数:6,代码来源:net.cpp

示例12: isValidIP

 bool isValidIP(const QString &ip)
 {
     return !QHostAddress(ip).isNull();
 }
开发者ID:zywo,项目名称:qBittorrent,代码行数:4,代码来源:net.cpp

示例13: QDialog

Client::Client(QWidget *parent) : QDialog(parent)
{
    hostLabel = new QLabel(tr("&Server name:"));
    portLabel = new QLabel(tr("S&erver port:"));

    // find out which IP to connect to
    QString ipAddress;
    QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
    // use the first non-localhost IPv4 address
    for (int i = 0; i < ipAddressesList.size(); ++i) {
        if (ipAddressesList.at(i) != QHostAddress::LocalHost &&
            ipAddressesList.at(i).toIPv4Address()) {
            ipAddress = ipAddressesList.at(i).toString();
            break;
        }
    }
    // if we did not find one, use IPv4 localhost
    if (ipAddress.isEmpty())
        ipAddress = QHostAddress(QHostAddress::LocalHost).toString();

    hostLineEdit = new QLineEdit(ipAddress);
    portLineEdit = new QLineEdit;
    portLineEdit->setValidator(new QIntValidator(1, 65535, this));

    hostLabel->setBuddy(hostLineEdit);
    portLabel->setBuddy(portLineEdit);

    statusLabel = new QLabel(tr("This examples requires that you run the "
                                "Secure Fortune Server example as well."));

    getFortuneButton = new QPushButton(tr("Get Fortune"));
    getFortuneButton->setDefault(true);
    getFortuneButton->setEnabled(false);

    quitButton = new QPushButton(tr("Quit"));

    buttonBox = new QDialogButtonBox;
    buttonBox->addButton(getFortuneButton, QDialogButtonBox::ActionRole);
    buttonBox->addButton(quitButton, QDialogButtonBox::RejectRole);

    secureSocket = new QSslSocket(this);

    // special slot to handle errors with the certificates
    // in particular the fact that they are self-signed
    connect(secureSocket, SIGNAL(sslErrors(QList<QSslError>)), this,
            SLOT(handleSSLError(QList<QSslError>)));

    connect(hostLineEdit, SIGNAL(textChanged(QString)),
            this, SLOT(enableGetFortuneButton()));
    connect(portLineEdit, SIGNAL(textChanged(QString)),
            this, SLOT(enableGetFortuneButton()));
    connect(getFortuneButton, SIGNAL(clicked()),
            this, SLOT(requestNewFortune()));
    connect(quitButton, SIGNAL(clicked()), this, SLOT(close()));
    connect(secureSocket, SIGNAL(readyRead()), this, SLOT(readFortune()));
    connect(secureSocket, SIGNAL(error(QAbstractSocket::SocketError)),
            this, SLOT(displayError(QAbstractSocket::SocketError)));

    QGridLayout *mainLayout = new QGridLayout;
    mainLayout->addWidget(hostLabel, 0, 0);
    mainLayout->addWidget(hostLineEdit, 0, 1);
    mainLayout->addWidget(portLabel, 1, 0);
    mainLayout->addWidget(portLineEdit, 1, 1);
    mainLayout->addWidget(statusLabel, 2, 0, 1, 2);
    mainLayout->addWidget(buttonBox, 3, 0, 1, 2);
    setLayout(mainLayout);

    setWindowTitle(tr("Secure Fortune Client"));
    portLineEdit->setFocus();
}
开发者ID:skralick,项目名称:ECE3574HW7,代码行数:70,代码来源:client.cpp

示例14: QDialog

Client::Client(QWidget *parent)
    : QDialog(parent), networkSession(0)
{
	 // find out which IP to connect to
	QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
	// use the first non-localhost IPv4 address
	for (int i = 0; i < ipAddressesList.size(); ++i) {
		if (ipAddressesList.at(i) != QHostAddress::LocalHost &&
			ipAddressesList.at(i).toIPv4Address()) {
			ipAddress = ipAddressesList.at(i).toString();
			break;
		}
	}
	// if we did not find one, use IPv4 localhost
	if (ipAddress.isEmpty())
		ipAddress = QHostAddress(QHostAddress::LocalHost).toString();

	userLabel = new QLabel("Username: ");
	passLabel = new QLabel("Password: ");
	statusLabel = new QLabel();

	userLineEdit = new QLineEdit();
	passLineEdit = new QLineEdit();
	passLineEdit->setEchoMode(QLineEdit::Password);

	registerButton = new QPushButton("Register");
	loginButton = new QPushButton("Login");
	cancelButton = new QPushButton("Cancel");

	buttonBox = new QDialogButtonBox();
	buttonBox->addButton(registerButton, QDialogButtonBox::ActionRole);
	buttonBox->addButton(loginButton, QDialogButtonBox::ActionRole);
	buttonBox->addButton(cancelButton, QDialogButtonBox::RejectRole);

	mainLayout = new QGridLayout;
	mainLayout->addWidget(userLabel, 0, 0, 1, 2);
	mainLayout->addWidget(userLineEdit, 1, 0, 1, 5);
	mainLayout->addWidget(passLabel, 2, 0, 1, 2);
	mainLayout->addWidget(passLineEdit, 3, 0, 1, 5);
	mainLayout->addWidget(statusLabel, 4, 0, 3, 4);
	mainLayout->addWidget(buttonBox, 7, 1, 1, 2);

	setLayout(mainLayout);

	tcpSocket = new QTcpSocket(this);

	connect(registerButton, SIGNAL(clicked()), this, SLOT(registerWithServer()));
	connect(cancelButton, SIGNAL(clicked()), this, SLOT(close()));
	connect(loginButton, SIGNAL(clicked()), this, SLOT(requestNewConnection()));
	connect(tcpSocket, SIGNAL(connected()), this, SLOT(sendLoginInfo()));
	connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(updateLabels()));
	//connect(tcpSocket, SIGNAL(disconnected()), this, SLOT(connectionClosedByServer()));

	QNetworkConfigurationManager manager;
	if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired) {
		// Get saved network configuration
		QSettings settings(QSettings::UserScope, QLatin1String("Trolltech"));
		settings.beginGroup(QLatin1String("QtNetwork"));
		const QString id = settings.value(QLatin1String("DefaultNetworkConfiguration")).toString();
		settings.endGroup();

		// If the saved network configuration is not currently discovered use the system default
		QNetworkConfiguration config = manager.configurationFromIdentifier(id);
		if ((config.state() & QNetworkConfiguration::Discovered) !=
			QNetworkConfiguration::Discovered) {
			config = manager.defaultConfiguration();
		}

		networkSession = new QNetworkSession(config, this);
		connect(networkSession, SIGNAL(opened()), this, SLOT(sessionOpened()));

		statusLabel->setText(tr("Opening network session."));
		networkSession->open();
	}

}
开发者ID:mickelfeng,项目名称:Threaded-Client-Server-Application,代码行数:76,代码来源:client.cpp

示例15: Q_UNUSED

void QxtMDNSPrivate::avahiRecordBrowserCallback(AvahiRecordBrowser *b, AvahiIfIndex interface, AvahiProtocol protocol, AvahiBrowserEvent event, const char *name, uint16_t clazz, uint16_t type, const void *rdata, size_t size, AvahiLookupResultFlags flags, void *userdata)
{
	///@TODO Support IPv6
	Q_UNUSED(interface);
	Q_UNUSED(protocol);
	Q_UNUSED(name);
	Q_UNUSED(clazz);
	Q_UNUSED(type);
	Q_UNUSED(size);
	Q_UNUSED(flags);
	QxtMDNSPrivate* self = static_cast<QxtMDNSPrivate*>(userdata);
	self->recordbrowser = b;
// 	qDebug() << "Return thing" << md->name << name << size;
	switch (event)
	{
		case AVAHI_BROWSER_NEW:
		{
			//Found an entry!
			uint32_t ip = qFromBigEndian(*static_cast<const uint32_t*>(rdata));
			if (self->sent)
			{
				QHostInfo info(self->info.lookupId());
				info.setAddresses(QList<QHostAddress>() << QHostAddress(ip));
				QMetaObject::invokeMethod(self->receiver, self->member, Q_ARG(QHostInfo, info));
			}
			else
			{
				self->addresses << QHostAddress(ip);
			}
			break;
		}
		case AVAHI_BROWSER_REMOVE:
		{
			uint32_t ip = qFromBigEndian(*static_cast<const uint32_t*>(rdata));
			self->addresses.removeAll(QHostAddress(ip));
			break;
		}
		case AVAHI_BROWSER_CACHE_EXHAUSTED:
			break;
		case AVAHI_BROWSER_ALL_FOR_NOW:
			if (self->addresses.count() == 0)
			{
				self->info.setError(QHostInfo::HostNotFound);
				self->info.setErrorString("The host was not found.");
			}
			else
			{
				self->info.setAddresses(self->addresses);
				self->addresses.clear();
			}
			QMetaObject::invokeMethod(self->receiver, self->member, Q_ARG(QHostInfo, self->info));
			self->sent = true;
			break;
		case AVAHI_BROWSER_FAILURE:

			if (self->sent)
			{
				QHostInfo info(self->info.lookupId());
				info.setError(QHostInfo::UnknownError);
				info.setErrorString(avahi_strerror(avahi_client_errno(self->client)));
				info.setAddresses(self->addresses);
				QMetaObject::invokeMethod(self->receiver, self->member, Q_ARG(QHostInfo, info));
			}
			else
			{
				self->info.setError(QHostInfo::UnknownError);
				self->info.setErrorString(avahi_strerror(avahi_client_errno(self->client)));
				self->info.setAddresses(self->addresses);
				self->addresses.clear();
				QMetaObject::invokeMethod(self->receiver, self->member, Q_ARG(QHostInfo, self->info));
				self->sent = true;
			}
			break;
	}
}
开发者ID:develnk,项目名称:qxtweb-qt5,代码行数:75,代码来源:qxtmdns_avahi.cpp


注:本文中的QHostAddress函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。