代码可以通过文件查找 ddd.ddd.ddd.ddd 模式。
避免使用"%d"
or"%u"
因为它们接受前导空格,and'-'
和'+'
.
伪代码
Read from a file until EOF found
repeatedly look for a digit
if it is found
note position
put digit back into stream
look for ddd.ddd.ddd.ddd
if found
decode (and test for values > 255)
if successful return result
go back to position
return fail value;
示例代码。还应该有 IO 错误检查。
unsigned long Parse_IP(FILE *inf) {
int ch;
for ((ch = fgetc(inf)) != EOF) {
if (isdigit(ch)) {
long pos = ftell(inf);
ungetc(ch, inf);
char buf[4][4];
int count = fscanf(inf, "%3[0-9].%3[0-9].%3[0-9].%3[0-9]",
buf[0], buf[1], buf[2], buf[3]);
if (count == 4) {
unsigned long ip = 0;
int i;
for (i=0; i<4; i++) {
int digit = atoi(buf[i]);
if (digit > 255) break;
ip = ip*256 + digit;
}
if (i == 4) return ip;
}
fseek(inf, pos, SEEK_SET);
}
}
return 0;
}
示例使用
unsigned long ip;
while ((ip = Parse_IP(inf)) != 0) {
printf("ip %08lX\n", ip);
}