xref: /original-bsd/bin/hostname/hostname.c (revision 682c554c)
1 /*
2  * Copyright (c) 1988, 1993 Regents of the University of California.
3  * All rights reserved.
4  *
5  * %sccs.include.redist.c%
6  */
7 
8 #ifndef lint
9 char copyright[] =
10 "@(#) Copyright (c) 1988, 1993 Regents of the University of California.\n\
11  All rights reserved.\n";
12 #endif /* not lint */
13 
14 #ifndef lint
15 static char sccsid[] = "@(#)hostname.c	5.5 (Berkeley) 04/29/93";
16 #endif /* not lint */
17 
18 #include <sys/param.h>
19 
20 #include <err.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <unistd.h>
25 
26 int
27 main(argc,argv)
28 	int argc;
29 	char *argv[];
30 {
31 	extern int optind;
32 	int ch, sflag;
33 	char *p, hostname[MAXHOSTNAMELEN];
34 
35 	sflag = 0;
36 	while ((ch = getopt(argc, argv, "s")) != EOF)
37 		switch (ch) {
38 		case 's':
39 			sflag = 1;
40 			break;
41 		case '?':
42 		default:
43 			(void)fprintf(stderr,
44 			    "usage: hostname [-s] [hostname]\n");
45 			exit(1);
46 		}
47 	argc -= optind;
48 	argv += optind;
49 
50 	if (*argv) {
51 		if (sethostname(*argv, strlen(*argv)))
52 			err(1, "sethostname");
53 	} else {
54 		if (gethostname(hostname, sizeof(hostname)))
55 			err(1, "gethostname");
56 		if (sflag && (p = strchr(hostname, '.')))
57 			*p = '\0';
58 		(void)printf("%s\n", hostname);
59 	}
60 	exit(0);
61 }
62