-
Notifications
You must be signed in to change notification settings - Fork 1
/
serverA.c
113 lines (87 loc) · 2.57 KB
/
serverA.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
/* Server A source code: 1 UDP socket
** This is a USC-EE450 Project
** Source code from: Socket Programming Reference - (Beej's-Guide)
*/
#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>
#define MYPORT "21831" // the port AWS will be connecting to
// get sockaddr, IPv4 or IPv6:
void *get_in_addr(struct sockaddr *sa)
{
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in*)sa)->sin_addr);
}
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
int main(void)
{
// UDP socket initialization: (from Beej's-Guide: listener.c)
int sockfd;
struct addrinfo hints, *servinfo, *p;
int rv;
int numbytes;
struct sockaddr_storage their_addr;
float buf;
float send[2];
socklen_t addr_len;
char s[INET6_ADDRSTRLEN];
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; // set to AF_INET to force IPv4
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = AI_PASSIVE; // use my IP
if ((rv = getaddrinfo(NULL, MYPORT, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
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);
printf("The Server A is up and running using UDP on port "MYPORT"\n");
//main loop:
//Receive input from AWS, calculate and send the result back to AWS.
while (1) {
// receive from AWS
addr_len = sizeof their_addr;
if ((numbytes = recvfrom(sockfd, &buf, 4 , 0, //wait for the incoming packets
(struct sockaddr *)&their_addr, &addr_len)) == -1) {
perror("recvfrom");
exit(1);
}
printf("The Server A received input <%g>\n", buf);
send[0] = buf * buf; // calculate x^2 here
send[1] = 2.0;
printf("The Server A calculated square: <%g>\n", send[0]);
// calculate and send result to aws
if ((numbytes = sendto(sockfd, &send, 8, 0, // send to UDP server, the address is assigned in getaddrinfo function above
(struct sockaddr *)&their_addr, addr_len)) == -1) {
perror("senderr: sendto");
exit(1);
}
printf("The Server A finished sending the output to AWS\n");
}
return 0;
}