-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtsserver.c
More file actions
86 lines (73 loc) · 2.05 KB
/
Copy pathtsserver.c
File metadata and controls
86 lines (73 loc) · 2.05 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
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
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "tslib.h"
#define BUFSIZE 1024
int main() {
socklen_t clientlen; /* byte size of client's address */
struct sockaddr_in serveraddr; /* server's addr */
struct sockaddr_in clientaddr; /* client addr */
char buf[BUFSIZE]; /* message buf */
ssize_t n; /* message byte size */
char *hostaddrp; /* dotted decimal host addr string */
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
perror("socket");
return 1;
}
int optval = 1;
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const void *)&optval , sizeof(int));
memset((char *) &serveraddr, 0, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
serveraddr.sin_port = htons(1981);
if (bind(sockfd, (struct sockaddr *) &serveraddr, sizeof(serveraddr)) < 0) {
perror("bind");
}
clientlen = sizeof(clientaddr);
while (1) {
memset(buf, 0, BUFSIZE);
n = recvfrom(sockfd, buf, BUFSIZE, 0, (struct sockaddr *) &clientaddr, &clientlen);
if (n < 0) {
perror("recvfrom");
return 1;
}
if( n != sizeof(timecmd_t)) {
printf("readed buffer broken got %zd need %zd\n", n, sizeof(timecmd_t));
}
hostaddrp = inet_ntoa(clientaddr.sin_addr);
if (hostaddrp == NULL) {
perror("inet_ntoa\n");
return 1;
}
printf("server received datagram from %s\n", hostaddrp);
timecmd_t *command = (timecmd_t *) &buf[0];
switch(command->cmd) {
case CMD_GETTIME: {
struct timeval tv;
printf("CMD_GETTIME\n");
gettimeofday(&tv, NULL);
command->version = 0;
command->sec = tv.tv_sec;
command->usec = tv.tv_usec;
timecmd_print(command);
}
break;
default:
printf("Unknown command\n");
break;
}
n = sendto(sockfd, buf, sizeof(timecmd_t), 0, (struct sockaddr *) &clientaddr, clientlen);
if (n < 0) {
perror("ERROR in sendto");
return 1;
}
}
return 0;
}