This repository was archived by the owner on Feb 3, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathudpserver.c
More file actions
56 lines (47 loc) · 1.26 KB
/
udpserver.c
File metadata and controls
56 lines (47 loc) · 1.26 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
53
54
55
56
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#define SERV_PORT 20001
#define BUFSIZE 1024
#define SADDR struct sockaddr
#define SLEN sizeof(struct sockaddr_in)
int main() {
int sockfd, n;
char mesg[BUFSIZE], ipadr[16];
struct sockaddr_in servaddr;
struct sockaddr_in cliaddr;
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
perror("socket problem");
exit(1);
}
memset(&servaddr, 0, SLEN);
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(SERV_PORT);
if (bind(sockfd, (SADDR *)&servaddr, SLEN) < 0) {
perror("bind problem");
exit(1);
}
printf("SERVER starts...\n");
while (1) {
unsigned int len = SLEN;
if ((n = recvfrom(sockfd, mesg, BUFSIZE, 0, (SADDR *)&cliaddr, &len)) < 0) {
perror("recvfrom");
exit(1);
}
mesg[n] = 0;
printf("REQUEST %s FROM %s : %d\n", mesg,
inet_ntop(AF_INET, (void *)&cliaddr.sin_addr.s_addr, ipadr, 16),
ntohs(cliaddr.sin_port));
if (sendto(sockfd, mesg, n, 0, (SADDR *)&cliaddr, len) < 0) {
perror("sendto");
exit(1);
}
}
}