Reputation: 47
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
Upvotes: 2
Views: 2628
Reputation: 215221
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.
Upvotes: 3