bool RemoteInterfaceSender::sendMessage(RemoteInterfaceMessage* message) {
	// Do we have a valid destination?
	if(message && message->destinationIp != "" && message->destinationPort != 0) {

		// Init socket
		QUdpSocket socket;
		if(!socket.bind(QHostAddress(server->ip), server->port, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint)) {
			// Show error
			Debug::error("[RemoteInterfaceSender] could not bind");
			return false;
		} else {
			// Add port and ip keys
			if(socket.localAddress().toString() != server->ip) 	message->properties->insert("reply-ip",socket.localAddress().toString());
			if(socket.localPort() != server->port) 				message->properties->insert("reply-port",QString("%1").arg(socket.localPort()));

			// Write to socket
			socket.writeDatagram(message->toString().toAscii(), QHostAddress(message->destinationIp), message->destinationPort);

			// Add to sent list
			server->addMessageToSent(message);

			// Show what happened
			Debug::print("[RemoteInterfaceSender] sent %1 message to %2:%3", message->type, message->destinationIp, message->destinationPort);
			return true;
		}

	} else {
		// Show error
		Debug::warning("[RemoteInterfaceSender] message destination must be specified!");
		return false;
	}
}
Beispiel #2
0
/*
 * 析构时发送"我离开了"的消息
 * 因为进行到窗口的析构函数时,子对象都已经被删除,故而不能使用_sender成员进行发送
*/
ChatWindow::~ChatWindow()
{
    QUdpSocket tmpSocket;
    QByteArray bytes=pack_Leave(_username,getIPv4());
    tmpSocket.writeDatagram(bytes,bytes.length(),QHostAddress::Broadcast,_port);
    delete ui;
}
Beispiel #3
0
void LinkQuality::send()
{

    cout<<"send"<<endl;
    int size = packetLengthEdit->text().toInt();
    int count = countEdit->text().toInt();

    //write message to log file
    gpsLock.lockForRead();
    fileLock.lockForWrite();
    *logFile<<"*********************************************"<<endl;
    *logFile<<"local:"<<endl<<"  "<<this->time.toAscii()<<"  "<<this->longitude.toAscii()<<"  "<<latitude.toAscii()
           <<"   "<<count<<"   "<<size<<endl;
    fileLock.unlock();
    gpsLock.unlock();

    QByteArray datagram;
    QDataStream out(&datagram, QIODevice::WriteOnly);
    out<<qint16(1);
    datagram.resize(size);
    cout<<datagram.size()<<endl;
    QUdpSocket sendSocket;
    for(int i = 0; i < count; i++)
    {
        sendSocket.writeDatagram(datagram, datagram.size(), QHostAddress(remoteAddr), CMD_PORT);
        //sleep(1);
    }
}
Beispiel #4
0
void ArduinoThread::run() {
    serv = new QTcpServer(this);
    connect(serv, SIGNAL(newConnection()), this, SLOT(NewConnection()));

    serv->listen(QHostAddress::Any, 34543);

    QProcess proc;
    proc.start("/sbin/ifconfig");
    proc.waitForFinished();
    QString ifconfigOutput = proc.readAllStandardOutput();

    QString strAddress;
    QRegExp rx("addr:([^ ]+)");
    int offset = 0;
    while(-1 != (rx.indexIn(ifconfigOutput, offset))) {
        offset += rx.matchedLength();

        strAddress = "[" + rx.cap(1) + "]";

        if(strAddress == "[127.0.0.1]")
            continue;
        if(!strAddress.contains(QRegExp("\\[\\d+\\.\\d+\\.\\d+\\.\\d+\\]")))
            continue;

        break;
    }

    QUdpSocket *udpSocket = new QUdpSocket(this);
    udpSocket->writeDatagram(strAddress.toAscii(), QHostAddress::Broadcast, 12345);

    exec();
}
void FetchThread::process(QString phost)
{

    QUdpSocket *udpSocket ;
    udpSocket= new QUdpSocket(0);
    udpSocket->bind(QHostAddress::LocalHost, 9999);
    udpSocket->waitForConnected(250);



    QTcpSocket socket;
    socket.connectToHost("localhost", 4949);
    socket.waitForConnected(500);

    while (socket.waitForReadyRead(250));
    QString t_hello = socket.readAll();
    qDebug() << "READ: " << t_hello;

    socket.write(QString("list\n").toStdString().c_str() );
    while (socket.waitForReadyRead(250));
    QString buf1 = socket.readAll();

    qDebug() << "READ: " << buf1;
    QStringList list_probe = buf1.split(QRegExp("\\s+"));

    for (int z=0; z< list_probe.size(); z++)
    {
        QString probe=list_probe.at(z);
        QString cmd = QString("fetch ").append(probe).append("\n");
        qDebug() << "cmd : " << cmd;
        socket.write(cmd.toStdString().c_str() );


        while (socket.waitForReadyRead(250));
        QString buf2 = socket.readAll();
        qDebug() << "Rep fetch :" << buf2 << "\n";

        QRegularExpression re("(\\w+).(\\w+) ([0-9.]+)\\n");
        QRegularExpressionMatchIterator i = re.globalMatch(buf2);
        re.setPatternOptions(QRegularExpression::MultilineOption);

        while (i.hasNext()) {
            QRegularExpressionMatch match = i.next();
            QString s_metric = match.captured(1);
            QString s_value = match.captured(3);
            QString s_mtr = "monit2influxdb,metric="+probe + "_" + s_metric + ",host=" + phost+ " value=" + s_value + " " + QString::number(1000000* QDateTime::currentMSecsSinceEpoch());
            qDebug() << "metric:  " << s_mtr.toLower();

            udpSocket->writeDatagram(s_mtr.toStdString().c_str(), QHostAddress::LocalHost, 9999);




        }

        udpSocket->close();


    }
}
Beispiel #6
0
void tst_QUdpSocket::unconnectedServerAndClientTest()
{
    QUdpSocket serverSocket;

    qRegisterMetaType<QAbstractSocket::SocketState>("QAbstractSocket::SocketState");

    QSignalSpy stateChangedSpy(&serverSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)));
    QVERIFY2(serverSocket.bind(), serverSocket.errorString().toLatin1().constData());
    QCOMPARE(stateChangedSpy.count(), 1);

    const char *message[] = {"Yo mista", "Yo", "Wassap"};

    QHostAddress serverAddress = QHostAddress::LocalHost;
    if (!(serverSocket.localAddress() == QHostAddress::Any))
        serverAddress = serverSocket.localAddress();

    for (int i = 0; i < 3; ++i) {
        QUdpSocket clientSocket;
        QCOMPARE(int(clientSocket.writeDatagram(message[i], strlen(message[i]),
                                                serverAddress, serverSocket.localPort())),
                 int(strlen(message[i])));
        char buf[1024];
        QHostAddress host;
        quint16 port;
        QVERIFY(serverSocket.waitForReadyRead(5000));
        QCOMPARE(int(serverSocket.readDatagram(buf, sizeof(buf), &host, &port)),
                 int(strlen(message[i])));
        buf[strlen(message[i])] = '\0';
        QCOMPARE(QByteArray(buf), QByteArray(message[i]));
    }
}
Beispiel #7
0
QString connection::Broadcast() {
    // Om ip adressen te ontdekken
    QNetworkAddressEntry inter;
    // sockets aanmaken en verbinden met enerzijds broadcast en anderzijds een luister poort
    QUdpSocket udpSocketSend;
    QUdpSocket udpSocketGet;
    udpSocketSend.connectToHost(inter.broadcast(), 40000);
    // udpSocketGet->bind(inter->ip(),667);
    // udpSocketGet->bind(QHostAddress::Any,667)
    if(udpSocketGet.bind(udpgetport,QUdpSocket::ShareAddress))
        Label->setText(Label->text() + "[INFO] Could properly bind udpSocketget to " + QString::number(udpgetport) + "\n");
    else Label->setText(Label->text() + "[INFO] Couldn't properly bind udpSocketget to " + QString::number(udpgetport) + "\n");
    // Pakket verzenden
    QByteArray send_datagram = "DISCOVER-STRATEGO-SERVER";
    // Optimalisatie voor in de loop
    QByteArray receive_datagram;

    quint16 serverPort;
    forever{
        udpSocketSend.writeDatagram(send_datagram, QHostAddress::Broadcast, 40000);
        if(udpSocketGet.waitForReadyRead(3000)){
            receive_datagram.resize(udpSocketGet.pendingDatagramSize());
            udpSocketGet.readDatagram(receive_datagram.data(),receive_datagram.size(),&server,&serverPort);
            if(QString::fromUtf8(receive_datagram.data()) == "DISCOVERED-STRATEGO-SERVER")
            {
                receive_datagram.resize(udpSocketGet.pendingDatagramSize());
                udpSocketGet.readDatagram(receive_datagram.data(),receive_datagram.size(),&server,&serverPort);
                Label->setText(Label->text() +"[INFO] PLAYER DATA: "+ receive_datagram.data() +"\n");
                speler = receive_datagram.toInt();
                if(speler==1)
                {
                    attacker=true;
                }
                else
                {
                    attacker=false;
                }
                receive_datagram.resize(udpSocketGet.pendingDatagramSize());
                udpSocketGet.readDatagram(receive_datagram.data(),receive_datagram.size(),&server,&serverPort);
                Label->setText(Label->text() + "[INFO] GAME DATA: "+receive_datagram.data()+"\n");
                spel = receive_datagram.toInt();
                Label->setText(Label->text() + " SPEL:" + QString::number(spel) + "\n");
                Label->setText(Label->text() + "[INFO] Found STRATEGO-SERVER on " + server.toString().toUtf8().constData() + "\n");
                return server.toString();
            }
        }
        else
        {
            Label->setText(Label->text() + "[INFO] UDP Discover TimeOut!\n");
            static int timeout=0;
            timeout++;
            if(timeout==5)
            {
                Label->setText(Label->text() + "[ERROR] Server is not online. Please try again later!");
                return "";
            }
        }
    }
    return "";
}
Beispiel #8
0
void tst_QUdpSocket::pendingDatagramSize()
{
    QUdpSocket server;
    QVERIFY2(server.bind(), server.errorString().toLatin1().constData());

    QHostAddress serverAddress = QHostAddress::LocalHost;
    if (!(server.localAddress() == QHostAddress::Any))
        serverAddress = server.localAddress();

    QUdpSocket client;
    QVERIFY(client.writeDatagram("this is", 7, serverAddress, server.localPort()) == 7);
    QVERIFY(client.writeDatagram(0, 0, serverAddress, server.localPort()) == 0);
    QVERIFY(client.writeDatagram("3 messages", 10, serverAddress, server.localPort()) == 10);

    char c = 0;
    QVERIFY(server.waitForReadyRead());
    if (server.hasPendingDatagrams()) {
#if defined Q_OS_HPUX && defined __ia64
        QEXPECT_FAIL("", "HP-UX 11i v2 can't determine the datagram size correctly.", Abort);
#endif
        QCOMPARE(server.pendingDatagramSize(), qint64(7));
        c = '\0';
        QCOMPARE(server.readDatagram(&c, 1), qint64(1));
        QCOMPARE(c, 't');
        c = '\0';
    } else {
        QSKIP("does not have the 1st datagram", SkipSingle);
    }

    if (server.hasPendingDatagrams()) {
        QCOMPARE(server.pendingDatagramSize(), qint64(0));
        QCOMPARE(server.readDatagram(&c, 1), qint64(0));
        QCOMPARE(c, '\0'); // untouched
        c = '\0';
    } else {
        QSKIP("does not have the 2nd datagram", SkipSingle);
    }

    if (server.hasPendingDatagrams()) {
        QCOMPARE(server.pendingDatagramSize(), qint64(10));
        QCOMPARE(server.readDatagram(&c, 1), qint64(1));
        QCOMPARE(c, '3');
    } else {
        QSKIP("does not have the 3rd datagram", SkipSingle);
    }
}
Beispiel #9
0
/**
 * @brief TransmitterTask::run
 */
