1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
|
#include "unicast_socket_sendto.h"
#include <errno.h> /* errno */
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
/* gettimeofday */
int unicast_socket_sendto( int port, char * dest_ip, char * message) {
struct sockaddr_in sDest;
int socket_id;
WSADATA wsad; //Structure required to activate sockets
int iResult = 0; // variable to perform tests
char msg_rcv[1024]; //message received
if (WSAStartup(2,&wsad) == 0)
{
printf("Sockets are now usable...\n");
}
else
{
printf("Error n°%d : Error during initialization.\n", errno);
//exit(errno);
return errno;
}
//Initialization of the UDP socket
socket_id = socket(AF_INET, SOCK_DGRAM,0);
if(socket_id != -1)
{
printf("Initialization of the UDP socket successful.\n");
}
else
{
printf("Erreur n%d : Unable to initialize socket.\n",errno);
//exit(errno);
return errno;
}
// initialization of the destination structure
sDest.sin_family = AF_INET;
sDest.sin_port = htons(port);
sDest.sin_addr.s_addr = inet_addr(dest_ip);
int sizeSdest = sizeof(sDest); //Size of the receiving structure
// Sending the message
printf("Sending of the socket ...\n");
iResult = sendto(socket_id,message,strlen(message)+1, 0, (struct sockaddr *)&sDest, sizeof(sDest));
if (iResult != -1)
{
printf("Successful message sending.\n");
}
else
{
printf("Error n%d : Unable to send message.\n",errno);
//exit(errno);
return errno;
}
// Receiving the message
/* bind to receive address */
if (bind(socket_id, (struct sockaddr *)&sDest, sizeSdest) == 0) {
printf("bind: Ok.\n");
}
else
{
printf("Error n%d: bind.\n",errno);
//exit(errno);
return errno;
}
iResult = recvfrom(socket_id, msg_rcv, sizeof(msg_rcv), 0, (struct sockaddr *)&sDest, &sizeSdest);
msg_rcv[iResult]='\0'; // recvfrom renvoie le nombre d'octet lu!
if (iResult != -1)
{
printf("successful message reception.\n");
}
else
{
printf("Error n%d : Unable to receive message.\n",errno);
//exit(errno);
return errno;
}
// Display of the message without interference
printf("The message is : %s\n", msg_rcv);
//Closing the socket
if (closesocket(socket_id) == 0)
{
printf("Socket closing.\n");
}
else
{
printf("Error closing the socket.\n");
//exit(errno);
return errno;
}
return 0;
} |
Partager