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
|
/*
author: sotech117
date: 9/25/2023
course: csci1680
description: listener for snowcast, a music streaming service
enjoy :)
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include "protocol.c"
main(int argc, char *argv[]) // no int here for good luck :)
{
// CHECK AND USE ARGUMENTS
// -------------------------------------------------------------------------------------------------
if (argc != 2) {
fprintf(stderr,"<udp port>\n");
exit(1);
}
// get the udp port
const char* udp_port = argv[1];
// GET UDP SOCKET
// -------------------------------------------------------------------------------------------------
int sockfd, err;
struct addrinfo hints, *servinfo, *p;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET; // set to AF_INET to use IPv4
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = AI_PASSIVE; // use my IP
if ((err = getaddrinfo(NULL, udp_port, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(err));
return 1;
}
// loop through all the results and bind to the first we can
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
perror("listener: socket");
continue;
}
if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
close(sockfd);
perror("listener: bind");
continue;
}
break;
}
if (p == NULL) {
fprintf(stderr, "listener: failed to bind socket\n");
return 2;
}
freeaddrinfo(servinfo);
// START READ/WRITE LOOP
// -------------------------------------------------------------------------------------------------
char buf[MAX_PACKET_SIZE]; // buffer for reading
struct sockaddr_storage their_addr; // connector's address information
socklen_t addr_len;
while(1) {
addr_len = sizeof their_addr;
int numbytes;
if ((numbytes = recvfrom(sockfd, buf, MAX_PACKET_SIZE , 0,
(struct sockaddr *)&their_addr, &addr_len)) == -1) {
perror("recvfrom");
exit(1);
}
// print the buffer
write(STDOUT_FILENO, buf, numbytes);
memset(buf, 0, MAX_PACKET_SIZE);
}
close(sockfd);
return 0;
}
|