-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtime_client.c
79 lines (62 loc) · 2.31 KB
/
time_client.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
/* time_client.c - main */
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#define BUFSIZE 64
#define MSG "Any Message \n"
/*------------------------------------------------------------------------
* main - UDP client for TIME service that prints the resulting time
*------------------------------------------------------------------------
*/
int
main(int argc, char **argv)
{
char *host = "localhost";
int port = 3000;
char now[100]; /* 32-bit integer to hold time */
struct hostent *phe; /* pointer to host information entry */
struct sockaddr_in sin; /* an Internet endpoint address */
int s, n, type; /* socket descriptor and socket type */
switch (argc) {
case 1:
break;
case 2:
host = argv[1];
case 3:
host = argv[1];
port = atoi(argv[2]);
break;
default:
fprintf(stderr, "usage: UDPtime [host [port]]\n");
exit(1);
}
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = htons(port);
/* Map host name to IP address, allowing for dotted decimal */
if ( phe = gethostbyname(host) ){
memcpy(&sin.sin_addr, phe->h_addr, phe->h_length);
}
else if ( (sin.sin_addr.s_addr = inet_addr(host)) == INADDR_NONE )
fprintf(stderr, "Can't get host entry \n");
/* Allocate a socket */
s = socket(AF_INET, SOCK_DGRAM, 0);
if (s < 0)
fprintf(stderr, "Can't create socket \n");
/* Connect the socket */
if (connect(s, (struct sockaddr *)&sin, sizeof(sin)) < 0)
fprintf(stderr, "Can't connect to %s %s \n", host, "Time");
(void) write(s, MSG, strlen(MSG));
/* Read the time */
n = read(s, (char *)&now, sizeof(now));
if (n < 0)
fprintf(stderr, "Read failed\n");
write(1, now, n);
exit(0);
}