]> git.ipfire.org Git - people/ms/libloc.git/commitdiff
network: Allow adding single IP addresses and automatically add the prefix
authorMichael Tremer <michael.tremer@ipfire.org>
Thu, 22 Oct 2020 12:24:34 +0000 (12:24 +0000)
committerMichael Tremer <michael.tremer@ipfire.org>
Thu, 22 Oct 2020 12:24:34 +0000 (12:24 +0000)
Signed-off-by: Michael Tremer <michael.tremer@ipfire.org>
src/network.c
src/test-network.c

index be88d758da62aae1f336d4b6fe7f244bab667107..d7b16456b24a12c10880d71b4d3e77b8097dfb25 100644 (file)
@@ -161,6 +161,7 @@ LOC_EXPORT int loc_network_new_from_string(struct loc_ctx* ctx, struct loc_netwo
                const char* address_string) {
        struct in6_addr first_address;
        char* prefix_string;
+       unsigned int prefix = 128;
        int r = -EINVAL;
 
        DEBUG(ctx, "Attempting to parse network %s\n", address_string);
@@ -174,21 +175,6 @@ LOC_EXPORT int loc_network_new_from_string(struct loc_ctx* ctx, struct loc_netwo
 
        DEBUG(ctx, "  Split into address = %s, prefix = %s\n", address_string, prefix_string);
 
-       // We need to have a prefix
-       if (!prefix_string) {
-               DEBUG(ctx, "No prefix set\n");
-               goto FAIL;
-       }
-
-       // Convert prefix to integer
-       unsigned int prefix = strtol(prefix_string, NULL, 10);
-
-       // End if the prefix was invalid
-       if (!prefix) {
-               DEBUG(ctx, "The prefix is zero or not a number\n");
-               goto FAIL;
-       }
-
        // Parse the address
        r = loc_parse_address(ctx, address_string, &first_address);
        if (r) {
@@ -196,9 +182,20 @@ LOC_EXPORT int loc_network_new_from_string(struct loc_ctx* ctx, struct loc_netwo
                goto FAIL;
        }
 
-       // Map the prefix to IPv6 if needed
-       if (IN6_IS_ADDR_V4MAPPED(&first_address))
-               prefix += 96;
+       // If a prefix was given, we will try to parse it
+       if (prefix_string) {
+               // Convert prefix to integer
+               prefix = strtol(prefix_string, NULL, 10);
+
+               if (!prefix) {
+                       DEBUG(ctx, "The prefix was not parsable: %s\n", prefix_string);
+                       goto FAIL;
+               }
+
+               // Map the prefix to IPv6 if needed
+               if (IN6_IS_ADDR_V4MAPPED(&first_address))
+                       prefix += 96;
+       }
 
 FAIL:
        // Free temporary buffer
index 8c7e898f49a69a3ab8bedc19bf85e936217b1e4d..b6776b48be914f6ca75051f63905d93462bd3161 100644 (file)
@@ -170,8 +170,8 @@ int main(int argc, char** argv) {
 
        // Try adding a single address
        err = loc_writer_add_network(writer, &network, "2001:db8::");
-       if (err != -EINVAL) {
-               fprintf(stderr, "It was possible to add an invalid network (err = %d)\n", err);
+       if (err) {
+               fprintf(stderr, "It was impossible to add an single IP address (err = %d)\n", err);
                exit(EXIT_FAILURE);
        }