1 /* Copyright (C) 1996 N.M. Maclaren
2 Copyright (C) 1996 The University of Cambridge
4 This includes all of the code needed to handle Internet addressing. It is way
5 outside current POSIX, unfortunately. It should be easy to convert to a system
6 that uses another mechanism. The signal handling is not necessary for its
7 function, but is an attempt to avoid the program hanging when the name server
16 #include <arpa/inet.h>
24 /* There needs to be some disgusting grobble for handling timeouts, which is
25 identical to the grobble in socket.c. */
27 static jmp_buf jump_buffer;
29 static void jump_handler (int sig) {
30 longjmp(jump_buffer,1);
33 static void clear_alarm (void) {
39 if (signal(SIGALRM,SIG_DFL) == SIG_ERR)
40 fatal(1,"unable to reset signal handler",NULL);
46 void find_address (struct in_addr *address, struct in_addr *anywhere,
47 struct in_addr *everywhere, int *port, char *hostname, int timespan) {
49 /* Locate the specified NTP server and return its Internet address and port
52 struct in_addr nowhere[1];
54 struct servent *service;
56 /* Set up the reserved Internet addresses, attempting not to assume that
57 addresses are 32 bits. */
59 local_to_address(nowhere,INADDR_LOOPBACK);
60 local_to_address(anywhere,INADDR_ANY);
61 local_to_address(everywhere,INADDR_BROADCAST);
63 /* Check the address, if any. This assumes that the DNS is reliable, or is at
64 least checked by someone else. But it doesn't assume that it is accessible, so
65 it needs to set up a timeout. */
70 if (setjmp(jump_buffer))
71 fatal(0,"unable to set up access to NTP server %s",hostname);
73 if (signal(SIGALRM,jump_handler) == SIG_ERR)
74 fatal(1,"unable to set up signal handler",NULL);
75 alarm((unsigned int)timespan);
77 /* Look up the Internet name or IP number. */
79 host = gethostbyname(hostname);
81 /* Now clear the timer and check the result. */
84 if (host == NULL) fatal(1,"unable to locate IP address/number: %s", hostname);
85 if (host->h_length != sizeof(struct in_addr))
86 fatal(0,"the address does not seem to be an Internet one: %s", hostname);
87 *address = *((struct in_addr **)host->h_addr_list)[0];
88 if (memcmp(address,nowhere,sizeof(struct in_addr)) == 0 ||
89 memcmp(address,anywhere,sizeof(struct in_addr)) == 0 ||
90 memcmp(address,everywhere,sizeof(struct in_addr)) == 0)
91 fatal(0,"reserved IP numbers cannot be used",NULL);
94 "%s: using NTP server %s (%s)\n",
95 argv0,host->h_name,inet_ntoa(*address));
98 /* Find out the port number (usually from /etc/services), and leave it in
99 network format. This is assumed not to be obtained from a network service!
100 Note that a port number is not assumed to be 16 bits. */
102 if ((service = getservbyname("ntp","udp")) != NULL) {
103 *port = service->s_port;
105 fprintf(stderr,"Using port %d for NTP\n",port_to_integer(*port));
110 "%s: assuming port %d for NTP - check /etc/services\n",
111 argv0,port_to_integer(*port));