-
Notifications
You must be signed in to change notification settings - Fork 7
/
udp_server.c
87 lines (74 loc) · 1.87 KB
/
udp_server.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
#include <stdio.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <ctype.h>
#include <stdlib.h>
#include "wrap.h"
#define MAXLINE 80
void do_something_for_client(char *buf, int bytes)
{
int i;
for (i = 0; i < bytes; i++)
{
#ifdef DEBUG
printf("%c\t", buf[i]);
#endif
buf[i] = toupper(buf[i]);
}
fflush(stdout);
}
/*
* Usage :
* ./udp_server <port>
*/
int main(int argc, char *argv[])
{
struct sockaddr_in server_addr, client_addr;
socklen_t client_addr_len;
char buf[MAXLINE];
char str[INET_ADDRSTRLEN];
int bytes;
int sock_fd;
int optval = 1;
if (argc != 2)
{
fprintf(stderr, "%s <port>\n", argv[0]);
exit(1);
}
/*
* AF_INET for IPv4
* SOCK_DGRAM for UDP
* protocol : 0
*/
sock_fd = Socket(AF_INET, SOCK_DGRAM, 0);
/* set reuse address option */
if (setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)) < 0)
{
perror("setsockoption error");
return -1;
}
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(atoi(argv[1]));
/* bind fd and address (fixed address) */
Bind(sock_fd, (struct sockaddr *)&server_addr, sizeof(server_addr));
printf("Accepting connecting...\n");
while (1)
{
/* recv client requst */
client_addr_len = sizeof(client_addr);
bytes = recvfrom(sock_fd, buf, MAXLINE, 0, (struct sockaddr*)&client_addr, &client_addr_len);
if (bytes == -1)
perror("recvform error");
printf("recv %d bytes from %s at port %d\n", bytes, inet_ntop(AF_INET, &client_addr.sin_addr, str, sizeof(str)), ntohs(client_addr.sin_port));
/* do something for client */
do_something_for_client(buf, bytes);
/* answer client request */
bytes = sendto(sock_fd, buf, bytes, 0, (struct sockaddr*)&client_addr, sizeof(client_addr));
if (bytes == -1)
perror("Send to error");
}
return 0;
}