-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathradio.c
117 lines (85 loc) · 2.5 KB
/
radio.c
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
113
114
115
116
/*
* radio.c
*
* Emulation of radio node using UDP (skeleton)
*/
// Implements
#include "radio.h"
// Uses
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
int sock, recv_len, s_len; // UDP Socket used by this node
#define FRAME_PAYLOAD_SIZE 188
void die(char *s)
{
perror(s);
exit(1);
}
int radio_init(int addr) {
struct sockaddr_in sa; // Structure to set own address
s_len=sizeof(sa);
// Check validity of address
if(1024 > addr || addr > 49151){
printf("%s\n", "Wrong address, must be 1024 to 49151!");
exit(0);
}
// Create UDP socket
if((sock =socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1){
die("Socket");
}
// Prepare address structure
memset((char *) &sa, 0, s_len);
sa.sin_family = AF_INET;
sa.sin_port = htons(addr);
sa.sin_addr.s_addr = htonl(INADDR_ANY);
// Bind socket to port
if((bind(sock , (struct sockaddr*)&sa, s_len)) == -1){
die("Bind");
}
return ERR_OK;
}
int radio_send(int dst, char* data, int len) {
struct sockaddr_in sa; // Structure to hold destination address
// Check that port and len are valid
if(1024 > dst || dst > 49151){
printf("%s\n", "Wrong address, must be 1024 to 49151!");
exit(0);
}
if(FRAME_PAYLOAD_SIZE < len){
printf("%s\n", "Data size is too big, must be blow %d!", FRAME_PAYLOAD_SIZE);
exit(1);
}
// Emulate transmission time
// Prepare address structure
memset((char *) &sa, 0, sizeof(sa));
sa.sin_family = AF_INET;
sa.sin_port = htons(dst);
/*if (inet_aton(SERVER , &sa.sin_addr) == 0)
{
printf("ERROR!!!!\n");
}*/
//sa.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
// Send the message
if(sendto(sock, data, len , 0 , (struct sockaddr *) &sa, sizeof(sa)) == -1){
die("sendto");
}
// Check if fully sent
return ERR_OK;
}
int radio_recv(int* src, char* data, int to_ms) {
//exit(-1);
struct sockaddr_in sa; // Structure to receive source address
int len = -1; // Size of received packet (or error code)
// First poll/select with timeout (may be skipped at first)
// Receive packet/data
if(len = recvfrom(sock, data, FRAME_PAYLOAD_SIZE, 0, (struct sockaddr *) &sa, &s_len) == -1){
die("recvfrom");
}
// Set source from address structure
// *src = ntohs(sa.sin_port);
return len;
}