TCP - Identity of timed out client - tcp

I want to know the identity of the timed out client ?
how ?
if the function that will receive data like this ..How can I know the client ID ?
your help will be greatly appreciated
Thank you :)
DWORD WINAPI Server::ClientThread(LPVOID lpParam)
{
char receivedData[BUFFER_SIZE];
ThreadData myThreadData = *(ThreadData*)lpParam;
while (1)
{
int returnValue;
// Perform a blocking recv() call
returnValue = recv(myThreadData.clientSocket, receivedData, BUFFER_SIZE, 0);
if (returnValue == 0)
break;
else if (returnValue == SOCKET_ERROR)
{
cout << "recv() failed - Error Code : " << WSAGetLastError() << endl;
}
else
{
receivedData[returnValue] = '\0';
cout << "I am the server and received " << receivedData << endl;
UnderstandComingMessage(receivedData, myThreadData);
}
}
}

I don't know what you mean by 'identity', but you can get the peer IP address and port by calling getpeername() on the socket.

Related

Why 10049 error occurs in udp communication even though ip and port are entered correctly

DWORD WINAPI socketRead(void *lpVoid)
{
while (true)
{
// UDP socket
WSADATA data_s;
WORD version = MAKEWORD(2, 2);
// socket start
int wsok = WSAStartup(version, &data_s);
if (wsok != 0)
{
cout << "Can't start Winsock!" << wsok;
return 0;
}
else
{
cout << "start Winsock!\n";
}
// socket bind
SOCKET in = socket(AF_INET, SOCK_DGRAM, 0);
SOCKADDR_IN serverHint = {};
memset(&serverHint, 0, sizeof(serverHint));
serverHint.sin_family = AF_INET; // IPv4
serverHint.sin_addr.S_un.S_addr = inet_addr("192.168.0.69");
serverHint.sin_port = htons(1480);
if (bind(in, (sockaddr *)&serverHint, sizeof(serverHint)) != SOCKET_ERROR)
{
cout << "bind socket!\n";
}
else
{
cout << "can't bind socket!" << WSAGetLastError() << endl;
// socket clean
int wsokE = WSACleanup();
if (wsokE != 0)
{
cout << "Can't cleanup Winsock!" << wsokE;
}
else
{
cout << "cleanup Winsock!\n";
}
// return 0;
}
}
this is my code. I want to do UDP socket communication using winsocket.
It is trying to do udp communication with another computer.
However, I keep getting error 10049 even though I wrote down the ip address and port number correctly.
The 1480 port I wrote down in the code is what I set arbitrarily. Do I need to do other processing on the computer?
When I use the same ip and port in the incoming and outgoing confirmation program called Ezterm, the values ​​come normally.
In conclusion, we want to receive data from "192.168.0.69".

QSerialPort detecting lost connection

My setup is as follows: Arduino Mega UART3 <--> Voltage Level shifter <--> Rpi4
All the code can be found here
Data is being sent synchronously from the Arduino to the Rpi at 100ms and 1000ms (depending on the importance of the data). And also data is being sent from the Rpi back to the Arduino asynchronously on GUI input (There is also a sync sent at 1000ms in case some frames are lost/corrupted).
Coms are handled in a separate thread than the GUI to provide the best user experience.
Well, all is working fine but I have been trying unsuccessfully to detect if the Rpi has lost connection with the Arduino. (In the other direction is covered with a serial watchdog.)
I wanted to avoid the use of another watchdog in the Qt part but I cannot find a suitable signal to detect the lost serial connection as the QSerialPort keeps reporting a Timeout error randomly... and there are no other methods that detect successfully the disconnection.
Here below is the workaround that I am trying to use without much success: (Probably it needs a major rewrite... but I need to be pointed in the right direction first)
// Serial Port Initialization
m_Serial = new QSerialPort();
m_Serial->setPortName("ttyS0");
//m_Serial->setPortName("ttyUSB0");
m_Serial->setBaudRate(QSerialPort::Baud115200);
m_Serial->setDataBits(QSerialPort::Data8);
m_Serial->setParity(QSerialPort::NoParity);
m_Serial->setStopBits(QSerialPort::OneStop);
m_Serial->setFlowControl(QSerialPort::NoFlowControl);
m_Serial->open(QIODevice::ReadWrite);
qDebug() << "SerialPort Status: " << m_Serial->isOpen();
emit serialConnected(m_Serial->isReadable());
while(!abort)
{
QThread::msleep(5);
while (!isConected(m_Serial)){
emit serialConnected(false);
isSerialConected = false;
QThread::sleep(1);
qDebug() << "Serial Error: ";
//qDebug() << "Is readable?: " << m_Serial->isReadable();
//qDebug() << "Bytes availiable?: " << m_Serial->bytesAvailable();
mutex.lock();
abort = _abort;
mutex.unlock();
}
if (!isSerialConected){
emit serialConnected(true);
isSerialConected=true;
}
mutex.lock();
abort = _abort;
mutex.unlock();
if(!m_outFrameQueue->isEmpty())
{
//qDebug() << "Frame empty";
{ *sendData*}
} else
{
if (m_Serial->waitForReadyRead(10) )
{ *readData*}
And the function that I am trying to use to detect if is actually connected:
bool SerialWorker::isConected(QSerialPort *m_Serial){
// qDebug() << "SerialPort Error: " << m_Serial->error();
// qDebug() << "SerialPort isReadable: " << m_Serial->isReadable();
// qDebug() << "SerialPort isReadable: " << m_Serial->bytesAvailable();
if (m_Serial->error() == QSerialPort::SerialPortError::NoError){
return true;
}
else if (m_Serial->error() == QSerialPort::SerialPortError::TimeoutError){
m_Serial->clearError();
//m_Serial->reset();
return true;
}else{
m_Serial->reset();
m_Serial->close();
m_Serial->clearError();
QThread::sleep(1);
m_Serial->open(QIODevice::ReadWrite);
return false;
}
}

How to connect using UDP to my pic32 and get an answer from it

I want to connet with Qt on windows to my PIC32 UDP server. With a test program in C, I can connect and get the answer, but with Qt it is impossible. What am I doing wrong ?
As you can see I use an ACTIVE WAITING with the while, and my slot doesn't seems to be triggered. Maybe you can see my mistake here ? I hate active waiting....
Here is my code on Qt :
void MuTweezer::run()
{
QHostAddress sender;
quint16 senderPort;
QByteArray datagram;
qint64 pendingBytes;
int cpt = 0;
// Message to send
QByteArray message("Hello that's charly");
// m_imuRcvSocket.bind(10000); why is it for in a client side !?
// SEEMS to NOT BE TRIGGERED
connect(&m_imuRcvSocket, SIGNAL(readyRead()), this, SLOT(recu()));
while(m_isRunning && cpt++ < 10)
{
// send the initial message
qint64 bytesSent= m_imuRcvSocket.writeDatagram(message, QHostAddress("192.168.0.15"), 10000);
cout << "Bytes sent : " << bytesSent << endl;
// We wait the answer from the server
while(!m_imuRcvSocket.hasPendingDatagrams());
// If there is no datagram available, this function returns -1
if((pendingBytes = m_imuRcvSocket.pendingDatagramSize()) == -1)
continue;
datagram.resize(pendingBytes);
m_imuRcvSocket.readDatagram(datagram.data(), datagram.size(),
&sender, &senderPort);
cout << "================="
<< "\nMessage from <" << sender.toString().toStdString().substr(7) << "> on port " << senderPort
<< "\nString : " << datagram.data()
<< "\nSize: " << pendingBytes << " Bytes (characters)\n"
<< "=================" <<
endl;
}
}
Here is my code on the PIC32, as you can see, once I receive a message, I send the answer, it allows me to make a bidirectionnal communication :
if(!UDPIsOpened(mySocket)){
DBPRINTF("Socket CLOSED");
continue; // go back to loop beginning
}
DBPRINTF("Socket OPEN");
if(!(lengthToGet = UDPIsGetReady(mySocket)))
continue;
// get the string
// UDPGetArray : returns the number of bytes successfully read from the UDP buffer.
if((lengthWeGot = UDPGetArray(message, lengthToGet)))
UDPDiscard(); // Discards any remaining RX data from a UDP socket.
/* Modifie it and send it back */
if(UDPIsPutReady(mySocket)){
message[20]= 'Z';
message[21]= 'i';
message[22]= 'b';
message[23]= 'o';
UDPPutArray(message, lengthWeGot);
UDPFlush();
}
Any idea ?
Try to use waitForBytesWritten and waitForReadyRead:
// to receive datagrams, the socket needs to be bound to an address and port
m_imuRcvSocket.bind();
// send the initial message
QByteArray message("Hi it's Charly");
qint64 bytesSent= m_imuRcvSocket.writeDatagram(message,
QHostAddress("200.0.0.3"),
10000);
bool datagramWritten = m_imuRcvSocket.waitForBytesWritten();
// add code to check datagramWritten
datagram.resize(50); // random size for testing
bool datagramReady = m_imuRcvSocket.waitForReadyRead() && m_imuRcvSocket.hasPendingDatagrams();
// add code to check datagramReady
m_imuRcvSocket.readDatagram(datagram.data(),
datagram.size(),
&sender,
&senderPort);
cout << "================="
<< "\nMessage from <" << sender << "> on port " << senderPort
<< "\nString : " << datagram
<< "\nSize: " << pendingBytes << " Bytes (characters)\n"
<< "=================" <<
endl;
A better alternative would be to use signals and slots as described in the documentation of QUdpSocket
if you plan to use the microprocessor as a client with UDP you need the MAC address of the destination machine otherwise it will not work. This one took me 4 hours to figure out.

C++ non-blocking TCP Server cannot send a message with more bytes than it received

I'm pretty new to network programing. I've written a simple non-blocking TCP Server using winsock2 but it behaves in a weird way that I couldn't find any example of it in previously asked questions.
My server can only send a message with as many bytes as it previously received. For example, if previously it received a "rec_msg", when I try to send "message_to_send" it only sends "message".
I don't if it has any effect but the server is encapsulated with a pure static class. Here are the function via a recieve and send message:
int TCPServer_Test::receiveMessage(){
while(1)
{
memset(recvbuf, 0, DEFAULT_BUFLEN);
iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
int err = WSAGetLastError();
int counter = 0;
if (iResult > 0)
{
std::cout << "Mesaj Alindi: " << recvbuf << std::endl;
break;
}
else if(err == WSAEWOULDBLOCK)
{
Sleep(200);
continue;
}
else if (iResult == 0){
printf("Connection closing...\n");
return -1;
}
else
{
printf("recv failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
assert(false);
}
}
}
void TCPServer_Test::sendMessage(char* Source){
strncpy(recvbuf, Source, DEFAULT_BUFLEN);
iSendResult = send( ClientSocket, recvbuf, iResult, 0);
if (iSendResult == SOCKET_ERROR) {
printf("send failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
assert(false);
}
else if (iSendResult == 0) {
printf("send failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
assert(false);
}
else
{
printf("Bytes sent: %d\n", iSendResult);
}
memset(recvbuf, 0, sizeof(recvbuf));
}
I would appreciate any help directly related or not.
It looks like it happens because you are using iResult variable that contains amount of data received during previous recv call when sending data instead of supplying real size of the data to be sent like this:
size_t bytes_count_to_be_send = strlen(Source);
iSendResult = send( ClientSocket, Source, bytes_count_to_be_send, 0);
Also notice that there is no real need to copy data into buffer.

HTTP GET problems

I'm trying to send GET request to generate receiving address (Blockchain api, https://blockchain.info/ru/api/api_receive)
On the page i've generated request - "
/api/receive?method=create&cors=true&format=plain&address=1A8JiWcwvpY7tAopUkSnGuEYHmzGYfZPiq&shared=false&callback=http%3A%2F%2Fgoogle.com
and need to receive an answer -
{"callback_url":"http://google.com","input_address":"16ofW1jBBLbVnDQWJsyL6NKq7hKms9tDLP","destination":"1A8JiWcwvpY7tAopUkSnGuEYHmzGYfZPiq","fee_percent":0}"
I found sample code and trying to send request
SOCKET Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
struct hostent *host;
host = gethostbyname("www.google.com");
SOCKADDR_IN SockAddr;
SockAddr.sin_port = htons(80);
SockAddr.sin_family = AF_INET;
SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);
std::cout << "Connecting...\n";
if (connect(Socket, (SOCKADDR*)(&SockAddr), sizeof(SockAddr)) != 0){
std::cout << "Could not connect";
return -1;
}
std::cout << "Connected.\n";
send(Socket, "GET /api/receive?method=create&cors=true&format=plain&address=1A8JiWcwvpY7tAopUkSnGuEYHmzGYfZPiq&shared=false&callback=http://microsoft.com/ HTTP/1.1\r\nHost: blockchain.info\r\nConnection: close\r\n\r\n", strlen("GET /api/receive?method=create&cors=true&format=plain&address=1A8JiWcwvpY7tAopUkSnGuEYHmzGYfZPiq&shared=false&callback=http://microsoft.com/ HTTP/1.1\r\nHost: blockchain.info\r\nConnection: close\r\n\r\n"), 0);
char buffer[10000];
int nDataLength;
while ((nDataLength = recv(Socket, buffer, 10000, 0)) > 0){
int i = 0;
while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') {
std::cout << buffer[i];
i += 1;
}
}
closesocket(Socket);
return 1;
}
but receive 404 error. What is the problem and what is the best way to parse an answer (I need to get "input_address")? Thanks for help!

Resources