-
Notifications
You must be signed in to change notification settings - Fork 0
/
udp.c
executable file
·80 lines (66 loc) · 1.78 KB
/
udp.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
#include "udp.h"
// create a socket and bind it to a port on the current machine
// used to listen for incoming packets
int
UDP_Open(int port)
{
int fd;
if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
perror("socket");
return 0;
}
// set up the bind
struct sockaddr_in myaddr;
bzero(&myaddr, sizeof(myaddr));
myaddr.sin_family = AF_INET;
myaddr.sin_port = htons(port);
myaddr.sin_addr.s_addr = INADDR_ANY;
if (bind(fd, (struct sockaddr *) &myaddr, sizeof(myaddr)) == -1) {
perror("bind");
close(fd);
return -1;
}
// give back descriptor
return fd;
}
// fill sockaddr_in struct with proper goodies
int
UDP_FillSockAddr(struct sockaddr_in *addr, char *hostName, int port)
{
bzero(addr, sizeof(struct sockaddr_in));
if (hostName == NULL) {
return 0; // it's OK just to clear the address
}
addr->sin_family = AF_INET; // host byte order
addr->sin_port = htons(port); // short, network byte order
struct in_addr *inAddr;
struct hostent *hostEntry;
if ((hostEntry = gethostbyname(hostName)) == NULL) {
perror("gethostbyname");
return -1;
}
inAddr = (struct in_addr *) hostEntry->h_addr;
addr->sin_addr = *inAddr;
// all is good
return 0;
}
int
UDP_Write(int fd, struct sockaddr_in *addr, char *buffer, int n)
{
int addrLen = sizeof(struct sockaddr_in);
int rc = sendto(fd, buffer, n, 0, (struct sockaddr *) addr, addrLen);
return rc;
}
int
UDP_Read(int fd, struct sockaddr_in *addr, char *buffer, int n)
{
int len = sizeof(struct sockaddr_in);
int rc = recvfrom(fd, buffer, n, 0, (struct sockaddr *) addr, (socklen_t *) &len);
// assert(len == sizeof(struct sockaddr_in));
return rc;
}
int
UDP_Close(int fd)
{
return close(fd);
}