-
Notifications
You must be signed in to change notification settings - Fork 0
/
udp.h
61 lines (49 loc) · 1.39 KB
/
udp.h
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
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <stdlib.h>
#include <arpa/inet.h>
#define MAX_BUFFER 1024
/**
* @returns the sockaddr_in struct object associated with the port (at localhose)
*/
struct sockaddr_in getAddr(int port) {
struct sockaddr_in serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(port);
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero);
return serverAddr;
}
/**
* @returns socket to listen to if no error returns -1 if there was an error
*/
int initialise_listener(int listenport) {
int udpSocket;
struct sockaddr_in serverAddr;
udpSocket = socket(PF_INET, SOCK_DGRAM, 0);
serverAddr = getAddr(listenport);
if(bind(udpSocket, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0) {
return -1;
}
return udpSocket;
}
/**
* Usage of the functions
* nBytes = recvfrom(udpSocket,buffer,1024,0,NULL, NULL);
* sendto(clientSocket,buffer,nBytes,MSG_NOSIGNAL,(struct sockaddr*)&addr,(socklen_t)sizeof(addr));
*
*/
/**
* @returns -1: error, 0: timeout, 1: fd is ready
*/
int isSocketReady(int fd,int usec) {
struct timeval tv;
fd_set f_set;
FD_ZERO(&f_set);
FD_SET(fd, &f_set);
tv.tv_sec = 0;
tv.tv_usec = usec;
return select(fd+1, &f_set, NULL, NULL, &tv);
}