PDA

View Full Version : Remake udp (SOCK_DGRAM) socket onto QUdpSocket



pethead
2nd November 2010, 03:49
I have this code in my C program.
Now I'm coding on Qt and want to remake this to QUdpSocket.
Is it really?

algorythm are here:
we have ip and port of udp server,
make data and send it to ip and port of server,
and waiting answer...
i can't use bind(ip,port), i don't know recv port, its generates the socket subsystem, and server get it from incoming datagramm.
i know Qudpsocket needs to be bind on fixed port.
Qudpsocket is unusable at my use?



unsigned char sendbuf[11] = "";
unsigned char recvbuf[DEFAULT_BUFLEN] = "";

SOCKET S;
sockaddr_in SA;
int SA_Size = sizeof(SA);

int iResult;
int recvbuflen = DEFAULT_BUFLEN;

WSAData WSData;
WSAStartup(0x101,&WSData);

S = socket(AF_INET,SOCK_DGRAM,0);

SA.sin_family=AF_INET;
SA.sin_port=htons(2323);
SA.sin_addr.S_un.S_addr=inet_addr(_ip.c_str());

//filling sendbuf here..

//sending sendbuf
sendto(S, (char*)sendbuf,sizeof(sendbuf), 0,(struct sockaddr *)&SA, sizeof(SA))

//receiving answer
fd_set rfds;
struct timeval tv;
tv.tv_sec = _timeout;
tv.tv_usec = 0;
FD_ZERO(&rfds);
FD_SET(S,&rfds);
if (select((int)S+1, &rfds, NULL, NULL, &tv) > 0)
{
//getting data from
iResult=recvfrom(S, (char*)recvbuf, recvbuflen, 0, (struct sockaddr *)&SA, &SA_Size);
closesocket(S);
WSACleanup();
}
...

ChrisW67
2nd November 2010, 05:22
Have you read the Broadcast Receiver (http://doc.qt.nokia.com/4.7/network-broadcastreceiver.html) and Broadcast Sender (http://doc.qt.nokia.com/4.7/network-broadcastsender.html) examples?

What have you tried?

pethead
2nd November 2010, 07:26
these samples based on binding of fixed port 45454.
sender and receiver connected to each other by knowing fixed port. how about if another receiver will connect from the same computer? the port is already binded. that is. second receiver doesn't receive anything.

Added after 1 18 minutes:

i did it! :)

ingredients:

m_pUdpSocket = new QUdpSocket(this);
m_pUdpSocket->connectToHost(strHost, nPort);

method write:

QByteArray arrBlock;
QDataStream out(&arrBlock, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_7);
out << (qint8)0x4C << (qint8)0x4D << (qint8)0x43 << (qint8)0x50 << (qint8)0x00 << (qint8)0x01 << (qint8)0xAA << (qint8)0xBB << (qint8)0x01 << (qint8)0x00 << (qint8)0x00;
m_pUdpSocket->write(arrBlock);

and slotReadyRead reacted by m_pUdpSocket, SIGNAL(readyRead()) has received Server answer on generic socket port.

I watched all exchage in WireShark sniffer.