-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsample_server.c
More file actions
52 lines (40 loc) · 1.61 KB
/
sample_server.c
File metadata and controls
52 lines (40 loc) · 1.61 KB
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
#include <stdio.h>
#include <stdlib.h>
#include "udp.h"
int main(int argc, char *argv[])
{
// This function opens a UDP socket,
// binding it to all IP interfaces of this machine,
// and port number SERVER_PORT
// (See details of the function in udp.h)
int sd = udp_socket_open(SERVER_PORT);
assert(sd > -1);
// Server main loop
while (1)
{
// Storage for request and response messages
char client_request[BUFFER_SIZE], server_response[BUFFER_SIZE];
// Demo code (remove later)
//printf("Server is listening on port %d\n", SERVER_PORT);
// Variable to store incoming client's IP address and port
struct sockaddr_in client_address;
// This function reads incoming client request from
// the socket at sd.
// (See details of the function in udp.h)
int rc = udp_socket_read(sd, &client_address, client_request, BUFFER_SIZE);
// Successfully received an incoming request
if (rc > 0)
{
// Demo code: send a SAY command back to client
strcpy(server_response, "say$ Server received your message!");
// This function writes back to the incoming client,
// whose address is now available in client_address,
// through the socket at sd.
// (See details of the function in udp.h)
rc = udp_socket_write(sd, &client_address, server_response, BUFFER_SIZE);
// Demo code (remove later)
//printf("Request served...\n");
}
}
return 0;
}