void TransmitterTask::run()
{
    QUdpSocket socket;
    socket.bind(port, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint);
    socket.writeDatagram(data, address, port);
    socket.waitForBytesWritten();
    socket.close();
    qDebug() << "Task:" << address << ':' << port << "<-" << data;
}
Beispiel #10
0
void tst_QUdpSocket::ipv6Loop()
{
    QFETCH(QByteArray, peterMessage);
    QFETCH(QByteArray, paulMessage);
    QFETCH(bool, success);

    QUdpSocket peter;
    QUdpSocket paul;

    quint16 peterPort = 28124;
    quint16 paulPort = 28123;

    if (!peter.bind(QHostAddress::LocalHostIPv6, peterPort)) {
        QCOMPARE(peter.error(), QUdpSocket::UnsupportedSocketOperationError);
    } else {
        QVERIFY(paul.bind(QHostAddress::LocalHostIPv6, paulPort));

        QCOMPARE(peter.writeDatagram(peterMessage.data(), peterMessage.length(), QHostAddress("::1"),
                                     paulPort), qint64(peterMessage.length()));
        QCOMPARE(paul.writeDatagram(paulMessage.data(), paulMessage.length(),
                                    QHostAddress("::1"), peterPort), qint64(paulMessage.length()));

        char peterBuffer[16*1024];
        char paulBuffer[16*1024];
#if !defined(Q_OS_WINCE)
        QVERIFY(peter.waitForReadyRead(5000));
        QVERIFY(paul.waitForReadyRead(5000));
#else
        QVERIFY(peter.waitForReadyRead(15000));
        QVERIFY(paul.waitForReadyRead(15000));
#endif
        if (success) {
            QCOMPARE(peter.readDatagram(peterBuffer, sizeof(peterBuffer)), qint64(paulMessage.length()));
            QCOMPARE(paul.readDatagram(paulBuffer, sizeof(peterBuffer)), qint64(peterMessage.length()));
        } else {
            QVERIFY(peter.readDatagram(peterBuffer, sizeof(peterBuffer)) != paulMessage.length());
            QVERIFY(paul.readDatagram(paulBuffer, sizeof(peterBuffer)) != peterMessage.length());
        }

        QCOMPARE(QByteArray(peterBuffer, paulMessage.length()), paulMessage);
        QCOMPARE(QByteArray(paulBuffer, peterMessage.length()), peterMessage);
    }
}
Beispiel #11
0
void tst_QUdpSocket::broadcasting()
{
    QFETCH_GLOBAL(bool, setProxy);
    if (setProxy) {
#ifdef TEST_QNETWORK_PROXY
        QFETCH_GLOBAL(int, proxyType);
        if (proxyType == QNetworkProxy::Socks5Proxy) {
            QSKIP("With socks5 Broadcast is not supported.", SkipAll);
        }
#endif
    }
#ifdef Q_OS_AIX
    QSKIP("Broadcast does not work on darko", SkipAll);
#endif
    const char *message[] = {"Yo mista", "", "Yo", "Wassap"};

    for (int i = 0; i < 4; ++i) {
        QUdpSocket serverSocket;
        QVERIFY2(serverSocket.bind(QHostAddress::Any, 5000), serverSocket.errorString().toLatin1().constData());

        QCOMPARE(serverSocket.state(), QUdpSocket::BoundState);

        connect(&serverSocket, SIGNAL(readyRead()), SLOT(empty_readyReadSlot()));

        QUdpSocket broadcastSocket;

        for (int j = 0; j < 100; ++j) {
            broadcastSocket.writeDatagram(message[i], strlen(message[i]),
                                          QHostAddress::Broadcast, 5000);
            QTestEventLoop::instance().enterLoop(15);
            if (QTestEventLoop::instance().timeout()) {
#if defined(Q_OS_FREEBSD)
                QEXPECT_FAIL("",
                             "Broadcasting to 255.255.255.255 does not work on FreeBSD",
                             Abort);
                QVERIFY(false); // seems that QFAIL() doesn't respect the QEXPECT_FAIL() :/
#endif
                QFAIL("Network operation timed out");
            }
            QVERIFY(serverSocket.hasPendingDatagrams());

            do {
                QByteArray arr;
                arr.resize(serverSocket.pendingDatagramSize() + 1);
                QHostAddress host;
                quint16 port;
                QCOMPARE((int) serverSocket.readDatagram(arr.data(), arr.size() - 1, &host, &port),
                         (int) strlen(message[i]));
                arr.resize(strlen(message[i]));
                QCOMPARE(arr, QByteArray(message[i]));
            } while (serverSocket.hasPendingDatagrams());
        }
    }
}
Beispiel #12
0
void DevicePluginWakeOnLan::wakeup(QString mac)
{
    const char header[] = {char(0xff), char(0xff), char(0xff), char(0xff), char(0xff), char(0xff)};
    QByteArray packet = QByteArray::fromRawData(header, sizeof(header));
    for(int i = 0; i < 16; ++i) {
        packet.append(QByteArray::fromHex(mac.remove(':').toLocal8Bit()));
    }
    qCDebug(dcWakeOnLan) << "Created magic packet:" << packet.toHex();
    QUdpSocket udpSocket;
    udpSocket.writeDatagram(packet.data(), packet.size(), QHostAddress::Broadcast, 9);
}
Beispiel #13
0
bool Myth::SendMessage( const QString &sMessage,
                        const QString &sAddress,
                        int   udpPort,
                        int   Timeout)
{
    bool bResult = false;

    if (sMessage.isEmpty())
        return bResult;

    if (Timeout < 0 || Timeout > 999)
        Timeout = 0;

    QString xmlMessage =
        "<mythmessage version=\"1\">\n"
        "  <text>" + sMessage + "</text>\n"
        "  <timeout>" + QString::number(Timeout) + "</timeout>\n"
        "</mythmessage>";

    QHostAddress address = QHostAddress::Broadcast;
    unsigned short port = 6948;

    if (!sAddress.isEmpty())
        address.setAddress(sAddress);

    if (udpPort != 0)
        port = udpPort;

    QUdpSocket *sock = new QUdpSocket();
    QByteArray utf8 = xmlMessage.toUtf8();
    int size = utf8.length();

    if (sock->writeDatagram(utf8.constData(), size, address, port) < 0)
    {
        LOG(VB_GENERAL, LOG_ERR,
            QString("Failed to send UDP/XML packet (Message: %1 "
                    "Address: %2 Port: %3")
                .arg(sMessage).arg(sAddress).arg(port));
    }
    else
    {
        LOG(VB_GENERAL, LOG_DEBUG,
            QString("UDP/XML packet sent! (Message: %1 Address: %2 Port: %3")
                .arg(sMessage)
                .arg(address.toString().toLocal8Bit().constData()).arg(port));
        bResult = true;
    }

    sock->deleteLater();

    return bResult;
}
Beispiel #14
0
void tst_QUdpSocket::loop()
{
    QFETCH(QByteArray, peterMessage);
    QFETCH(QByteArray, paulMessage);
    QFETCH(bool, success);

    QUdpSocket peter;
    QUdpSocket paul;

    QVERIFY2(peter.bind(), peter.errorString().toLatin1().constData());
    QVERIFY2(paul.bind(), paul.errorString().toLatin1().constData());

    QHostAddress peterAddress = QHostAddress::LocalHost;
    if (!(peter.localAddress() == QHostAddress::Any))
        peterAddress = peter.localAddress();
    QHostAddress pualAddress = QHostAddress::LocalHost;
    if (!(paul.localAddress() == QHostAddress::Any))
        pualAddress = paul.localAddress();

    QCOMPARE(peter.writeDatagram(peterMessage.data(), peterMessage.length(),
                                 pualAddress, paul.localPort()), qint64(peterMessage.length()));
    QCOMPARE(paul.writeDatagram(paulMessage.data(), paulMessage.length(),
                                peterAddress, peter.localPort()), qint64(paulMessage.length()));

    QVERIFY(peter.waitForReadyRead(5000));
    QVERIFY(paul.waitForReadyRead(5000));
    char peterBuffer[16*1024];
    char paulBuffer[16*1024];
    if (success) {
        QCOMPARE(peter.readDatagram(peterBuffer, sizeof(peterBuffer)), qint64(paulMessage.length()));
        QCOMPARE(paul.readDatagram(paulBuffer, sizeof(peterBuffer)), qint64(peterMessage.length()));
    } else {
        QVERIFY(peter.readDatagram(peterBuffer, sizeof(peterBuffer)) != paulMessage.length());
        QVERIFY(paul.readDatagram(paulBuffer, sizeof(peterBuffer)) != peterMessage.length());
    }

    QCOMPARE(QByteArray(peterBuffer, paulMessage.length()), paulMessage);
    QCOMPARE(QByteArray(paulBuffer, peterMessage.length()), peterMessage);
}
Beispiel #15
0
qint64 ServerPool::writeDatagram(const char * data, qint64 size,
                                 const QHostAddress &addr, quint16 port)
{
    if (!m_listening || m_udpSockets.isEmpty())
    {
        LOG(VB_GENERAL, LOG_ERR, "Trying to write datagram to disconnected "
            "ServerPool instance.");
        return -1;
    }

    QUdpSocket *socket = m_udpSockets.first();
    return socket->writeDatagram(data, size, addr, port);
}
Beispiel #16
0
static int SendMessage(const MythUtilCommandLineParser &cmdline)
{
    QHostAddress address = QHostAddress::Broadcast;
    unsigned short port = 6948;

    QString message = kMessage;

    if (cmdline.toBool("udpport"))
        port = (unsigned short)cmdline.toUInt("udpport");
    if (cmdline.toBool("bcastaddr"))
        address.setAddress(cmdline.toString("bcastaddr"));

    QMap<QString,QString>::const_iterator i;
    QMap<QString,QString> extras = cmdline.GetExtra();
    for (i = extras.begin(); i != extras.end(); ++i)
    {
        QString name = i.key();
        QString value = i.value();

        name.replace("--", "");
        cerr << "name: " << name.toLocal8Bit().constData()
             << " -- value: " << value.toLocal8Bit().constData() << endl;

        name.append("%");
        name.prepend("%");
        message.replace(name, value);
    }

    cout << "output:\n" << message.toLocal8Bit().constData() << endl;

    QUdpSocket *sock = new QUdpSocket();
    QByteArray utf8 = message.toUtf8();

    int result = GENERIC_EXIT_OK;
    if (sock->writeDatagram(utf8, address, port) < 0)
    {
        cout << "Failed to send UDP/XML packet" << endl;
        result = GENERIC_EXIT_NOT_OK;
    }
    else
    {
        cout << "Sent UDP/XML packet to IP "
             << address.toString().toLocal8Bit().constData()
             << " and port: " << port << endl;
    }

    sock->deleteLater();
   
    return result;
}
Beispiel #17
0
void connection::sendChatData()
{
    QUdpSocket udpSocketSend;
    QByteArray send_datagram;
    qDebug("send1");
    QByteArray datagram = ChatInput->toPlainText().toUtf8();
    ChatInput->clear();
    qDebug("send1.1");
    send_datagram = datagram + "@@" + QByteArray::number(speler);
    qDebug("send1.2");
    qDebug() << send_datagram;
    udpSocketSend.writeDatagram(send_datagram, opponent, 6666);
    qDebug("send1.3");
}
Beispiel #18
0
void tst_QUdpSocket::writeDatagramToNonExistingPeer()
{
    QFETCH(bool, bind);
    QFETCH(QHostAddress, peerAddress);

    quint16 peerPort = 33533 + int(bind);

    QUdpSocket sUdp;
    QSignalSpy sReadyReadSpy(&sUdp, SIGNAL(readyRead()));
    if (bind)
        QVERIFY(sUdp.bind());
    QCOMPARE(sUdp.writeDatagram("", 1, peerAddress, peerPort), qint64(1));
    QTestEventLoop::instance().enterLoop(1);
    QCOMPARE(sReadyReadSpy.count(), 0);
}
Beispiel #19
0
Datei: main.cpp Projekt: xtuer/Qt
int main(int argc, char *argv[]) {
    QCoreApplication a(argc, argv);

    QHostAddress multicastAddress("225.20.40.20"); // Multicast 组的地址
    QUdpSocket *udpSocket = new QUdpSocket();
    int messageCount = 10;

    for (int i = 0; i < messageCount; ++i) {
        QString data = generateMessage(i, '*');
        // 使用 Unicast 发送消息
        udpSocket->writeDatagram(data.toUtf8(), multicastAddress, 13930);
        qDebug() << data;
    }

    return a.exec();
}
Beispiel #20
0
	void UDPBundleSender::uploadBundles(const AudioBundle::Vector& toUpload) const
	{
		QUdpSocket socket;
		for (int i = 0; i < toUpload.size(); ++i)
		{
			QByteArray serializedBundle;
			toUpload[i]->serialize(serializedBundle);
			if (socket.writeDatagram(serializedBundle, QHostAddress(ip), port) == -1)
			{
				DEBUG << "Bundle" << i << "was not sent";
			}

			QThread::msleep(sendingDelay);
//			QThread::msleep(1);
		}
	}
