main.c
2.83 KB
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
#include <stdio.h>
#include <string.h> // pour strlen()
#include <stdlib.h> // pour exit()
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/udp.h>
#include <arpa/inet.h>
//Fonction permettant d'envoyer un message en broadcast
void sendUDPBroadcast(unsigned char *message, int taille_message, int port) {
int broadcast_enable = 1;
//Option broadcast ON
int s = socket(AF_INET, SOCK_DGRAM, 0);
//Création de la socket : s = file descriptor de la socket, AF_INET (socket internet), SOCK_DGRAM (datagramme, UDP, sans connexion)
if(s < 0){
//Test de la valeur de retour de la socket
perror("sendUDPBroadcast.socket");
exit(-1);
}
if (setsockopt(s, SOL_SOCKET, SO_BROADCAST, &broadcast_enable, sizeof(broadcast_enable)) < 0) {
//Mise option broadcast à la socket
perror("sendUDPBroadcast.setsockopt");
exit(-1);
}
struct sockaddr_in broadcast_address;
memset(&broadcast_address, 0, sizeof(broadcast_address));
broadcast_address.sin_family = AF_INET;
broadcast_address.sin_port = htons(port);
broadcast_address.sin_addr.s_addr = INADDR_BROADCAST; //255.255.255.255
//Envoie du message grâce à la socket
if(sendto(s, message, taille_message, 0, (struct sockaddr *) &broadcast_address,
sizeof(broadcast_address)) < 0 ) {
perror("sendUDPBroadcast.sendto");
exit(-1);
}
}
//Fonction permettant d'envoyer un message à une adresse
void sendUDPUnicast(char *address, unsigned char *message, int taille_message, int port) {
int s = socket(AF_INET, SOCK_DGRAM, 0);
//Création de la socket : s = file descriptor de la socket, AF_INET (socket internet), SOCK_DGRAM (datagramme, UDP, sans connexion)
if(s < 0){
//Test de la valeur de retour de la socket
perror("sendUDPUnicast.socket");
exit(-1);
}
struct sockaddr_in unicast_address;
//Creation structure adresse de destination
memset(&unicast_address, 0, sizeof(unicast_address));
//Mise à zéro de la structure d'adresse
unicast_address.sin_family = AF_INET;
unicast_address.sin_port = htons(port);
//Mise du port en ordre du réseau (big endian)
unicast_address.sin_addr.s_addr = inet_addr(address);
if(sendto(s, message, taille_message, 0, (struct sockaddr *) &unicast_address, sizeof(unicast_address)) < 0 ) {
perror("sendUDPUnicast.sendto");
exit(-1);
}
}
int main(void){
unsigned char message_broadcast[100] = "J'envoie en UDP boradcast";
unsigned char message_unicast[100] = "J'envoie en UDP unicast";
// send broadcast
sendUDPBroadcast(message_broadcast, strlen(message_broadcast), 2030);
// send unicast
char adresse[50] = "127.0.0.1";
sendUDPUnicast(adresse, message_unicast, strlen(message_unicast), 2030);
return 0;
}