inet_aton() returning success for invalid ip addresses?

I am looking for some function to verify that if given string is a valid ipv4 address, but inet_aton() seems to be happy with strings like "11" and "1.1" what is best way to validate an ipv4 string.

#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>

int
main(int argc, char *argv[])
{
    struct in_addr addr;

   if (argc != 2) {
        fprintf(stderr, "%s <dotted-address>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

   if (inet_aton(argv[1], &addr) == 0) {
        fprintf(stderr, "Invalid address\n");
        exit(EXIT_FAILURE);
    }

   printf("%s\n", inet_ntoa(addr));
    exit(EXIT_SUCCESS);
}

the ouput for some invalid strings are

[root@ ~]# ./a.out 1.1
1.0.0.1
[root@ ~]# ./a.out "1 some junk"
0.0.0.1
[root@ ~]# ./a.out "10 some junk"
0.0.0.10

I want a routine to reject any string not in dotted decimal notation x.x.x.x, x from 0 to 255

Answers


This is the specified/documented behavior for inet_aton.

If you want to accept only dotted-quad decimal notation, use:

unsigned char *a = (void *)&addr, dummy;
if (sscanf(src, "%3hhd.%3hhd.%3hhd.%3hhd%c", a, a+1, a+2, a+3, &dummy)!=4) {
    /* error */
}

Alternatively, you might use the inet_pton function, which is more restrictive in the formats it accepts.


Need Your Help

How do I do a negative / nomatch / inverse search in data.table?

r select data.table

What happens if I want to select all the rows in a data.table that do not contain a particular value in the key variable using binary search? By the way, what is the correct jargon for what I want ...

Parsing a CAD or BIM file and fetching/exporting the 'Layer Name'

cad step

Sound-byte Question: How easy or difficult is it to parse a CAD/BIM file and return(export) just the names of those 'Layers, Sheets, or Worksets' contained within?