I am working on a UDP socket in C++ that is a client and also a server at one time. I am using Visual Studio 2017 and run it on Windows 7. I have some troubles with recvfrom() function, that is ending with "invalid argument" error. I think socket is okay, sockaddr_in structs are okay, thread is okay and even the while-loop with sendto() function is okay. But the thread ends after calling a recvfrom() function and I really don't know where the problem is...
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>
#include <thread>
#pragma comment(lib, "Ws2_32.lib")
using namespace std;
void printMessage(SOCKET s, SOCKADDR_IN destAddr) {
char message[100];
int result, error;
int addrSize = sizeof(destAddr);
do {
printf("som v threade\n");
result = recvfrom(s, message, 100, 0, (SOCKADDR*)&destAddr, &addrSize);
printf("%d\n", result);
if (result < 0) {
error = WSAGetLastError();
printf("%d\n", error);
}
if (result > 0)
printf("%s", message);
} while (result > 0);
}
int main(int argc, char *argv[]) {
WORD dllVersion = MAKEWORD(2, 1);
WSADATA wsaData;
if (WSAStartup(dllVersion, &wsaData) != 0) {
printf("Winsock startup failed");
exit(1);
}
const char *ip = "127.0.0.1";
int dstPort = 49999;
int srcPort = 49999;
SOCKADDR_IN destaddr, srcaddr;
SOCKET s;
s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (s < 0) {
printf("Error creating socket");
exit(1);
}
destaddr.sin_family = AF_INET;
destaddr.sin_addr.s_addr = inet_addr(ip);
destaddr.sin_port = htons(dstPort);
srcaddr.sin_family = AF_INET;
srcaddr.sin_addr.s_addr = htonl(INADDR_ANY);
srcaddr.sin_port = htons(srcPort);
bind(s, (SOCKADDR*)&srcaddr, sizeof(srcaddr));
thread receiving (printMessage, s, destaddr);
receiving.detach();
while (1) {
char message[100];
printf("Write a message:");
scanf("%s", message);
if (sendto(s, message, sizeof(message), 0, (SOCKADDR *) &destaddr, sizeof(destaddr)) < 0) {
printf("Message not sent");
exit(1);
}
}
return 0;
}