Use sysconf() instead of HOST_NAME_MAX

This commit is contained in:
sin 2014-02-14 15:01:15 +00:00
parent 7309302e25
commit efbce07f94
1 changed files with 14 additions and 3 deletions

View File

@ -15,7 +15,16 @@ usage(void)
int int
main(int argc, char *argv[]) main(int argc, char *argv[])
{ {
char host[HOST_NAME_MAX + 1]; long sz;
char *host;
sz = sysconf(_SC_HOST_NAME_MAX);
if (sz < 0)
sz = 255;
host = malloc(sz + 1);
if (!host)
eprintf("malloc:");
ARGBEGIN { ARGBEGIN {
default: default:
@ -23,13 +32,15 @@ main(int argc, char *argv[])
} ARGEND; } ARGEND;
if (argc < 1) { if (argc < 1) {
if (gethostname(host, sizeof(host)) < 0) if (gethostname(host, sz + 1) < 0)
eprintf("gethostname:"); eprintf("gethostname:");
puts(host); puts(host);
} else { } else {
if (sethostname(argv[0], strlen(argv[0])) < 0) if (sethostname(argv[0], sz + 1) < 0)
eprintf("sethostname:"); eprintf("sethostname:");
} }
free(host);
return EXIT_SUCCESS; return EXIT_SUCCESS;
} }