summary |
shortlog |
log |
commit | commitdiff |
tree
raw |
patch |
inline | side by side (from parent 1:
9d32506)
gethostname(3) returns -1 on failure and that was being returned from
main; use 1 instead. getaddrinfo(3) returns EAI_ADDRFAMILY et al on
failure, but here they're defined as small negative integers, unsuitable
for main()'s return value; again, use 1 instead. Along the way, flip
the logic so the end is nigh when possible, avoiding the cognitive
overhead of tracking state when continuing to read through the source.
main(int argc, char *argv[])
{
char buf[_POSIX_HOST_NAME_MAX + 1];
main(int argc, char *argv[])
{
char buf[_POSIX_HOST_NAME_MAX + 1];
- const char *hostname = buf;
struct addrinfo hints, *res;
struct addrinfo hints, *res;
/* Borrowed the important code below from LocalName() in sbr/mts.c. */
/* Borrowed the important code below from LocalName() in sbr/mts.c. */
- if (argc < 2) {
- /* First get our local name. */
- status = gethostname(buf, sizeof buf);
- } else if (argc == 2) {
- hostname = argv[1];
- } else if (argc > 2) {
fprintf(stderr, "usage: %s [hostname]\n", argv[0]);
return 1;
}
fprintf(stderr, "usage: %s [hostname]\n", argv[0]);
return 1;
}
-
- if (status == 0) {
- /* Now fully qualify the hostname. */
- memset(&hints, 0, sizeof hints);
- hints.ai_flags = AI_CANONNAME;
- hints.ai_family = AF_UNSPEC;
-
- if ((status = getaddrinfo(hostname, NULL, &hints, &res)) == 0) {
- printf("%s\n", res->ai_canonname);
- freeaddrinfo(res);
- } else {
- printf("%s\n", hostname);
+ if (argc == 2)
+ hostname = argv[1];
+ else {
+ /* First get our local name. */
+ if (gethostname(buf, sizeof buf)) {
+ fprintf(stderr, "gethostname() failed: %s\n", strerror(errno));
+ return 1;
- } else {
- fprintf(stderr, "gethostname() failed: %s\n", strerror(errno));
+ hostname = buf;
+ }
+
+ /* Now fully qualify the hostname. */
+ memset(&hints, 0, sizeof hints);
+ hints.ai_flags = AI_CANONNAME;
+ hints.ai_family = AF_UNSPEC;
+
+ if (getaddrinfo(hostname, NULL, &hints, &res)) {
+ printf("%s\n", hostname);
+ return 1;
+ printf("%s\n", res->ai_canonname);