util: Add helper to return name of address family

We have a few places where we want to include the name of the internet
protocol version (IPv4 or IPv6) in a message, which we handle with an
open-coded ?: expression.

This seems like something that might be more widely useful, so make a
trivial helper to return the correct string based on the address family.

Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
Signed-off-by: Stefano Brivio <sbrivio@redhat.com>
This commit is contained in:
David Gibson 2024-03-21 15:04:48 +11:00 committed by Stefano Brivio
parent f4e38b5cd2
commit 67a6258918
2 changed files with 21 additions and 3 deletions

View file

@ -309,7 +309,7 @@ unsigned int nl_get_ext_if(int s, sa_family_t af)
if (defifi) { if (defifi) {
if (ndef > 1) if (ndef > 1)
info("Multiple default %s routes, picked first", info("Multiple default %s routes, picked first",
af == AF_INET ? "IPv4" : "IPv6"); af_name(af));
return defifi; return defifi;
} }
@ -318,11 +318,11 @@ unsigned int nl_get_ext_if(int s, sa_family_t af)
return anyifi; return anyifi;
info("Multiple interfaces with %s routes, use -i to select one", info("Multiple interfaces with %s routes, use -i to select one",
af == AF_INET ? "IPv4" : "IPv6"); af_name(af));
} }
if (!nany) if (!nany)
info("No interfaces with %s routes", af == AF_INET ? "IPv4" : "IPv6"); info("No interfaces with %s routes", af_name(af));
return 0; return 0;
} }

18
util.h
View file

@ -156,6 +156,24 @@ int fls(unsigned long x);
int write_file(const char *path, const char *buf); int write_file(const char *path, const char *buf);
int write_remainder(int fd, const struct iovec *iov, int iovcnt, size_t skip); int write_remainder(int fd, const struct iovec *iov, int iovcnt, size_t skip);
/**
* af_name() - Return name of an address family
* @af: Address/protocol family (AF_INET or AF_INET6)
*
* Returns: Name of the protocol family as a string
*/
static inline const char *af_name(sa_family_t af)
{
switch (af) {
case AF_INET:
return "IPv4";
case AF_INET6:
return "IPv6";
default:
return "<unknown address family>";
}
}
/** /**
* mod_sub() - Modular arithmetic subtraction * mod_sub() - Modular arithmetic subtraction
* @a: Minued, unsigned value < @m * @a: Minued, unsigned value < @m