xref: /freebsd/contrib/ntp/libntp/numtoa.c (revision 734e82fe33aa764367791a7d603b383996c6b40b)
1 /*
2  * numtoa - return asciized network numbers store in local array space
3  */
4 #include <config.h>
5 
6 #include <sys/types.h>
7 #ifdef HAVE_NETINET_IN_H
8 #include <netinet/in.h>		/* ntohl */
9 #endif
10 
11 #include <stdio.h>
12 #include <ctype.h>
13 
14 #include "ntp_fp.h"
15 #include "lib_strbuf.h"
16 #include "ntp_stdlib.h"
17 
18 char *
19 numtoa(
20 	u_int32 num
21 	)
22 {
23 	register u_int32 netnum;
24 	register char *buf;
25 
26 	netnum = ntohl(num);
27 	LIB_GETBUF(buf);
28 	snprintf(buf, LIB_BUFLENGTH, "%lu.%lu.%lu.%lu",
29 		 ((u_long)netnum >> 24) & 0xff,
30 		 ((u_long)netnum >> 16) & 0xff,
31 		 ((u_long)netnum >> 8) & 0xff,
32 		 (u_long)netnum & 0xff);
33 	return buf;
34 }
35 
36 
37 /* Convert a refid & stratum to a string */
38 const char *
39 refid_str(
40 	u_int32	refid,
41 	int	stratum
42 	)
43 {
44 	char *	text;
45 	size_t	tlen;
46 	char *  cp;
47 
48 	if (stratum > 1)
49 		return numtoa(refid);
50 
51 	LIB_GETBUF(text);
52 	text[0] = '.';
53 	/* What if any non-NUL char is not printable? */
54 	memcpy(&text[1], &refid, sizeof(refid));
55 	text[1 + sizeof(refid)] = '\0';
56 	tlen = strlen(text);
57 	text[tlen] = '.';
58 	text[tlen + 1] = '\0';
59 
60 	/*
61 	 * Now make sure the contents are 'graphic'.
62 	 *
63 	 * This refid is expected to be up to 4 ascii graphics.
64 	 * If any character is not a graphic, replace it with a space.
65 	 * This will at least alert the viewer of a problem.
66 	 */
67 	for (cp = text + 1; *cp; ++cp) {
68 		if (!isgraph((int)*cp)) {
69 			*cp = ' ';
70 		}
71 	}
72 
73 	return text;
74 }
75 
76