diff --git a/opal/util/net.c b/opal/util/net.c index 6b9ccf4504..71b3f4b5d3 100644 --- a/opal/util/net.c +++ b/opal/util/net.c @@ -78,6 +78,37 @@ #include "opal/threads/tsd.h" #include "opal/mca/base/mca_base_param.h" +/* this function doesn't depend on sockaddr_h */ +bool opal_net_isaddr(const char *name) +{ + unsigned int groups[8]; + int i; + + if (4 != sscanf(name, "%u.%u.%u.%u", + &groups[0], &groups[1], &groups[2], &groups[3])) { + /* this isn't an IPv4 address */ + goto checkipv6; + } + + for (i=0; i < 4; i++) { + if (255 < groups[i]) { + return false; + } + } + return true; + + checkipv6: + /* TODO: deal with all the shorthand notations for IPv6! */ + if (8 != sscanf(name, "%x:%x:%x:%x:%x:%x:%x:%x", + &groups[0], &groups[1], &groups[2], &groups[3], + &groups[4], &groups[5], &groups[6], &groups[7])) { + /* this isn't an IPv6 address */ + return false; + } + /* there are no value limits on the individual groups */ + return true; +} + #ifdef HAVE_STRUCT_SOCKADDR_IN typedef struct private_ipv4_t { diff --git a/opal/util/net.h b/opal/util/net.h index c1ec888610..2355cdf2bb 100644 --- a/opal/util/net.h +++ b/opal/util/net.h @@ -137,6 +137,13 @@ OPAL_DECLSPEC char* opal_net_get_hostname(const struct sockaddr *addr); */ OPAL_DECLSPEC int opal_net_get_port(const struct sockaddr *addr); +/** + * Test if a string is actually an IP address + * + * Returns true if the string is of IPv4 or IPv6 address form + */ +OPAL_DECLSPEC bool opal_net_isaddr(const char *name); + END_C_DECLS #endif /* OPAL_UTIL_NET_H */