[PATCH 1/2] util: add wrapper function to check if address string is an ip

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



---
 src/util/network.c |   37 +++++++++++++++++++++++++++++++++++++
 src/util/network.h |    2 ++
 2 files changed, 39 insertions(+), 0 deletions(-)

diff --git a/src/util/network.c b/src/util/network.c
index 6e24792..2e0cf9c 100644
--- a/src/util/network.c
+++ b/src/util/network.c
@@ -54,6 +54,43 @@ static int getIPv6Addr(virSocketAddrPtr addr, virIPv6AddrPtr tab) {
 }
 
 /**
+ * virIsNumericIPAddr:
+ * @address: a text string containing a host name or IPv4/IPv6 address
+ *
+ * Given a text string, determines whether it contains a valid IPv4/IPv6
+ * address.
+ *
+ * Returns 0 if the given string is an IPv4 or IPv6 address, or non-zero
+ * for any other condition.
+ */
+int
+virIsNumericIPAddr(const char *address) {
+    int returnCode;
+    struct addrinfo hints;
+    struct addrinfo *res = NULL;
+
+    /* Sanity check we've been given a text string */
+    if (address == NULL)
+        return(-1);
+
+    /* Do a name lookup on the given string, and see what we're given back */
+    memset(&hints, 0, sizeof(hints));
+    hints.ai_family = AF_UNSPEC;     /* Doesn't matter whether IPv4 or IPv6 */
+    hints.ai_socktype = 0;           /* Socket type doesn't matter          */
+    hints.ai_flags = AI_NUMERICHOST; /* Force a numeric IP address check    */
+    hints.ai_protocol = 0;           /* Doesn't matter which protocol       */
+    returnCode = getaddrinfo (address, NULL, &hints, &res);
+    if (0 == returnCode) {
+        /* A result was returned.  This means the text string we were
+         * given is a valid IP address.  We now free the result(s) we
+         * were given, and pass back the return code */
+        freeaddrinfo(res);
+    }
+
+    return returnCode;
+}
+
+/**
  * virSocketParseAddr:
  * @val: a numeric network address IPv4 or IPv6
  * @addr: where to store the return value.
diff --git a/src/util/network.h b/src/util/network.h
index 5307c8c..c2e88d8 100644
--- a/src/util/network.h
+++ b/src/util/network.h
@@ -24,6 +24,8 @@ typedef union {
 } virSocketAddr;
 typedef virSocketAddr *virSocketAddrPtr;
 
+int virIsNumericIPAddr    (const char *address);
+
 int virSocketParseAddr    (const char *val,
                            virSocketAddrPtr addr,
                            int hint);
-- 
1.7.2.1

--
libvir-list mailing list
libvir-list@xxxxxxxxxx
https://www.redhat.com/mailman/listinfo/libvir-list


[Index of Archives]     [Virt Tools]     [Libvirt Users]     [Lib OS Info]     [Fedora Users]     [Fedora Desktop]     [Fedora SELinux]     [Big List of Linux Books]     [Yosemite News]     [KDE Users]     [Fedora Tools]