Beispiel #21
0
bool UDPSocket::sendUDPDatagramWithAnyPort(const QHostAddress &targetAddress, quint16 targetPort, const QByteArray &data, QString *errorString){
    qDebug()<<"UDPSocket::sendUDPDatagram(...)-targetAddress:"<<targetAddress.toString()<<" targetPort:"<<targetPort;

    QUdpSocket udpSocket;
    qint64 size = udpSocket.writeDatagram(data, targetAddress, targetPort);
    if(errorString){
        *errorString = udpSocket.errorString();
    }

    if(size == -1){
        qCritical()<<QString("UDP Datagram Sent Failed! Target Address:%1, Port:%2, %3").arg(targetAddress.toString()).arg(targetPort).arg(udpSocket.errorString());
        return false;
    } 

    return (size == data.size())?true:false;;

}
Beispiel #22
0
void Midi2UdpThread::run()
{
	QUdpSocket *udpSocket;
	udpSocket = new QUdpSocket(0);
	 
	forever {
		
		if (abort) {
			delete udpSocket;
			
			return;
		}
		
		if (poll(pfd, npfd, 250) > 0) {
			
			// Get MIDI event
			snd_seq_event_input(seq_handle, &midi_event);
			
			long len = snd_midi_event_decode(eventparser, midimsg, MAX_MIDI_MESSAGE_LENGTH, midi_event);
			
			if( len < 0 ) {
				printf("midi2udp: Error decoding midi event!\n");
			} else {
				printf("midi2udp: got midi event: ");
				for(int i=0; i<len; ++i) {
					printf("0x%x ", midimsg[i]);
				}
				printf("\n");
			
				// Send it over UDP
				for(set<string>::iterator ip_it = ds_ips.begin(); ip_it != ds_ips.end(); ++ip_it)
				{
					QString to_((*ip_it).c_str());
					printf("sending to %s\n", (*ip_it).c_str());
					QHostAddress to(to_);
					udpSocket->writeDatagram((char*)midimsg, len, to, DS_PORT);
				}
			}
			
			snd_seq_free_event(midi_event);
			
			snd_midi_event_reset_decode(eventparser);
		}
	}
}
Beispiel #23
0
/** Manda un Magic Packet a la MAC*/
void In2MagicPacket::SendPacket(QString strMAC){
    QByteArray packet;
    packet.fill(0xFF,6);
    QStringList lst=strMAC.split(":");
    QByteArray bArrayMac;
    bool ok;
    for (int x=0;x<lst.count();x++){
        const unsigned int foo=lst.at(x).toInt(&ok,16);
        bArrayMac.append(foo);
    }
    //Metemos la direccion 16 veces
    for (int x=0;x<16;x++){
        packet.append(bArrayMac);
    }

    QUdpSocket p;
    QHostAddress myBroadcastAddress = QHostAddress("255.255.255.255");
    p.writeDatagram(packet,myBroadcastAddress,9);
}
Beispiel #24
0
void tst_QUdpSocket::writeDatagram()
{
    QUdpSocket server;
    QVERIFY2(server.bind(), server.errorString().toLatin1().constData());

    QHostAddress serverAddress = QHostAddress::LocalHost;
    if (!(server.localAddress() == QHostAddress::Any))
        serverAddress = server.localAddress();

    QUdpSocket client;

    qRegisterMetaType<qint64>("qint64");
    qRegisterMetaType<QAbstractSocket::SocketError>("QAbstractSocket::SocketError");

    for(int i=0;; i++) {
        QSignalSpy errorspy(&client, SIGNAL(error(QAbstractSocket::SocketError)));
        QSignalSpy bytesspy(&client, SIGNAL(bytesWritten(qint64)));

        qint64 written = client.writeDatagram(QByteArray(i * 1024, 'w'), serverAddress,
                                              server.localPort());

        if (written != i * 1024) {
#if defined (Q_OS_HPUX)
            QSKIP("HP-UX 11.11 on hai (PA-RISC 64) truncates too long datagrams.", SkipSingle);
#endif
            QCOMPARE(bytesspy.count(), 0);
            QCOMPARE(errorspy.count(), 1);
            QCOMPARE(*static_cast<const int *>(errorspy.at(0).at(0).constData()),
                     int(QUdpSocket::DatagramTooLargeError));
            QCOMPARE(client.error(), QUdpSocket::DatagramTooLargeError);
            break;
        }
        QVERIFY(bytesspy.count() == 1);
        QCOMPARE(*static_cast<const qint64 *>(bytesspy.at(0).at(0).constData()),
                 qint64(i * 1024));
        QCOMPARE(errorspy.count(), 0);
        if (!server.waitForReadyRead(5000))
            QSKIP(QString("UDP packet lost at size %1, unable to complete the test.").arg(i * 1024).toLatin1().data(), SkipSingle);
        QCOMPARE(server.pendingDatagramSize(), qint64(i * 1024));
        QCOMPARE(server.readDatagram(0, 0), qint64(0));
    }
}
Beispiel #25
0
//I'm in a new network, let's be polite and introduce myself
void LanLinkProvider::broadcastToNetwork()
{

    if (!mServer->isListening()) {
        //Not started
        return;
    }

    Q_ASSERT(mTcpPort != 0);

    qCDebug(KDECONNECT_CORE()) << "Broadcasting identity packet";

    QHostAddress destAddress = mTestMode? QHostAddress::LocalHost : QHostAddress(QStringLiteral("255.255.255.255"));

    NetworkPackage np(QLatin1String(""));
    NetworkPackage::createIdentityPackage(&np);
    np.set(QStringLiteral("tcpPort"), mTcpPort);

#ifdef Q_OS_WIN
    //On Windows we need to broadcast from every local IP address to reach all networks
    QUdpSocket sendSocket;
    for (const QNetworkInterface &iface : QNetworkInterface::allInterfaces()) {
        if ( (iface.flags() & QNetworkInterface::IsUp)
          && (iface.flags() & QNetworkInterface::IsRunning)
          && (iface.flags() & QNetworkInterface::CanBroadcast)) {
            for (const QNetworkAddressEntry &ifaceAddress : iface.addressEntries()) {
                QHostAddress sourceAddress = ifaceAddress.ip();
                if (sourceAddress.protocol() == QAbstractSocket::IPv4Protocol && sourceAddress != QHostAddress::LocalHost) {
                    qCDebug(KDECONNECT_CORE()) << "Broadcasting as" << sourceAddress;
                    sendSocket.bind(sourceAddress, PORT);
                    sendSocket.writeDatagram(np.serialize(), destAddress, PORT);
                    sendSocket.close();
                }
            }
        }
    }
#else
    mUdpSocket.writeDatagram(np.serialize(), destAddress, PORT);
#endif

}
Beispiel #26
0
void tst_QUdpSocket::zeroLengthDatagram()
{
    QFETCH_GLOBAL(bool, setProxy);
    if (setProxy)
        return;

    QUdpSocket receiver;
    QVERIFY(receiver.bind());

    QVERIFY(!receiver.waitForReadyRead(100));
    QVERIFY(!receiver.hasPendingDatagrams());

    QUdpSocket sender;
    QCOMPARE(sender.writeDatagram(QByteArray(), QHostAddress::LocalHost, receiver.localPort()), qint64(0));

    QVERIFY(receiver.waitForReadyRead(1000));
    QVERIFY(receiver.hasPendingDatagrams());

    char buf;
    QCOMPARE(receiver.readDatagram(&buf, 1), qint64(0));
}
void DialogTimeStampGenerator2::on_pushButton_clicked()
{
	static TB2PC_PACKET p;
	static ALIVE_PACKET ap;

	p.magicNumber1 = MAGIC_NUMBER1;
	p.magicNumber2 = MAGIC_NUMBER2;

	p.packetVersion = ui->lineEdit_packetVersion->text().toInt();
	p.batteryVoltageTB = ui->lineEdit_batteryVoltageTB->text().toInt();
	p.triggerStationID = ui->comboBox_triggerStationID->itemData(ui->comboBox_triggerStationID->currentIndex()).toInt();
	p.binRssiTS = ui->lineEdit_binRssiTS->text().toInt();

	QTime t0(0,0,0);
	ap.triggerTimeBB = t0.msecsTo(ui->timeEdit_triggerTimeBB->time())*10;
	ap.triggerTimeTS_L = t0.msecsTo(ui->timeEdit_triggerTimeTS_L->time())*10;
	ap.triggerTimeTS_R = t0.msecsTo(ui->timeEdit_triggerTimeTS_R->time())*10;
	ap.batteryVoltageTS = ui->lineEdit_batteryVoltageTS->text().toInt();
	ap.batteryVoltageBB = ui->lineEdit_batteryVoltageBB->text().toInt();
	ap.boatBoxID = ui->comboBox_boatBoxID->itemData(ui->comboBox_boatBoxID->currentIndex()).toInt();
	ap.binRssiBB = ui->lineEdit_binRssiBB->text().toInt();
	ap.stationTriggeredAt = ui->comboBox_stationTriggeredAt->itemData(ui->comboBox_stationTriggeredAt->currentIndex()).toInt();

	p.tsPacket = ap;

	p.baseTime_100us = t0.msecsTo(ui->timeEdit_baseTime->time())*10;

	p.crc = CRC8_run((uint8_t*)(&p), sizeof(p)-1);

	//printPacket(p);

	QByteArray datagram;
	datagram.setRawData((char*)(&p), sizeof(p));

	QUdpSocket* udpSocket = new QUdpSocket(this);
	udpSocket->writeDatagram(datagram.data(), datagram.size(), QHostAddress::Broadcast, UDP_LISTEN_PORT);
}
Beispiel #28
0
bool Myth::SendNotification( bool  bError,
                             const QString &Type,
                             const QString &sMessage,
                             const QString &sOrigin,
                             const QString &sDecription,
                             const QString &sImage,
                             const QString &sExtra,
                             const QString &sProgressText,
                             float fProgress,
                             int   Duration,
                             bool  bFullscreen,
                             uint  Visibility,
                             uint  Priority,
                             const QString &sAddress,
                             int   udpPort )
{
    bool bResult = false;

    if (sMessage.isEmpty())
        return bResult;

    if (Duration < 0 || Duration > 999)
        Duration = -1;

    QString xmlMessage =
        "<mythnotification version=\"1\">\n"
        "  <text>" + sMessage + "</text>\n"
        "  <origin>" + (sOrigin.isNull() ? tr("MythServices") : sOrigin) + "</origin>\n"
        "  <description>" + sDecription + "</description>\n"
        "  <timeout>" + QString::number(Duration) + "</timeout>\n"
        "  <image>" + sImage + "</image>\n"
        "  <extra>" + sExtra + "</extra>\n"
        "  <progress_text>" + sProgressText + "</progress_text>\n"
        "  <progress>" + QString::number(fProgress) + "</progress>\n"
        "  <fullscreen>" + (bFullscreen ? "true" : "false") + "</fullscreen>\n"
        "  <visibility>" + QString::number(Visibility) + "</visibility>\n"
        "  <priority>" + QString::number(Priority) + "</priority>\n"
        "  <type>" + (bError ? "error" : Type) + "</type>\n"
        "</mythnotification>";

    QHostAddress address = QHostAddress::Broadcast;
    unsigned short port = 6948;

    if (!sAddress.isEmpty())
        address.setAddress(sAddress);

    if (udpPort != 0)
        port = udpPort;

    QUdpSocket *sock = new QUdpSocket();
    QByteArray utf8 = xmlMessage.toUtf8();
    int size = utf8.length();

    if (sock->writeDatagram(utf8.constData(), size, address, port) < 0)
    {
        LOG(VB_GENERAL, LOG_ERR,
            QString("Failed to send UDP/XML packet (Notification: %1 "
                    "Address: %2 Port: %3")
                .arg(sMessage).arg(sAddress).arg(port));
    }
    else
    {
        LOG(VB_GENERAL, LOG_DEBUG,
            QString("UDP/XML packet sent! (Notification: %1 Address: %2 Port: %3")
                .arg(sMessage)
                .arg(address.toString().toLocal8Bit().constData()).arg(port));
        bResult = true;
    }

    sock->deleteLater();

    return bResult;
}
Beispiel #29
0
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QCoreApplication::setApplicationName("mythmessage");

    QHostAddress address = QHostAddress::Broadcast;
    unsigned short port = 6948;

    QString message = kMessage;

    bool verbose = false;

    MythMessageCommandLineParser cmdline;
    if (!cmdline.Parse(argc, argv))
    {
        cmdline.PrintHelp();
        return GENERIC_EXIT_INVALID_CMDLINE;
    }

    if (cmdline.toBool("showhelp"))
    {
        cmdline.PrintHelp();
        return GENERIC_EXIT_OK;
    }

    if (cmdline.toBool("showversion"))
    {
        cmdline.PrintVersion();
        return GENERIC_EXIT_OK;
    }

    if (cmdline.toBool("printtemplate"))
    {
        cerr << kMessage.toLocal8Bit().constData() << endl;
        return GENERIC_EXIT_OK;
    }

    if (cmdline.toBool("verbose"))
        verbose = true;
    if (cmdline.toBool("port"))
        port = (unsigned short)cmdline.toUInt("port");
    if (cmdline.toBool("addr"))
        address.setAddress(cmdline.toString("addr"));

    QMap<QString,QString>::const_iterator i;
    QMap<QString,QString> extras = cmdline.GetExtra();
    for (i = extras.begin(); i != extras.end(); ++i)
    {
        QString name = i.key();
        QString value = i.value();

        name.replace("--", "");
        if (verbose)
            cerr << "name: " << name.toLocal8Bit().constData()
                 << " -- value: " << value.toLocal8Bit().constData() << endl;

        name.append("%");
        name.prepend("%");
        message.replace(name, value);
    }

    if (verbose)
        cout << "output:\n" << message.toLocal8Bit().constData() << endl;

    QUdpSocket *sock = new QUdpSocket();
    QByteArray utf8 = message.toUtf8();

    if (sock->writeDatagram(utf8, address, port) < 0)
    {
        cout << "Failed to send UDP/XML packet" << endl;
    }
    else
    {
        cout << "Sent UDP/XML packet to IP "
             << address.toString().toLocal8Bit().constData()
             << " and port: " << port << endl;
    }

    sock->deleteLater();
   
    return GENERIC_EXIT_OK;
}
Beispiel #30
-1
void SendNetworkPackets(unsigned int i, unsigned int j, unsigned int k) { //sends desired data over UDP to the robot. I used it to send the # of squares and the ms required to render each frame. (It uses the time data to know when to read for UDP packets and hence the for loop iteration essentially stands for the # of frames it wants to read from the odroid.
    static QUdpSocket udpSocket; //create socket
    
    QByteArray datagram = QByteArray::number(i) + " " + QByteArray::number(j) + " " + QByteArray::number(k) + " "; //create data stream
    
    udpSocket.writeDatagram(datagram.data(), datagram.size(), QHostAddress(QstringTargetIPAddress), TargetPortNumber); //send that data stream over UDP to the TargetIpAddress with the given TargetPortNumber
}