判断输入的字符串是否为ip地址
首先给出一个c函数的原型:int sscanf(const char *buffer,const char *format,[argument ]...)它的返回值是参数的数据,也就是argument的个数,buffer:存储的数据,format:格式控制字符串,argument:选择性设定字符串。这个程序从标准流读取数据,可以进行无限制的输入。下面贴出代码,然后引出另外一个问题,将字符串ip转换成整形ip地址。
#include<stdio.h>#include<string.h>int main(void){ char str[32]; int a,b,c,d; int ret=0; while(fgets(str,sizeof(str),stdin)!=NULL) { int len=strlen(str); str[len]='\0'; ret=sscanf(str,"%d.%d.%d.%d",&a,&b,&c,&d); if(ret==4&&(a>=0&&a<=255)&&(b>=0&&b<=255)&&(c>=0&&c<=255)&&(d>=0&&d<=255)) { printf("it is ip!\n"); } else printf("it is not ip!\n"); } return 0;}
12.3.4.5
it is a ip!
下面来引出另外一个问题,在很多情况下,要求把字符串ip转换成整形ip,这个问题也可以应用sscanf这个函数,首先把四个字段存储到a,b,c,d四个变量当中去,然后进行移位运算,因为ip地址是32位的,而且是无符号整形变量,所以可以应用unsigned int 来存储. unsinged int ip=(a<<24)+(b<<16)+(c<<8)+d。