示例#1
0
// Отправка измененных данных в главное окно
void serverEdit::on_save_clicked() {
    qInfo() << "serverEdit::on_save_clicked: Send start";

    // Создаем экземпляр класса favServer
    favServer server;
    // Заполняем его информацией из виджетов..
    //..параметров сервера
    server.serverName = ui->serverName->text();
    server.serverIP = ui->serverIP->text();
    server.serverPort = ui->serverPort->text();
    server.serverPass = ui->serverPassword->text();
    server.check_name = ui->name_check->isChecked();
    server.name = ui->name->currentText();

    //..Конвертируем Url в IP
    //..проверяем, IP ли это
    bool isIP = true;
    int pointCount = 0;
    int numberCount = 0;
    for(int i = 0; i< server.serverIP.size();i++) {
        if(server.serverIP[i].isNumber()) {
            isIP = true;
            numberCount++;
        } else if (server.serverIP[i] == '.') {
            isIP = true;
            pointCount++;
        } else {
            isIP = false;
            break;
        }
    }
    // Если это IP - проверяем его корректность
    if(isIP) { //127.0.0.1
        if(pointCount < 3 || numberCount <4 || numberCount > 12) {
            QMessageBox::warning(this,tr("Внимание!"), tr("Некорректный IP адресс сервера.\nВведите правильный IP сервера или его Url.\nПример: \"127.0.0.1\", \"example.server.com\"\nТип ошибки: IP Adress INCORRECT"), QMessageBox::Ok);
            qInfo() << "serverEdit::on_save_clicked: IP Adress INCORRECT";
            return;
        }
    // Если это Url - конвертируем в IP
    } else {
        QHostInfo info = QHostInfo::fromName(server.serverIP);
        if(info.errorString() == "Unknown error") {
            server.serverIP = info.addresses()[0].toString();
        } else {
            QMessageBox::warning(this,tr("Внимание!"), tr("Некорректный адресс сервера.\nВведите правильный IP сервера или его Url.\nПример: \"127.0.0.1\", \"example.server.com\"\nТип ошибки: ")+info.errorString(), QMessageBox::Ok);
            qInfo() << "serverEdit::on_save_clicked: " << info.errorString();
            return;
        }
    }

    //..активированных аддонов
    for(int i = 0;i<ui->addonTree->topLevelItemCount();i++)
        if(ui->addonTree->topLevelItem(i)->checkState(0) == Qt::Checked)
            server.serverAddons.append(ui->addonTree->topLevelItem(i)->text(2) + "/" +ui->addonTree->topLevelItem(i)->text(1));

    // Передаем экземпляр в сигнал
    emit sendData(server, newServ);
    this->close();
}
示例#2
0
static QScriptValue qhostinfo_fromName(QScriptContext *context, QScriptEngine *engine)
{
    QHostInfo obj;
    QScriptValue scriptlist = engine->newObject();

    if (context->argumentCount() == 1 && context->argument(0).isString()) {
        obj = QHostInfo::fromName(context->argument(0).toString());
        QScriptValue addressList = engine->newObject();
        QList<QHostAddress> qlist = obj.addresses();
        for (int i = 0; i < qlist.size(); i += 1) {
            addressList.setProperty(i, qlist[i].toString());
        }
        scriptlist.setProperty("addresses",   addressList);
        scriptlist.setProperty("error",       obj.error());
        if (obj.error() > 0) {
            scriptlist.setProperty("errorString", obj.errorString());
        }
        else {
            scriptlist.setProperty("errorString", "No Error");
        }
        scriptlist.setProperty("hostName",    obj.hostName());
        scriptlist.setProperty("lookupId",    obj.lookupId());
    }

    return scriptlist;
}
示例#3
0
QString QHostInfoProto::errorString() const
{
    QHostInfo *item = qscriptvalue_cast<QHostInfo*>(thisObject());
    if (item)
        return item->errorString();
    return QString();
}
示例#4
0
void SlaveInterfacePrivate::slotHostInfo(const QHostInfo &info)
{
    QByteArray data;
    QDataStream stream(&data, QIODevice::WriteOnly);
    stream <<  info.hostName() << info.addresses() << info.error() << info.errorString();
    connection->send(CMD_HOST_INFO, data);
}
QList<QHostAddress> LimitedSocket::performResolve(QString host, bool bPreferIPv6)
{
	QHostInfo info = QHostInfo::fromName(host);
	QList<QHostAddress> addresses, ip4, ip6;
	
	addresses = info.addresses();
	
	if(info.error() != QHostInfo::NoError)
		throw info.errorString();
	
	foreach(QHostAddress addr, addresses)
	{
		if(addr.protocol() == QAbstractSocket::IPv6Protocol)
			ip6 << addr;
		else if(addr.protocol() == QAbstractSocket::IPv4Protocol)
			ip4 << addr;
	}
	
	addresses.clear();
	
	if(bPreferIPv6)
		addresses << ip6 << ip4;
	else
		addresses << ip4 << ip6;
	
	return addresses;
}
示例#6
0
void NetClient::connectToServer(const QString &hostName, qint16 port,
                                HostIdentifierType identType)
{
    QHostAddress address;
    if (identType == HostName)
    {
        QHostInfo host = QHostInfo::fromName(hostName);
        if (host.error() != QHostInfo::NoError)
        {
            qDebug() << host.errorString();
            return;
        }
        else
        {
            address = host.addresses().first();
        }
    }
    else
    {
        if (!address.setAddress(hostName))
        {
            qDebug() << "Setting address failed" << endl;
            return;
        }
    }

    tcpSocket->connectToHost(address, port);
}
示例#7
0
void Network::lookedUp(const QHostInfo &host)
{
    if (host.error() != QHostInfo::NoError) {
        qDebug() << "Lookup failed:" << host.errorString();
        return;
    }
    _serverAddr = host.addresses().at(0);
}
示例#8
0
void Address::onLookUpFinished(const QHostInfo &host)
{
    if (host.error() != QHostInfo::NoError) {
        emit lookedUp(false, host.errorString());
    } else {
        ipAddrList = host.addresses();
        emit lookedUp(true, QString());
    }
}
示例#9
0
void
ServerInfo::reverselookUp(const QHostInfo &host)
{
    qDebug() << __PRETTY_FUNCTION__ << " called ...";

    if (host.error() != QHostInfo::NoError) {
        qDebug() << "Lookup failed:" << host.errorString();
        return;
    }
}
示例#10
0
void In2SaiControl::lookedUp(const QHostInfo & host){
    if (host.error() != QHostInfo::NoError) {
             qDebug() << "Lookup failed:" << host.errorString();
             return;
         }

         foreach (const QHostAddress &address, host.addresses())
             qDebug() << "Found address:" << address.toString();

}
void WeatherWorker::networkLookedUp(const QHostInfo &host)
{
    if(host.error() != QHostInfo::NoError) {
        //qDebug() << "test network failed, errorCode:" << host.error();
        emit this->nofityNetworkStatus(host.errorString());
    }
    else {
        //qDebug() << "test network success, the server's ip:" << host.addresses().first().toString();
        emit this->nofityNetworkStatus("OK");
    }
}
示例#12
0
文件: NtpApp.cpp 项目: koahnig/qntp
void NtpApp::sltLookupReceived(QHostInfo host)
{
    if (host.error() != QHostInfo::NoError) {
        qDebug() << "Lookup failed:" << host.errorString();
        return;
    }

    foreach (const QHostAddress &address, host.addresses())
        qDebug() << "Found address:" << address.toString();

    HostInfo = host;
}
示例#13
0
void MainWindow::finishedLookup(QHostInfo info)
{
    if(info.error())
    {
        serverView->append(info.errorString());
    }
    else
    {
        serverView->append("Connecting...");
        sock.connectToHost(info.addresses().first(), ui->portEdit->text().toInt());
    }
}
示例#14
0
void GameSpyServer::query()
{
    QHostInfo ns = QHostInfo::fromName(m_sHost);
    if(!ns.addresses().isEmpty())
    {
        if(m_pUdpSocket->writeDatagram("\\basic\\\\info\\", 13,
            ns.addresses().first(), m_iPort) == -1)
        {
            emit errorEncountered(m_pUdpSocket->errorString());
        }
    }
    else
        emit errorEncountered(ns.errorString());
}
示例#15
0
void MainWindow::PrintConnectionInfo(const QHostInfo &hostInfo, int port)
{
    const QList<QHostAddress> &addresses = hostInfo.addresses();

    if (hostInfo.error() != QHostInfo::NoError) {
        qWarning("Lookup failed: %s", hostInfo.errorString().toAscii().constData());
        return;
    }

    if (!addresses.isEmpty())
    {
        QHostAddress address = addresses.first();
        qDebug() << "Connect: " << address.toString() << " Port: " << port << endl;
    }
}
示例#16
0
void ReverseResolution::hostResolved(const QHostInfo &host)
{
    const QString ip = m_lookups.take(host.lookupId());
    Q_ASSERT(!ip.isNull());

    if (host.error() != QHostInfo::NoError) {
        qDebug() << "DNS Reverse resolution error: " << host.errorString();
        return;
    }

    const QString hostname = host.hostName();

    qDebug() << Q_FUNC_INFO << ip << QString("->") << hostname;
    m_cache.insert(ip, new QString(hostname));
    if (isUsefulHostName(hostname, ip))
        emit ipResolved(ip, hostname);
}
示例#17
0
void HifiSockAddr::handleLookupResult(const QHostInfo& hostInfo) {
    if (hostInfo.error() != QHostInfo::NoError) {
        qCDebug(networking) << "Lookup failed for" << hostInfo.lookupId() << ":" << hostInfo.errorString();
        emit lookupFailed();
    }

    foreach(const QHostAddress& address, hostInfo.addresses()) {
        // just take the first IPv4 address
        if (address.protocol() == QAbstractSocket::IPv4Protocol) {
            _address = address;
            qCDebug(networking) << "QHostInfo lookup result for"
                << hostInfo.hostName() << "with lookup ID" << hostInfo.lookupId() << "is" << address.toString();
            emit lookupCompleted();
            break;
        }
    }
}
示例#18
0
void
ServerInfo::lookUp(const QHostInfo &host)
{
    qDebug() << __PRETTY_FUNCTION__ << " called ...";

    if (host.error() != QHostInfo::NoError) {
        qDebug() << "Lookup failed:" << host.errorString();
        return;
    }

    QString s;
    if(!host.addresses().isEmpty()) {

        s += QLatin1String("IP addresses: ");

        for(int i = 0;i < host.addresses().count();++i) {
            s += host.addresses().at(i).toString() + QLatin1String("\n");
        }

        GeoIPRecord* record = GeoIP_record_by_addr(gi,host.addresses().first().toString().toLatin1().constData());
        if(record) {

        const char* returnedCountry = record->country_name;

        s += QLatin1String("Country: ") + returnedCountry + QLatin1String("\n");
        s += QLatin1String("City: ") + QLatin1String(record->city)  + QLatin1String("\n");
        s += QLatin1String("Latitude: ") + QString::number(record->latitude)  + QLatin1String("\n");
        s += QLatin1String("Longitude: ") + QString::number(record->longitude)  + QLatin1String("\n");
        s += QLatin1String("Region: ") + QLatin1String(record->region) + QLatin1String("\n");
        s += QLatin1String("Postal code: ") + QLatin1String(record->postal_code) + QLatin1String("\n");

        }
        /* Save for later use */
        this->latitude = record->latitude;
        this->longitude = record->longitude;

        if(this->mainWindow->ui->googleMapsLookup_checkBox->isChecked()) {
            this->loadGoogleMaps();
        }

        this->ui->plainTextEdit->setPlainText(s);
    }
}
void IPNetworkClientWidget::lookupFinished(QHostInfo info)
{
    if (info.error() != QHostInfo::NoError) {
        emit log(info.errorString(), "", Pip3lineConst::LERROR);
    } else { // success populating the combobox, at this point the list shoud not be empty ...
        QList<QHostAddress> list = info.addresses();
        if (list.isEmpty()) {
            qCritical() << "[NetworkClientWidget::lookupFinished] returned adress list is empty T_T";
            return;
        }

        for (int i = 0; i < list.size(); i++) {
            ui->hostResolvComboBox->addItem(list.at(i).toString());
        }
        ui->hostResolvComboBox->setCurrentIndex(0);
        ui->hostResolvComboBox->setDisabled(false);
        listener->setHostAddress(list.at(0));
        listener->setHostname(info.hostName());
        emit newSNI(info.hostName());
    }
}
示例#20
0
QHostInfo QHostInfoAgent::fromName(const QString &hostName)
{
    QHostInfo results;

#if defined(QHOSTINFO_DEBUG)
    qDebug("QHostInfoAgent::fromName(%s) looking up...",
           hostName.toLatin1().constData());
#endif

    // Load res_init on demand.
    static volatile bool triedResolve = false;
    if (!triedResolve) {
        QMutexLocker locker(QMutexPool::globalInstanceGet(&local_res_init));
        if (!triedResolve) {
            resolveLibrary();
            triedResolve = true;
        }
    }

    // If res_init is available, poll it.
    if (local_res_init)
        local_res_init();

    QHostAddress address;
    if (address.setAddress(hostName)) {
        // Reverse lookup
// Reverse lookups using getnameinfo are broken on darwin, use gethostbyaddr instead.
#if !defined (QT_NO_GETADDRINFO) && !defined (Q_OS_DARWIN)
        sockaddr_in sa4;
#ifndef QT_NO_IPV6
        sockaddr_in6 sa6;
#endif
        sockaddr *sa = 0;
        QT_SOCKLEN_T saSize = 0;
        if (address.protocol() == QAbstractSocket::IPv4Protocol) {
            sa = (sockaddr *)&sa4;
            saSize = sizeof(sa4);
            memset(&sa4, 0, sizeof(sa4));
            sa4.sin_family = AF_INET;
            sa4.sin_addr.s_addr = htonl(address.toIPv4Address());
        }
#ifndef QT_NO_IPV6
        else {
            sa = (sockaddr *)&sa6;
            saSize = sizeof(sa6);
            memset(&sa6, 0, sizeof(sa6));
            sa6.sin6_family = AF_INET6;
            memcpy(sa6.sin6_addr.s6_addr, address.toIPv6Address().c, sizeof(sa6.sin6_addr.s6_addr));
        }
#endif

        char hbuf[NI_MAXHOST];
        if (sa && getnameinfo(sa, saSize, hbuf, sizeof(hbuf), 0, 0, 0) == 0)
            results.setHostName(QString::fromLatin1(hbuf));
#else
        in_addr_t inetaddr = qt_safe_inet_addr(hostName.toLatin1().constData());
        struct hostent *ent = gethostbyaddr((const char *)&inetaddr, sizeof(inetaddr), AF_INET);
        if (ent)
            results.setHostName(QString::fromLatin1(ent->h_name));
#endif

        if (results.hostName().isEmpty())
            results.setHostName(address.toString());
        results.setAddresses(QList<QHostAddress>() << address);
        return results;
    }

    // IDN support
    QByteArray aceHostname = QUrl::toAce(hostName);
    results.setHostName(hostName);
    if (aceHostname.isEmpty()) {
        results.setError(QHostInfo::HostNotFound);
        results.setErrorString(hostName.isEmpty() ?
                               QCoreApplication::translate("QHostInfoAgent", "No host name given") :
                               QCoreApplication::translate("QHostInfoAgent", "Invalid hostname"));
        return results;
    }

#if !defined (QT_NO_GETADDRINFO)
    // Call getaddrinfo, and place all IPv4 addresses at the start and
    // the IPv6 addresses at the end of the address list in results.
    addrinfo *res = 0;
    struct addrinfo hints;
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = PF_UNSPEC;
#ifdef Q_ADDRCONFIG
    hints.ai_flags = Q_ADDRCONFIG;
#endif

    int result = getaddrinfo(aceHostname.constData(), 0, &hints, &res);
# ifdef Q_ADDRCONFIG
    if (result == EAI_BADFLAGS) {
        // if the lookup failed with AI_ADDRCONFIG set, try again without it
        hints.ai_flags = 0;
        result = getaddrinfo(aceHostname.constData(), 0, &hints, &res);
    }
# endif

    if (result == 0) {
        addrinfo *node = res;
        QList<QHostAddress> addresses;
        while (node) {
#ifdef QHOSTINFO_DEBUG
                qDebug() << "getaddrinfo node: flags:" << node->ai_flags << "family:" << node->ai_family << "ai_socktype:" << node->ai_socktype << "ai_protocol:" << node->ai_protocol << "ai_addrlen:" << node->ai_addrlen;
#endif
            if (node->ai_family == AF_INET) {
                QHostAddress addr;
                addr.setAddress(ntohl(((sockaddr_in *) node->ai_addr)->sin_addr.s_addr));
                if (!addresses.contains(addr))
                    addresses.append(addr);
            }
#ifndef QT_NO_IPV6
            else if (node->ai_family == AF_INET6) {
                QHostAddress addr;
                sockaddr_in6 *sa6 = (sockaddr_in6 *) node->ai_addr;
                addr.setAddress(sa6->sin6_addr.s6_addr);
                if (sa6->sin6_scope_id)
                    addr.setScopeId(QString::number(sa6->sin6_scope_id));
                if (!addresses.contains(addr))
                    addresses.append(addr);
            }
#endif
            node = node->ai_next;
        }
        if (addresses.isEmpty() && node == 0) {
            // Reached the end of the list, but no addresses were found; this
            // means the list contains one or more unknown address types.
            results.setError(QHostInfo::UnknownError);
            results.setErrorString(tr("Unknown address type"));
        }

        results.setAddresses(addresses);
        freeaddrinfo(res);
    } else if (result == EAI_NONAME
               || result ==  EAI_FAIL
#ifdef EAI_NODATA
	       // EAI_NODATA is deprecated in RFC 3493
	       || result == EAI_NODATA
#endif
	       ) {
        results.setError(QHostInfo::HostNotFound);
        results.setErrorString(tr("Host not found"));
    } else {
        results.setError(QHostInfo::UnknownError);
        results.setErrorString(QString::fromLocal8Bit(gai_strerror(result)));
    }

#else
    // Fall back to gethostbyname for platforms that don't define
    // getaddrinfo. gethostbyname does not support IPv6, and it's not
    // reentrant on all platforms. For now this is okay since we only
    // use one QHostInfoAgent, but if more agents are introduced, locking
    // must be provided.
    QMutexLocker locker(::getHostByNameMutex());
    hostent *result = gethostbyname(aceHostname.constData());
    if (result) {
        if (result->h_addrtype == AF_INET) {
            QList<QHostAddress> addresses;
            for (char **p = result->h_addr_list; *p != 0; p++) {
                QHostAddress addr;
                addr.setAddress(ntohl(*((quint32 *)*p)));
                if (!addresses.contains(addr))
                    addresses.prepend(addr);
            }
            results.setAddresses(addresses);
        } else {
            results.setError(QHostInfo::UnknownError);
            results.setErrorString(tr("Unknown address type"));
        }
#if !defined(Q_OS_VXWORKS)
    } else if (h_errno == HOST_NOT_FOUND || h_errno == NO_DATA
               || h_errno == NO_ADDRESS) {
        results.setError(QHostInfo::HostNotFound);
        results.setErrorString(tr("Host not found"));
#endif
    } else {
        results.setError(QHostInfo::UnknownError);
        results.setErrorString(tr("Unknown error"));
    }
#endif //  !defined (QT_NO_GETADDRINFO)

#if defined(QHOSTINFO_DEBUG)
    if (results.error() != QHostInfo::NoError) {
        qDebug("QHostInfoAgent::fromName(): error #%d %s",
               h_errno, results.errorString().toLatin1().constData());
    } else {
        QString tmp;
        QList<QHostAddress> addresses = results.addresses();
        for (int i = 0; i < addresses.count(); ++i) {
            if (i != 0) tmp += ", ";
            tmp += addresses.at(i).toString();
        }
        qDebug("QHostInfoAgent::fromName(): found %i entries for \"%s\": {%s}",
               addresses.count(), hostName.toLatin1().constData(),
               tmp.toLatin1().constData());
    }
#endif
    return results;
}
示例#21
0
void KviDnsResolver::slotHostLookupTerminated(const QHostInfo &oHostInfo)
{
	if(oHostInfo.error() != QHostInfo::NoError)
	{
		m_pPrivateData->eState = Failure;

		switch(oHostInfo.error())
		{
			case QHostInfo::HostNotFound:
				m_pPrivateData->eError = KviError::HostNotFound;
			break;
			default:
				m_pPrivateData->eError = KviError::DNSQueryFailed;
			break;
		}

		m_pPrivateData->szError = oHostInfo.errorString();

		emit lookupDone(this);

		return;
	}

	m_pPrivateData->szHostName = oHostInfo.hostName();

	QList<QHostAddress> lAddresses = oHostInfo.addresses();

	m_pPrivateData->pAddressList->clear();

	m_pPrivateData->eError = KviError::Success;
	m_pPrivateData->szError = QString();
	m_pPrivateData->eState = Success;

	foreach(QHostAddress oAddress,lAddresses)
	{
		switch(m_pPrivateData->eQueryType)
		{
			case IPv4:
				if(oAddress.protocol() == QAbstractSocket::IPv4Protocol)
					m_pPrivateData->pAddressList->append(new QString(oAddress.toString()));
			break;
			case IPv6:
				if(oAddress.protocol() == QAbstractSocket::IPv6Protocol)
					m_pPrivateData->pAddressList->append(new QString(oAddress.toString()));
			break;
			case Any:
				m_pPrivateData->pAddressList->append(new QString(oAddress.toString()));
			break;
			default:
				KVI_ASSERT_MSG(false,"Invalid DNS query type!");
				m_pPrivateData->eState = Failure;
				m_pPrivateData->eError = KviError::InternalError;
				m_pPrivateData->szError = __tr2qs("Internal error: unhandled DNS query type");
				emit lookupDone(this);
				return;
			break;
		}
	}

	if(m_pPrivateData->pAddressList->isEmpty())
	{
		m_pPrivateData->eState = Failure;
		m_pPrivateData->eError = KviError::ValidNameButNoIpAddress;
		m_pPrivateData->szError = __tr2qs("DNS query returned no IP address results of the requested type");
	}

	emit lookupDone(this);

}
/*!

*/
MonitorClient::MonitorClient( QObject * parent,
                              DispHolder & disp_holder,
                              const char * hostname,
                              const int port,
                              const int version )

    : QObject( parent )
    , M_disp_holder( disp_holder )
    , M_server_port( static_cast< quint16 >( port ) )
    , M_socket( new QUdpSocket( this ) )
    , M_timer( new QTimer( this ) )
    , M_version( version )
    , M_waited_msec( 0 )
{
    assert( parent );

    // check protocl versin range
    if ( version < 1 )
    {
        M_version = 1;
    }

    if ( 4 < version )
    {
        M_version = 4;
    }

    QHostInfo host = QHostInfo::fromName( QString::fromAscii( hostname ) );

    if ( host.error() != QHostInfo::NoError )
    {
        qDebug() << "Error " << host.errorString();
        return;
    }

    M_server_addr = host.addresses().front();

    // INADDR_ANY, bind random created port to local
    if ( ! M_socket->bind( 0 ) )
    {
        std::cerr << "MonitorClient. failed to bind the socket."
                  << std::endl;
        return;
    }

    if ( ! isConnected() )
    {
        std::cerr << "MonitorClient. failed to initialize the socket."
                  << std::endl;
        return;
    }

    // setReadBufferSize() makes no effect for QUdpSocet...
    // M_socket->setReadBufferSize( 8192 * 256 );

    connect( M_socket, SIGNAL( readyRead() ),
             this, SLOT( handleReceive() ) );

    connect( M_timer, SIGNAL( timeout() ),
             this, SLOT( handleTimer() ) );

}
示例#23
0
QHostInfo QHostInfoAgent::fromName(const QString &hostName)
{
    QHostInfo results;
    results.setHostName(hostName);

#if defined(QHOSTINFO_DEBUG)
    qDebug("QHostInfoAgent::fromName(%s) looking up...",
           hostName.toLatin1().constData());
#endif

    QHostAddress address;
    if (address.setAddress(hostName)) {
        // Reverse lookup
// Reverse lookups using getnameinfo are broken on darwin, use gethostbyaddr instead.
#if !defined (QT_NO_GETADDRINFO) && !defined (Q_OS_DARWIN)
        sockaddr_in sa4;
        sockaddr_in6 sa6;
        sockaddr *sa;
        QT_SOCKLEN_T saSize;
        if (address.protocol() == QAbstractSocket::IPv4Protocol) {
            sa = (sockaddr *)&sa4;
            saSize = sizeof(sa4);
            memset(&sa4, 0, sizeof(sa4));
            sa4.sin_family = AF_INET;
            sa4.sin_addr.s_addr = htonl(address.toIPv4Address());
        } else {
            sa = (sockaddr *)&sa6;
            saSize = sizeof(sa6);
            memset(&sa6, 0, sizeof(sa6));
            sa6.sin6_family = AF_INET6;
            memcpy(sa6.sin6_addr.s6_addr, address.toIPv6Address().c, sizeof(sa6.sin6_addr.s6_addr));
        }

        char hbuf[NI_MAXHOST];
        if (getnameinfo(sa, saSize, hbuf, sizeof(hbuf), 0, 0, 0) != 0) {
            results.setError(QHostInfo::HostNotFound);
            results.setErrorString(tr("Host not found"));
            return results;            
        }
        results.setHostName(QString::fromLatin1(hbuf));
#else
        in_addr_t inetaddr = inet_addr(hostName.toLatin1().constData());
        struct hostent *ent = gethostbyaddr((const char *)&inetaddr, sizeof(inetaddr), AF_INET);
        if (!ent) {
            results.setError(QHostInfo::HostNotFound);
            results.setErrorString(tr("Host not found"));
            return results;            
        }
        results.setHostName(QString::fromLatin1(ent->h_name));
#endif
    }
    
#if !defined (QT_NO_GETADDRINFO)
    // Call getaddrinfo, and place all IPv4 addresses at the start and
    // the IPv6 addresses at the end of the address list in results.
    addrinfo *res = 0;
    struct addrinfo hints;
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = PF_UNSPEC;

    int result = getaddrinfo(hostName.toLatin1().constData(), 0, &hints, &res);
    if (result == 0) {
        addrinfo *node = res;
        QList<QHostAddress> addresses;
        while (node) {
            if (node->ai_family == AF_INET) {
                QHostAddress addr;
                addr.setAddress(ntohl(((sockaddr_in *) node->ai_addr)->sin_addr.s_addr));
                if (!addresses.contains(addr))
                    addresses.prepend(addr);
            } else if (node->ai_family == AF_INET6) {
                QHostAddress addr;
                addr.setAddress(((sockaddr_in6 *) node->ai_addr)->sin6_addr.s6_addr);
                if (!addresses.contains(addr))
                    addresses.append(addr);
            } else {
                results.setError(QHostInfo::UnknownError);
                results.setErrorString(tr("Unknown address type"));
                break;
            }
            node = node->ai_next;
        }
        results.setAddresses(addresses);
        freeaddrinfo(res);
    } else if (result == EAI_NONAME 
               || result ==  EAI_FAIL
               || result ==  EAI_FAIL
#ifdef EAI_NODATA
	       // EAI_NODATA is deprecated in RFC 3493
	       || result == EAI_NODATA
#endif
	       ) {
        results.setError(QHostInfo::HostNotFound);
        results.setErrorString(tr("Host not found"));
    } else {
        results.setError(QHostInfo::UnknownError);
        results.setErrorString(QString::fromLocal8Bit(gai_strerror(result)));
    }

#else
    // Fall back to gethostbyname for platforms that don't define
    // getaddrinfo. gethostbyname does not support IPv6, and it's not
    // reentrant on all platforms. For now this is okay since we only
    // use one QHostInfoAgent, but if more agents are introduced, locking
    // must be provided.
    QMutexLocker locker(::getHostByNameMutex());
    hostent *result = gethostbyname(hostName.toLatin1().constData());
    if (result) {
        if (result->h_addrtype == AF_INET) {
            QList<QHostAddress> addresses;
            for (char **p = result->h_addr_list; *p != 0; p++) {
                QHostAddress addr;
                addr.setAddress(ntohl(*((quint32 *)*p)));
                if (!addresses.contains(addr))
                    addresses.prepend(addr);
            }
            results.setAddresses(addresses);
        } else {
            results.setError(QHostInfo::UnknownError);
            results.setErrorString(tr("Unknown address type"));
        }
    } else if (h_errno == HOST_NOT_FOUND || h_errno == NO_DATA
               || h_errno == NO_ADDRESS) {
        results.setError(QHostInfo::HostNotFound);
        results.setErrorString(tr("Host not found"));
    } else {
        results.setError(QHostInfo::UnknownError);
        results.setErrorString(tr("Unknown error"));
    }
#endif //  !defined (QT_NO_GETADDRINFO)

#if defined(QHOSTINFO_DEBUG)
    if (results.error() != QHostInfo::NoError) {
        qDebug("QHostInfoAgent::fromName(): error #%d %s",
               h_errno, results.errorString().toLatin1().constData());
    } else {
        QString tmp;
        QList<QHostAddress> addresses = results.addresses();
        for (int i = 0; i < addresses.count(); ++i) {
            if (i != 0) tmp += ", ";
            tmp += addresses.at(i).toString();
        }
        qDebug("QHostInfoAgent::fromName(): found %i entries for \"%s\": {%s}",
               addresses.count(), hostName.toLatin1().constData(),
               tmp.toLatin1().constData());
    }
#endif
    return results;
}
示例#24
0
TelescopeTCP::TelescopeTCP(const QString &name, const QString &params, Equinox eq)
	: TelescopeClient(name)
	, port(0)
	, tcpSocket(new QTcpSocket())
	, end_of_timeout(0)
	, time_delay(0)
	, equinox(eq)
{
	hangup();
	
	// Example params:
	// localhost:10000:500000
	// split into:
	// host       = localhost
	// port       = 10000 (int)
	// time_delay = 500000 (int)

	QRegExp paramRx("^([^:]*):(\\d+):(\\d+)$");
	QString host;

	if (paramRx.exactMatch(params))
	{
		// I will not use the ok param to toInt as the
		// QRegExp only matches valid integers.
		host		= paramRx.capturedTexts().at(1).trimmed();
		port		= paramRx.capturedTexts().at(2).toInt();
		time_delay	= paramRx.capturedTexts().at(3).toInt();
	}
	else
	{
		qWarning() << "WARNING - incorrect TelescopeTCP parameters";
		return;
	}

	qDebug() << "TelescopeTCP paramaters host, port, time_delay:" << host << port << time_delay;

	if (port <= 0 || port > 0xFFFF)
	{
		qWarning() << "ERROR creating TelescopeTCP - port not valid (should be less than 32767)";
		return;
	}
	
	if (time_delay <= 0 || time_delay > 10000000)
	{
		qWarning() << "ERROR creating TelescopeTCP - time_delay not valid (should be less than 10000000)";
		return;
	}
	
	//BM: TODO: This may cause some delay when there are more telescopes
	QHostInfo info = QHostInfo::fromName(host);
	if (info.error())
	{
		qWarning() << "ERROR creating TelescopeTCP: error looking up host " << host << ":" << info.errorString();
		return;
	}
	//BM: is info.addresses().isEmpty() if there's no error?
	//qDebug() << "TelescopeClient::create(): Host addresses:" << info.addresses();
	foreach(const QHostAddress& resolvedAddress, info.addresses())
	{
		//For now, Stellarium's telescope servers support only IPv4
		if(resolvedAddress.protocol() == QTcpSocket::IPv4Protocol)
		{
			address = resolvedAddress;
			break;
		}
	}
	if(address.isNull())
	{
		qWarning() << "ERROR creating TelescopeTCP: cannot find IPv4 address. Addresses found at " << host << ":" << info.addresses();
		return;
	}
	
	end_of_timeout = -0x8000000000000000LL;
	
	interpolatedPosition.reset();
	
	connect(tcpSocket, SIGNAL(connected()), this, SLOT(socketConnected()));
	connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketFailed(QAbstractSocket::SocketError)));
}
示例#25
0
QHostInfo QHostInfoAgent::fromName(const QString &hostName)
{
    QHostInfo results;

#if defined(QHOSTINFO_DEBUG)
    qDebug("QHostInfoAgent::fromName(%s) looking up...",
           hostName.toLatin1().constData());
#endif

    // Load res_init on demand.
    resolveLibrary();

    // If res_init is available, poll it.
    if (local_res_init)
        local_res_init();

    QHostAddress address;
    if (address.setAddress(hostName)) {
        // Reverse lookup
        sockaddr_in sa4;
        sockaddr_in6 sa6;
        sockaddr *sa = 0;
        QT_SOCKLEN_T saSize = 0;
        if (address.protocol() == QAbstractSocket::IPv4Protocol) {
            sa = (sockaddr *)&sa4;
            saSize = sizeof(sa4);
            memset(&sa4, 0, sizeof(sa4));
            sa4.sin_family = AF_INET;
            sa4.sin_addr.s_addr = htonl(address.toIPv4Address());
        }
        else {
            sa = (sockaddr *)&sa6;
            saSize = sizeof(sa6);
            memset(&sa6, 0, sizeof(sa6));
            sa6.sin6_family = AF_INET6;
            memcpy(sa6.sin6_addr.s6_addr, address.toIPv6Address().c, sizeof(sa6.sin6_addr.s6_addr));
        }

        char hbuf[NI_MAXHOST];
        if (sa && getnameinfo(sa, saSize, hbuf, sizeof(hbuf), 0, 0, 0) == 0)
            results.setHostName(QString::fromLatin1(hbuf));

        if (results.hostName().isEmpty())
            results.setHostName(address.toString());
        results.setAddresses(QList<QHostAddress>() << address);
        return results;
    }

    // IDN support
    QByteArray aceHostname = QUrl::toAce(hostName);
    results.setHostName(hostName);
    if (aceHostname.isEmpty()) {
        results.setError(QHostInfo::HostNotFound);
        results.setErrorString(hostName.isEmpty() ?
                               QCoreApplication::translate("QHostInfoAgent", "No host name given") :
                               QCoreApplication::translate("QHostInfoAgent", "Invalid hostname"));
        return results;
    }

    // Call getaddrinfo, and place all IPv4 addresses at the start and
    // the IPv6 addresses at the end of the address list in results.
    addrinfo *res = 0;
    struct addrinfo hints;
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = PF_UNSPEC;
#ifdef Q_ADDRCONFIG
    hints.ai_flags = Q_ADDRCONFIG;
#endif

    int result = getaddrinfo(aceHostname.constData(), 0, &hints, &res);
# ifdef Q_ADDRCONFIG
    if (result == EAI_BADFLAGS) {
        // if the lookup failed with AI_ADDRCONFIG set, try again without it
        hints.ai_flags = 0;
        result = getaddrinfo(aceHostname.constData(), 0, &hints, &res);
    }
# endif

    if (result == 0) {
        addrinfo *node = res;
        QList<QHostAddress> addresses;
        while (node) {
#ifdef QHOSTINFO_DEBUG
                qDebug() << "getaddrinfo node: flags:" << node->ai_flags << "family:" << node->ai_family << "ai_socktype:" << node->ai_socktype << "ai_protocol:" << node->ai_protocol << "ai_addrlen:" << node->ai_addrlen;
#endif
            if (node->ai_family == AF_INET) {
                QHostAddress addr;
                addr.setAddress(ntohl(((sockaddr_in *) node->ai_addr)->sin_addr.s_addr));
                if (!addresses.contains(addr))
                    addresses.append(addr);
            }
            else if (node->ai_family == AF_INET6) {
                QHostAddress addr;
                sockaddr_in6 *sa6 = (sockaddr_in6 *) node->ai_addr;
                addr.setAddress(sa6->sin6_addr.s6_addr);
                if (sa6->sin6_scope_id)
                    addr.setScopeId(QString::number(sa6->sin6_scope_id));
                if (!addresses.contains(addr))
                    addresses.append(addr);
            }
            node = node->ai_next;
        }
        if (addresses.isEmpty() && node == 0) {
            // Reached the end of the list, but no addresses were found; this
            // means the list contains one or more unknown address types.
            results.setError(QHostInfo::UnknownError);
            results.setErrorString(tr("Unknown address type"));
        }

        results.setAddresses(addresses);
        freeaddrinfo(res);
    } else if (result == EAI_NONAME
               || result ==  EAI_FAIL
#ifdef EAI_NODATA
               // EAI_NODATA is deprecated in RFC 3493
               || result == EAI_NODATA
#endif
               ) {
        results.setError(QHostInfo::HostNotFound);
        results.setErrorString(tr("Host not found"));
    } else {
        results.setError(QHostInfo::UnknownError);
        results.setErrorString(QString::fromLocal8Bit(gai_strerror(result)));
    }


#if defined(QHOSTINFO_DEBUG)
    if (results.error() != QHostInfo::NoError) {
        qDebug("QHostInfoAgent::fromName(): error #%d %s",
               h_errno, results.errorString().toLatin1().constData());
    } else {
        QString tmp;
        QList<QHostAddress> addresses = results.addresses();
        for (int i = 0; i < addresses.count(); ++i) {
            if (i != 0) tmp += ", ";
            tmp += addresses.at(i).toString();
        }
        qDebug("QHostInfoAgent::fromName(): found %i entries for \"%s\": {%s}",
               addresses.count(), hostName.toLatin1().constData(),
               tmp.toLatin1().constData());
    }
#endif
    return results;
}
示例#26
0
void ConnectThread::run()
{
	QHostInfo addr = QHostInfo::fromName(mAddress);
	if (addr.error() != QHostInfo::NoError) {
		Q_EMIT error(addr.errorString());
		return;
	}

	QHostAddress actualAddr;
	QList<QHostAddress> addresses = addr.addresses();
	for (QList<QHostAddress>::const_iterator iter = addresses.begin();
			iter != addresses.end(); ++ iter) {
		if (iter->protocol() == QAbstractSocket::IPv4Protocol) {
			actualAddr = *iter;
			break;
		}
	}

	if (actualAddr.isNull()) {
		Q_EMIT error(tr("无法解析域名: 找不到'%1'的IPv4地址").arg(mAddress));
		return;
	}

	// Begin connection
	{
		std::string addr = actualAddr.toString().toStdString();
		TCPSocketAddress remote (addr,mPort);
		IOVideoSource *src = 0;

		Error rc;
		TCPSocket *ctrl = new TCPSocket (::socket(AF_INET, SOCK_STREAM, 0));
		TCPSocket *data = new TCPSocket (::socket(AF_INET, SOCK_STREAM, 0));

		ctrl->setBlockingMode(false);
		data->setBlockingMode(false);

		ctrl->connect(&remote);
		do {
			rc = ctrl->poll(IODevice::POLL_WRITE,200);
			if (rc.isSuccess()) break;
			else if (rc.getErrorType() == Error::ERR_TIMEOUT) continue;
			else {
				rc.setErrorString("无法连接到远端服务器");
				goto connect_ctrl_failed;
			}
		}while(!mShouldStop);

		data->connect(&remote);
		do {
			rc = data->poll(IODevice::POLL_WRITE,200);
			if (rc.isSuccess()) break;
			else if (rc.getErrorType() == Error::ERR_TIMEOUT) continue;
			else {
				rc.setErrorString("无法连接到远端服务器");
				goto connect_data_failed;
			}
		}while(!mShouldStop);

		ctrl->setBlockingMode(true);
		data->setBlockingMode(true);


		src = new IOVideoSource(ctrl,data);
		rc = src->init();
		if (rc.isError()) {
			rc.setErrorString("初始化视频源失败,原因为:" + rc.getErrorString());
			goto init_video_source_failed;
		}


		mVideoSource = src;
		Q_EMIT success();
		return;

		init_video_source_failed:
		delete src;
		connect_data_failed:
		connect_ctrl_failed:
		ctrl->close();
		data->close();
		delete ctrl;
		delete data;

		Q_EMIT error(QString::fromStdString(rc.getErrorString()));

	}
}