判断IP地址是否为合法的IP(初级版本)

思路:

  1.  只包含3个点号;
  2.  第一个段的数据为1~255,其它段的数据为0~255;
  3.  除了数字和.号不能出现其它的字符
    #include<stdio.h>
    #include<ctype.h>
    int CountPoint(const char *str)		//计算点号个数
    {
    	int count = 0;
    	while (*str != '\0')
    	{
    		if (*str == '.')
    		{
    			count++;
    		}
    		str++;
    	}
    	return count;
    }
    
    //IP地址的规则是: (1~255).(0~255).(0~255).(0~255)
    /*1、只包含3个点号;
     *2、第一个段的数据为1~255,其它段的数据为0~255;
     *3、除了数字和.号不能出现其它的字符
    */
    bool IsLegalIP(const char *str)
    {
    	int num = 0;
    	if (str == NULL)
    	{
    		return false;
    	}
    	if (CountPoint(str) != 3)	//点分十进制只含3个点号
    	{
    		return false;
    	}
    	if (str[0] == '0')
    	{
    		return false;
    	}
    	
    	while (*str != '\0')		//循环结束的条件是遇见'\0'。
    	{
    		if (isdigit(*str))
    		{
    			num=num * 10 +*str - '0';
    		}
    		else if (*str != '.' || num > 255)
    		{
    			return false;
    		}
    		else
    		{
    			num = 0;
    		}
    		str++;
    	}
    	if (num > 255)    //最后一个点分十进制需要额外小心
    	{
    		return false;
    	}
    
    	return true;
    }
    
    
    int main()
    {
    	const char *str[] = { "192.168.1.1","1.0.0","1.0.0.0","256.1.2.1","192.1.1.256","192.09.09.10" };
    	for (int i = 0; i<sizeof(str) / sizeof(str[0]); i++)
    	{
    		if (IsLegalIP(str[i]))
    		{
    			printf("%s 是合法的IP\n", str[i]);
    		}
    		else
    		{
    			printf("%s 不是合法的IP\n", str[i]);
    		}
    	}
    	return 0;
    }
    

 总结:每一个点分十进制段,非零的数字字符前面不得含有字符。

并没有做到很完善,需要进一步修改。

运行结果

猜你喜欢

转载自blog.csdn.net/qq_41822235/article/details/81407435