#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include<stdio.h>
#include<iostream>
using namespace std;
#include<winsock2.h>
#include <windows.h>
#pragma comment(lib,"ws2_32.lib") //Winsock Library
#define BUFLEN 512 //Max length of buffer
#define PORT 2000 //The port on which to listen for incoming data
#include <sys/types.h>
#include <pthread.h>
struct sockaddr_in si_other;
int s, recv_len, slen = sizeof(si_other);
char buf[BUFLEN];
char message[BUFLEN];
WSADATA wsa;
char SERVER[15];
pthread_t inviaT, riceviT;
int x;
void *invia(void *);
void *ricevi(void *);
int main(void)
{
printf("Inserisci indirizzo ip: ");
gets(SERVER);
fflush(stdin);
//Initialise winsock
//printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
{
printf("Failed. Error Code : %d", WSAGetLastError());
exit(EXIT_FAILURE);
}
//printf("Initialised.\n");
//create socket
if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == SOCKET_ERROR)
{
printf("socket() failed with error code : %d", WSAGetLastError());
exit(EXIT_FAILURE);
}
//setup address structure
memset((char *)&si_other, 0, sizeof(si_other));
si_other.sin_family = AF_INET;
si_other.sin_port = htons(PORT);
si_other.sin_addr.S_un.S_addr = inet_addr(SERVER);
//start communication
while (1)
{
x = pthread_create(&inviaT, NULL, invia, NULL);
x = pthread_create(&riceviT, NULL, ricevi, NULL);
pthread_join(inviaT, NULL);
pthread_join(riceviT, NULL);
}
closesocket(s);
WSACleanup();
return 0;
}
void *invia(void *in){
printf("Inserisci messaggio: ");
gets(message);
if (sendto(s, message, strlen(message), 0, (struct sockaddr *) &si_other, slen) == SOCKET_ERROR)
{
printf("sendto() failed with error code : %d", WSAGetLastError());
exit(EXIT_FAILURE);
}
}
void *ricevi(void *in){
//receive a reply and print it
//clear the buffer by filling null, it might have previously received data
memset(buf, '\0', BUFLEN);
//try to receive some data, this is a blocking call
if (recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen) == SOCKET_ERROR)
{
printf("recvfrom() failed with error code : %d", WSAGetLastError());
exit(EXIT_FAILURE);
}
puts(buf);
}