ipaddr

print the IP address of the selected interface
git clone git://git.sgregoratto.me/ipaddr
Log | Files | Refs

commit b724ef9c7360cbe63727ac4b90bd52500af1393d
parent 013cb6ba880648933e4bf42c8aebb088e532fb65
Author: Stephen Gregoratto <dev@sgregoratto.me>
Date:   Thu, 31 Oct 2019 21:10:21 +1100

improve option handling, memory usage and semantics.

- Refactor the option handling to add a help flag and keep it to 2
  levels of indentation.
- Don't duplicate the interface string.
- Rename ifa to iter, since we use it to iterate over the interfaces.

Diffstat:
Mipaddr.c | 52+++++++++++++++++++++++++---------------------------
1 file changed, 25 insertions(+), 27 deletions(-)

diff --git a/ipaddr.c b/ipaddr.c @@ -18,11 +18,10 @@ int main(int argc, char **argv) { - struct ifaddrs *ifaddr, *ifa; - int status; - char host[NI_MAXHOST]; - char *iface; + struct ifaddrs *ifaddr, *iter; size_t sa_size; + int status; + char host[NI_MAXHOST + 1], *iface; #if HAVE_PLEDGE if (pledge("stdio") == -1) @@ -35,47 +34,46 @@ main(int argc, char **argv) goto usage; } - if (argv[1][0] == '-') { - switch (argv[1][1]) { - case '4': - sa_size = sizeof(struct sockaddr_in); - break; - case '6': - sa_size = sizeof(struct sockaddr_in6); - break; - default: - warnx("invalid IP version"); - goto usage; - } - } else { - warnx("invalid IP version"); + if (argv[1][0] != '-') { + warnx("invalid argument"); + goto usage; + } + + switch (argv[1][1]) { + case '4': + sa_size = sizeof(struct sockaddr_in); + break; + case '6': + sa_size = sizeof(struct sockaddr_in6); + break; + default: + warnx("invalid argument"); + case 'h': goto usage; } - if ((iface = strdup(argv[2])) == NULL) - err(1, "strdup"); + iface = argv[2]; if (getifaddrs(&ifaddr) == -1) err(1, "getifaddrs"); - for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) { - if (ifa->ifa_addr == NULL) + for (iter = ifaddr; iter != NULL; iter = iter->ifa_next) { + if (iter->ifa_addr == NULL) continue; - status = getnameinfo(ifa->ifa_addr, sa_size, host, NI_MAXHOST, + status = getnameinfo(iter->ifa_addr, sa_size, host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST); - if ((strncmp(ifa->ifa_name, iface, strlen(iface)) == 0) - && (ifa->ifa_addr->sa_family == AF_INET)) { + if ((strncmp(iter->ifa_name, iface, strlen(iface)) == 0) + && (iter->ifa_addr->sa_family == AF_INET)) { if (status != 0) errx(1, "getnameinfo: %s", gai_strerror(status)); - printf("%s %s\n", ifa->ifa_name, host); + printf("%s %s\n", iter->ifa_name, host); break; } } - free(iface); freeifaddrs(ifaddr); return 0;