本文整理汇总了C++中QHostAddress::toString方法的典型用法代码示例。如果您正苦于以下问题:C++ QHostAddress::toString方法的具体用法?C++ QHostAddress::toString怎么用?C++ QHostAddress::toString使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类QHostAddress
的用法示例。
在下文中一共展示了QHostAddress::toString方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: readMessagefromBuddy
void slm_client::readMessagefromBuddy(QString incomingMessage, QHostAddress peerAddress)
{
QDateTime currentTime;
QString shownMessage;
//decrypt the message
incomingMessage = encryptionObject.dencrypt(incomingMessage, "qweertesdjhfgjhsdfsmg2008xbnxcvbnxvashgdahgdhafdajhfdvsbdcvgsdvf");
qDebug() << "Decrypted Text :: " << incomingMessage;
// check if the message gui is open or not and open if it is not.
if(this->getGuiKey() == 0)
{
this->show();
this->setGuiKey(1);// set the gui key to one to indicate it is opened
}
else
{
this->activateWindow();// if it is already opened, activate it before writing the message
}
//show the message to the user by adding current data and time
shownMessage = currentTime.currentDateTime().toString() + " From " + peerAddress.toString() + ": " + "\n" + "\n" + incomingMessage + "\n";
m_ui->slm_clientIncomingTextArea->append(shownMessage);
}
示例2: updateInterfaceAddressCombo
void AdvancedSettings::updateInterfaceAddressCombo()
{
// Try to get the currently selected interface name
const QString ifaceName = comboBoxInterface.itemData(comboBoxInterface.currentIndex()).toString(); // Empty string for the first element
const QString currentAddress = BitTorrent::Session::instance()->networkInterfaceAddress();
// Clear all items and reinsert them, default to all
comboBoxInterfaceAddress.clear();
comboBoxInterfaceAddress.addItem(tr("All addresses"));
comboBoxInterfaceAddress.setCurrentIndex(0);
auto populateCombo = [this, ¤tAddress](const QString &ip, const QAbstractSocket::NetworkLayerProtocol &protocol)
{
Q_ASSERT((protocol == QAbstractSocket::IPv4Protocol) || (protocol == QAbstractSocket::IPv6Protocol));
// Only take ipv4 for now?
if ((protocol != QAbstractSocket::IPv4Protocol) && (protocol != QAbstractSocket::IPv6Protocol))
return;
comboBoxInterfaceAddress.addItem(ip);
//Try to select the last added one
if (ip == currentAddress)
comboBoxInterfaceAddress.setCurrentIndex(comboBoxInterfaceAddress.count() - 1);
};
if (ifaceName.isEmpty()) {
for (const QHostAddress &ip : asConst(QNetworkInterface::allAddresses()))
populateCombo(ip.toString(), ip.protocol());
}
else {
const QNetworkInterface iface = QNetworkInterface::interfaceFromName(ifaceName);
const QList<QNetworkAddressEntry> addresses = iface.addressEntries();
for (const QNetworkAddressEntry &entry : addresses) {
const QHostAddress ip = entry.ip();
populateCombo(ip.toString(), ip.protocol());
}
}
}
示例3: addService
void ServerDiscoveryModel::addService(KDNSSD::RemoteService::Ptr service)
{
QUrl url;
url.setScheme("drawpile");
QHostAddress hostname = KDNSSD::ServiceBrowser::resolveHostName(service->hostName());
url.setHost(hostname.isNull() ? service->hostName() : hostname.toString());
if(service->port() != DRAWPILE_PROTO_DEFAULT_PORT)
url.setPort(service->port());
QDateTime started = QDateTime::fromString(service->textData()["started"], Qt::ISODate);
started.setTimeSpec(Qt::UTC);
DiscoveredServer s {
url,
service->serviceName(),
service->textData()["title"],
service->textData()["protocol"],
started
};
beginInsertRows(QModelIndex(), _servers.size(), _servers.size());
_servers.append(s);
endInsertRows();
}
示例4: processPendingDatagrams
void NetworkMonitor::processPendingDatagrams()
{
while( socket.hasPendingDatagrams() )
{
QByteArray datagram;
QHostAddress sender;
datagram.resize( socket.pendingDatagramSize() );
socket.readDatagram( datagram.data(), datagram.size(), &sender );
if( QString( datagram.data() ) == QString( broadcastPing.data() ) && datagram.size() == broadcastPing.size() )
break;
QString socketKey = sender.toString( );
if( !connectedDevices.contains( socketKey ) )
{
PacketUdp* device = new PacketUdp( );
connectedDevices.insert( socketKey, device ); // stick it in our own list of boards we know about
device->setRemoteHostInfo( &sender, listenPort );
device->setKey( socketKey );
device->setInterfaces( messageInterface, this );
device->open( );
// post it to the UI
BoardArrivalEvent* event = new BoardArrivalEvent( Board::Udp );
event->pUdp.append( device );
application->postEvent( mainWindow, event );
}
if( connectedDevices.contains( socketKey ) ) // pass the packet through to the packet interface
{
connectedDevices.value( socketKey )->incomingMessage( datagram );
connectedDevices.value( socketKey )->processPacket( );
connectedDevices.value( socketKey )->resetTimer( );
}
}
}
示例5: nativeConnect
bool QNativeSocketEnginePrivate::nativeConnect(const QHostAddress &address, quint16 port)
{
#if defined (QNATIVESOCKETENGINE_DEBUG)
qDebug("QNativeSocketEnginePrivate::nativeConnect() to %s :: %i", address.toString().toLatin1().constData(), port);
#endif
struct sockaddr_in sockAddrIPv4;
qt_sockaddr_in6 sockAddrIPv6;
struct sockaddr *sockAddrPtr = 0;
QT_SOCKLEN_T sockAddrSize = 0;
qt_socket_setPortAndAddress(socketDescriptor, &sockAddrIPv4, &sockAddrIPv6, port, address, &sockAddrPtr, &sockAddrSize);
forever {
int connectResult = ::WSAConnect(socketDescriptor, sockAddrPtr, sockAddrSize, 0,0,0,0);
if (connectResult == SOCKET_ERROR) {
int err = WSAGetLastError();
WS_ERROR_DEBUG(err);
switch (err) {
case WSANOTINITIALISED:
//###
break;
case WSAEISCONN:
socketState = QAbstractSocket::ConnectedState;
break;
case WSAEWOULDBLOCK: {
// If WSAConnect returns WSAEWOULDBLOCK on the second
// connection attempt, we have to check SO_ERROR's
// value to detect ECONNREFUSED. If we don't get
// ECONNREFUSED, we'll have to treat it as an
// unfinished operation.
int value = 0;
QT_SOCKLEN_T valueSize = sizeof(value);
if (::getsockopt(socketDescriptor, SOL_SOCKET, SO_ERROR, (char *) &value, &valueSize) == 0) {
if (value == WSAECONNREFUSED) {
setError(QAbstractSocket::ConnectionRefusedError, ConnectionRefusedErrorString);
socketState = QAbstractSocket::UnconnectedState;
break;
}
if (value == WSAETIMEDOUT) {
setError(QAbstractSocket::NetworkError, ConnectionTimeOutErrorString);
socketState = QAbstractSocket::UnconnectedState;
break;
}
if (value == WSAEHOSTUNREACH) {
setError(QAbstractSocket::NetworkError, HostUnreachableErrorString);
socketState = QAbstractSocket::UnconnectedState;
break;
}
if (value == WSAEADDRNOTAVAIL) {
setError(QAbstractSocket::NetworkError, AddressNotAvailableErrorString);
socketState = QAbstractSocket::UnconnectedState;
break;
}
}
// fall through
}
case WSAEINPROGRESS:
setError(QAbstractSocket::UnfinishedSocketOperationError, InvalidSocketErrorString);
socketState = QAbstractSocket::ConnectingState;
break;
case WSAEADDRINUSE:
setError(QAbstractSocket::NetworkError, AddressInuseErrorString);
break;
case WSAECONNREFUSED:
setError(QAbstractSocket::ConnectionRefusedError, ConnectionRefusedErrorString);
socketState = QAbstractSocket::UnconnectedState;
break;
case WSAETIMEDOUT:
setError(QAbstractSocket::NetworkError, ConnectionTimeOutErrorString);
break;
case WSAEACCES:
setError(QAbstractSocket::SocketAccessError, AccessErrorString);
socketState = QAbstractSocket::UnconnectedState;
break;
case WSAEHOSTUNREACH:
setError(QAbstractSocket::NetworkError, HostUnreachableErrorString);
socketState = QAbstractSocket::UnconnectedState;
break;
case WSAENETUNREACH:
setError(QAbstractSocket::NetworkError, NetworkUnreachableErrorString);
socketState = QAbstractSocket::UnconnectedState;
break;
case WSAEINVAL:
case WSAEALREADY:
setError(QAbstractSocket::UnfinishedSocketOperationError, InvalidSocketErrorString);
break;
default:
break;
}
if (socketState != QAbstractSocket::ConnectedState) {
#if defined (QNATIVESOCKETENGINE_DEBUG)
qDebug("QNativeSocketEnginePrivate::nativeConnect(%s, %i) == false (%s)",
address.toString().toLatin1().constData(), port,
socketState == QAbstractSocket::ConnectingState
? "Connection in progress" : socketErrorString.toLatin1().constData());
#endif
return false;
//.........这里部分代码省略.........
示例6: setAddress
void RDStation::setAddress(QHostAddress addr) const
{
SetRow("IPV4_ADDRESS",addr.toString());
}
示例7: setIp
void RaspberryPiDebugWidget::setIp(QHostAddress ip)
{
ui->labIp->setText(ip.toString());
}
示例8: fromName
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;
//.........这里部分代码省略.........
示例9: SelectDefaultListen
//.........这里部分代码省略.........
else
LOG(VB_GENERAL, LOG_DEBUG, QString("Skipping "
"non-private address during IPv4 autoselection: %1")
.arg(PRETTYIP_(ip)));
}
else
LOG(VB_GENERAL, LOG_DEBUG, QString("Skipping address: %1")
.arg(PRETTYIP_(ip)));
#if !defined(QT_NO_IPV6)
}
else
{
if (ip.isInSubnet(kLinkLocal6))
{
// set scope id for link local address
ip.setScopeId(qni->name());
qnai->setIp(ip);
}
if (naList_6.contains(*qnai))
// already defined, skip
continue;
else if ((!config_v6.isNull()) && (ip == config_v6))
{
// IPv6 address is defined, add it
LOG(VB_GENERAL, LOG_DEBUG,
QString("Adding BackendServerIP6 to address list."));
naList_6.append(*qnai);
v6IsSet = true;
}
else if (ip == QHostAddress::LocalHostIPv6)
{
// always listen on LocalHost
LOG(VB_GENERAL, LOG_DEBUG,
QString("Adding IPv6 loopback to address list."));
naList_6.append(*qnai);
if (!v6IsSet && (config_v6 == ip))
v6IsSet = true;
}
else if (ip.isInSubnet(kLinkLocal6) && allowLinkLocal)
{
// optionally listen on linklocal
// the next clause will enable it anyway if no IP address
// has been set
LOG(VB_GENERAL, LOG_DEBUG,
QString("Adding link-local '%1' to address list.")
.arg(ip.toString()));
naList_6.append(*qnai);
}
else if (config_v6.isNull())
{
if (ip.isInSubnet(kLinkLocal6))
LOG(VB_GENERAL, LOG_DEBUG,
QString("Adding link-local '%1' to address list.")
.arg(PRETTYIP_(ip)));
else
LOG(VB_GENERAL, LOG_DEBUG,
QString("Adding '%1' to address list.")
.arg(PRETTYIP_(ip)));
naList_6.append(*qnai);
}
else
LOG(VB_GENERAL, LOG_DEBUG, QString("Skipping address: %1")
.arg(PRETTYIP_(ip)));
}
#endif
}
}
if (!v4IsSet && (config_v4 != QHostAddress::LocalHost)
&& !naList_4.isEmpty())
{
LOG(VB_GENERAL, LOG_CRIT, LOC + QString("Host is configured to listen "
"on %1, but address is not used on any local network "
"interfaces.").arg(config_v4.toString()));
}
#if !defined(QT_NO_IPV6)
if (!v6IsSet && (config_v6 != QHostAddress::LocalHostIPv6)
&& !naList_6.isEmpty())
{
LOG(VB_GENERAL, LOG_CRIT, LOC + QString("Host is configured to listen "
"on %1, but address is not used on any local network "
"interfaces.").arg(PRETTYIP_(config_v6)));
}
#endif
// NOTE: there is no warning for the case where both defined addresses
// are localhost, and neither are found. however this would also
// mean there is no configured network at all, and should be
// sufficiently rare a case as to not worry about it.
}
示例10: run
void VisionReceiver::run() {
QUdpSocket socket;
// Create vision socket
if (simulation) {
// The simulator doesn't multicast its vision. Instead, it sends to two
// different ports.
// Try to bind to the first one and, if that fails, use the second one.
if (!socket.bind(SimVisionPort)) {
if (!socket.bind(SimVisionPort + 1)) {
throw runtime_error(
"Can't bind to either simulated vision port");
}
}
} else {
// Receive multicast packets from shared vision.
if (!socket.bind(port, QUdpSocket::ShareAddress)) {
throw runtime_error("Can't bind to shared vision port");
}
multicast_add(&socket, SharedVisionAddress);
}
// There should be at most four packets: one for each camera on each of two
// frames, assuming some clock skew between this
// computer and the vision computer.
_packets.reserve(4);
_running = true;
while (_running) {
char buf[65536];
// Wait for a UDP packet
if (!socket.waitForReadyRead(500)) {
// Time out once in a while so the thread has a chance to exit
continue;
}
QHostAddress host;
quint16 portNumber = 0;
qint64 size = socket.readDatagram(buf, sizeof(buf), &host, &portNumber);
if (size < 1) {
fprintf(stderr, "VisionReceiver: %s\n",
(const char*)socket.errorString().toLatin1());
// See Processor for why we can't use QThread::msleep()
::usleep(100 * 1000);
continue;
}
// FIXME - Verify that it is from the right host, in case there are
// multiple visions on the network
// Parse the protobuf message
VisionPacket* packet = new VisionPacket;
packet->receivedTime = timestamp();
if (!packet->wrapper.ParseFromArray(buf, size)) {
fprintf(stderr,
"VisionReceiver: got bad packet of %d bytes from %s:%d\n",
(int)size, (const char*)host.toString().toLatin1(),
portNumber);
continue;
}
// Add to the vector of packets
_mutex.lock();
_packets.push_back(packet);
_mutex.unlock();
}
}
示例11: addInterface
bool JDnsShared::addInterface(const QHostAddress &addr)
{
if(shutting_down)
return false;
QString str;
int index = instances.count();
str = QString("attempting to use interface %1").arg(addr.toString());
if(db)
db->addDebug(dbname + QString::number(index), QStringList() << str);
QJDns *jdns;
if(mode == UnicastInternet || mode == UnicastLocal)
{
jdns = new QJDns(this);
jdns_link(jdns);
if(!jdns->init(QJDns::Unicast, addr))
{
doDebug(jdns, index);
delete jdns;
return false;
}
if(mode == UnicastLocal)
{
QJDns::NameServer host;
host.address = QHostAddress("224.0.0.251");
host.port = 5353;
jdns->setNameServers(QList<QJDns::NameServer>() << host);
}
}
else
{
// only one instance supported for now (see more in the
// comment below)
if(!instances.isEmpty())
return false;
jdns = new QJDns(this);
jdns_link(jdns);
// instead of binding to the requested address, we'll bind
// to "Any". this is because QJDns doesn't support
// multiple interfaces. however, if that ever changes,
// we can update the code here and things should be mostly
// transparent to the user of JDnsShared.
//if(!jdns->init(QJDns::Multicast, addr))
if(!jdns->init(QJDns::Multicast, QHostAddress::Any))
{
doDebug(jdns, index);
delete jdns;
return false;
}
}
Instance *i = new Instance;
i->jdns = jdns;
i->addr = addr;
instances += i;
if(mode == UnicastInternet)
applyNameServers(i);
str = QString("interface ready");
if(db)
db->addDebug(dbname + QString::number(index), QStringList() << str);
return true;
}
示例12: udpProcessPendingDatagrams
void Widget::udpProcessPendingDatagrams()
{
while (udpSocket->hasPendingDatagrams())
{
QHostAddress rAddr;
quint16 rPort;
QByteArray datagram;
qint64 dataRead = 0;
int datagramSize = udpSocket->pendingDatagramSize();
datagram.resize(datagramSize);
while(dataRead < datagram.size())
{
qint64 readNow = udpSocket->readDatagram(datagram.data()+dataRead, datagramSize, &rAddr, &rPort); // le +dataRead sur un tableau, ça décale le pointeur d'un offset de taille dataRead !
if(readNow != -1)
{
dataRead += readNow; // Remember the total number of bytes read, so we know when to stop
if (datagramSize > (datagram.size() - dataRead)) // Make sure we don't overflow
datagramSize = (datagram.size() - dataRead);
}
else
{
logStatusMessage(QString("Socket error : ").arg(udpSocket->errorString()));
return;
}
}
// Add player on connection
if ((unsigned char)datagram[0]==MsgConnect && (unsigned char)datagram[1]==0
&& (unsigned char)datagram[2]==0 && datagram.size()>=22)
{
QString name = dataToString(datagram.right(datagram.size()-22));
int nameFullSize = getVUint32Size(datagram.right(datagram.size()-22))+name.size();
QString sesskey = dataToString(datagram.right(datagram.size()-22-nameFullSize));
//logMessage(QString("UDP: Connect detected with name : ")+name);
//logMessage(QString("UDP: Connect detected with sesskey : ")+sesskey);
//logMessage(QString("UDP: Datagram was : ")+datagram.toHex());
bool is_sesskey_valid = true;
if (enableSessKeyValidation) {
is_sesskey_valid = QCryptographicHash::hash(QString(sesskey.right(40) + saltPassword).toLatin1(),
QCryptographicHash::Md5).toHex() == sesskey.left(32);
}
if (is_sesskey_valid)
{
//logMessage("Sesskey token accepted");
// Create new player if needed, else just update player
Player* newPlayer = Player::findPlayer(udpPlayers, rAddr.toString(),rPort);
if (newPlayer->IP != rAddr.toString()) // IP:Port not found in player list
{
newPlayer->resetNetwork();
//newPlayer->connected = true; // Not really connected until we finish the handshake
newPlayer->name = name;
newPlayer->IP = rAddr.toString();
newPlayer->port = rPort;
// Check if we have too many players connected
int n=0;
for (int i=0;i<udpPlayers.size();i++)
if (udpPlayers[i]->connected)
n++;
if (n>=maxConnected)
{
sendMessage(newPlayer, MsgDisconnect, "Error : Too many players connected. Try again later.");
}
else
// If not add the player
udpPlayers << newPlayer;
}
else // IP:Port found in player list
{
if (newPlayer->connected) // TODO: Error, player already connected
{
sendMessage(newPlayer, MsgDisconnect, "Error : Player already connected.");
return;
}
// Check if we have too many players connected
int n=0;
for (int i=0;i<udpPlayers.size();i++)
if (udpPlayers[i]->connected)
n++;
if (n>=maxConnected)
{
sendMessage(newPlayer, MsgDisconnect, "Error : Too many players connected. Try again later.");
}
newPlayer->resetNetwork();
newPlayer->name = name;
newPlayer->IP = rAddr.toString();
newPlayer->port = rPort;
//newPlayer->connected = true; // We're not really connected until we finish the handshake
}
}
else
{
QString badHash = QCryptographicHash::hash((QString(sesskey.right(40))
//.........这里部分代码省略.........
示例13: defined
#include "DdeFaceTracker.h"
#include "FaceshiftConstants.h"
#include "InterfaceLogging.h"
#include "Menu.h"
static const QHostAddress DDE_SERVER_ADDR("127.0.0.1");
static const quint16 DDE_SERVER_PORT = 64204;
static const quint16 DDE_CONTROL_PORT = 64205;
#if defined(Q_OS_WIN)
static const QString DDE_PROGRAM_PATH = "/dde/dde.exe";
#elif defined(Q_OS_MAC)
static const QString DDE_PROGRAM_PATH = "/dde.app/Contents/MacOS/dde";
#endif
static const QStringList DDE_ARGUMENTS = QStringList()
<< "--udp=" + DDE_SERVER_ADDR.toString() + ":" + QString::number(DDE_SERVER_PORT)
<< "--receiver=" + QString::number(DDE_CONTROL_PORT)
<< "--headless";
static const int NUM_EXPRESSIONS = 46;
static const int MIN_PACKET_SIZE = (8 + NUM_EXPRESSIONS) * sizeof(float) + sizeof(int);
static const int MAX_NAME_SIZE = 31;
// There's almost but not quite a 1-1 correspondence between DDE's 46 and Faceshift 1.3's 48 packets.
// The best guess at mapping is to:
// - Swap L and R values
// - Skip two Faceshift values: JawChew (22) and LipsLowerDown (37)
static const int DDE_TO_FACESHIFT_MAPPING[] = {
1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14,
16,
18, 17,
示例14: main
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QHostAddress address = QHostAddress::Broadcast;
unsigned short port = 6948;
QString message = kMessage;
bool verbose = false;
if (a.argc() == 0)
{
printHelp();
return GENERIC_EXIT_OK;
}
for (int argpos = 1; argpos < a.argc(); ++argpos)
{
QString arg = a.argv()[argpos];
if (arg.startsWith("-h") || arg.startsWith("--help"))
{
printHelp();
return GENERIC_EXIT_OK;
}
}
for (int argpos = 1; argpos < a.argc(); ++argpos)
{
QString arg = a.argv()[argpos];
if (arg.startsWith("--help") || arg.startsWith("--template"))
continue;
if (arg.startsWith("--verbose"))
{
verbose = true;
continue;
}
if (arg.startsWith("--udpport"))
{
port = arg.section("=", 1).toUShort();
if (port == 0)
port = 6948;
continue;
}
if (arg.startsWith("--bcastaddr"))
{
QString newaddr = arg.section("=", 1);
if (!newaddr.isEmpty())
address.setAddress(newaddr);
continue;
}
QString name = arg.section("=", 0, 0);
name.replace("--", "");
QString value = QString::fromLocal8Bit(
arg.section("=", 1).toLocal8Bit());
if (verbose)
{
QByteArray tmp_name = name.toLocal8Bit();
QByteArray tmp_value = value.toLocal8Bit();
cerr << "name: " << tmp_name.constData()
<< " -- value: " << tmp_value.constData() << endl;
}
name.append("%");
name.prepend("%");
message.replace(name, value);
}
if (verbose)
{
QByteArray tmp_message = message.toLocal8Bit();
cout << "output:\n" << tmp_message.constData() << endl;
}
QUdpSocket *sock = new QUdpSocket();
QByteArray utf8 = message.toUtf8();
int size = utf8.length();
if (sock->writeDatagram(utf8.constData(), size, address, port) < 0)
{
VERBOSE(VB_IMPORTANT, "Failed to send UDP/XML packet");
}
else
{
cout << "Sent UDP/XML packet to IP "
<< address.toString().toLocal8Bit().constData()
<< " and port: " << port << endl;
}
sock->deleteLater();
return GENERIC_EXIT_OK;
//.........这里部分代码省略.........
示例15: calculateAuthKey
const QByteArray Auth::calculateAuthKey()
{
QSqlDatabase db = QSqlDatabase::database ( m_db );
bool ok = false;
QSqlQuery query(db);
ok = query.exec( QString("SELECT Value from Config where Name = 'ZM_AUTH_HASH_SECRET'") );
if (!ok || !query.next()) {
qDebug("Hash Error: error getting zm_auth_hash_secret from db %s", qPrintable(query.lastError().text()));
return QByteArray();
}
QString auth_key = query.value(0).toString(); // HASH Secret
ok = query.exec( QString("SELECT Value from Config where Name = 'ZM_AUTH_HASH_IPS'") );
if (!ok || !query.next()) {
qDebug("Hash Error: error getting zm_auth_hash_ips from db %s", qPrintable(query.lastError().text()));
return QByteArray();
}
bool use_remote_addr = query.value(0).toBool(); // Include remote addr?
ok = query.exec( QString("SELECT now()") );
if (!ok || !query.next()) {
qDebug("Hash Error: Can not read Server Time. now() function doesn't work %s",
qPrintable(query.lastError().text()));
return QByteArray();
}
QDateTime dateTime = query.value(0).toDateTime();
auth_key += m_userName;
auth_key += m_hashPassword;
if ( use_remote_addr )
{
QTcpSocket socket;
socket.connectToHost( db.hostName(), ConnectionManager::connectionWebPort( m_db ), QIODevice::ReadOnly );
//if we can get ip address from the socket in 3000 ms
if ( socket.waitForConnected( 3000 ) ){
auth_key += socket.localAddress().toString();
} else {
//else try with HostInfo
QHostInfo hinfo = QHostInfo::fromName ( QHostInfo::localHostName() );
QHostInfo checkLocalHost = QHostInfo::fromName ( db.hostName() );
if ( ! checkLocalHost.addresses().isEmpty() )
if ( checkLocalHost.addresses().first().toString() == "127.0.0.1" ) hinfo = checkLocalHost;
if ( !hinfo.addresses().isEmpty() )
{
//TODO: fix this. Use the correct interface address and not the first
QHostAddress address = hinfo.addresses().first();
auth_key += address.toString();
}
}
}
dateTime = dateTime.toTimeSpec( Qt::LocalTime );
auth_key += QString::number( dateTime.time().hour() ); //hour
auth_key += QString::number( dateTime.date().day() ); //day of month
auth_key += QString::number( dateTime.date().month() -1 ); //month
auth_key += QString::number( dateTime.date().year() - 1900 ); //years since 1900
qDebug ( qPrintable("authkey: " + auth_key) );
QByteArray ret = QCryptographicHash::hash( auth_key.toUtf8(), QCryptographicHash::Md5 );
//qDebug ( qPrintable(QString (auth_key.toUtf8())) );
qDebug ( qPrintable("authkey hex: " + ret.toHex()) );
m_authKey = ret.toHex();
return m_authKey;
}