]> git.ipfire.org Git - people/ms/libloc.git/blobdiff - src/libloc.c
database: Implement lookup
[people/ms/libloc.git] / src / libloc.c
index 8b8872c404da93571bab75ea25e95b5428a65dd0..630a4d5c8c7d414ba46a708d766d31e72db58a5b 100644 (file)
@@ -14,6 +14,8 @@
        Lesser General Public License for more details.
 */
 
+#include <arpa/inet.h>
+#include <netinet/in.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <stddef.h>
@@ -156,3 +158,34 @@ LOC_EXPORT int loc_load(struct loc_ctx* ctx, const char* path) {
 
        return 0;
 }
+
+LOC_EXPORT int loc_parse_address(struct loc_ctx* ctx, const char* string, struct in6_addr* address) {
+       DEBUG(ctx, "Paring IP address %s\n", string);
+
+       // Try parsing this as an IPv6 address
+       int r = inet_pton(AF_INET6, string, address);
+
+       // If inet_pton returns one it has been successful
+       if (r == 1) {
+               DEBUG(ctx, "%s is an IPv6 address\n", string);
+               return 0;
+       }
+
+       // Try parsing this as an IPv4 address
+       struct in_addr ipv4_address;
+       r = inet_pton(AF_INET, string, &ipv4_address);
+       if (r == 1) {
+               DEBUG(ctx, "%s is an IPv4 address\n", string);
+
+               // Convert to IPv6-mapped address
+               address->s6_addr32[0] = htonl(0x0000);
+               address->s6_addr32[1] = htonl(0x0000);
+               address->s6_addr32[2] = htonl(0xffff);
+               address->s6_addr32[3] = ipv4_address.s_addr;
+
+               return 0;
+       }
+
+       DEBUG(ctx, "%s is not an valid IP address\n", string);
+       return 1;
+}