inet_aton()返回无效IP地址的成功? [英] inet_aton() returning success for invalid ip addresses?
问题描述
但inet_aton()似乎很喜欢像11和1.1这样的字符串
什么是验证ipv4字符串的最佳方法。
#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> \\\
,argv [0]);
exit(EXIT_FAILURE);
if(inet_aton(argv [1],& addr)== 0){
fprintf(stderr,Invalid address \\\
);
exit(EXIT_FAILURE);
}
printf(%s\\\
,inet_ntoa(addr));
退出(EXIT_SUCCESS);
}
某些无效字符串的输出是
[root @〜]#./a.out 1.1
1.0.0.1
[root @〜]#./a.out 1某些垃圾
0.0.0.1
[root @〜]#./a.out10某些垃圾
0.0.0.10
我想要一个例程拒绝任何不以点分十进制表示的字符串
xxxx,x从0到255
这是 inet_aton
的指定/记录行为。
如果您只想接受点划十进制表示法,请使用:
unsigned char * a =(void * )& addr,dummy;
if(sscanf(src,%3hhd。%3hhd。%3hhd。%3hhd%c,a,a + 1,a + 2,a + 3,&dummy)!= 4){
/ * error * /
}
或者,您可以使用 inet_pton
函数,它在接受的格式中受到更多限制。
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
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.
这篇关于inet_aton()返回无效IP地址的成功?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!