forked from remzi-arpacidusseau/ostep-code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
udp.c
67 lines (54 loc) · 1.76 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
#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 my_addr;
bzero(&my_addr, sizeof(my_addr));
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(port);
my_addr.sin_addr.s_addr = INADDR_ANY;
if (bind(fd, (struct sockaddr *) &my_addr, sizeof(my_addr)) == -1) {
perror("bind");
close(fd);
return -1;
}
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 *in_addr;
struct hostent *host_entry;
if ((host_entry = gethostbyname(hostname)) == NULL) {
perror("gethostbyname");
return -1;
}
in_addr = (struct in_addr *) host_entry->h_addr;
addr->sin_addr = *in_addr;
return 0;
}
int UDP_Write(int fd, struct sockaddr_in *addr, char *buffer, int n) {
int addr_len = sizeof(struct sockaddr_in);
int rc = sendto(fd, buffer, n, 0, (struct sockaddr *) addr, addr_len);
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);
}