C++判断输入IP地址的规范性

C++``判断输入IP地址的规范性

#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;

bool isIP4(string s)
{
	
	const char *ip = s.data();    //string类型转换为char类型
	
	int count=0;
	char ip1[15];
	cout << ip << endl;
	cout << strlen(ip) << endl;    //计算字符串的长度
								   //cout << strlen(IP) << endl;
	int IP_Len = strlen(ip);
	for (int i = 0; i < IP_Len; i++)
	{

		if (isdigit(ip[i]) == 0 && ip[i] != '.')     //判断字符串是否为数字
		{
			cout << ip[i] << endl;
			return false;
		}
		if (ip[i] == '.')    //判断‘.’的个数
		{
			count++;
		 }
		if (i<= IP_Len -1)  //同时出现两个..返回错误。
		{
			if (ip[i] == ip[i + 1] && ip[i + 1]=='.')
			{
				cout << "同时出现两个:." << endl;
				return false;
			}
			
		}
	}
	if (count != 3)//如果‘.’的个数不等于3,判定IP不规范
	{
		cout << count << endl;
		return false;
	}
	//以.分割字符串,判定字符串的数值是否大于255,或小于0;
	//获取第一个字符串
	strcpy_s(ip1, s.c_str());
	char *p[5];
	char *buf;
	p[0] = strtok_s(ip1, ".", &buf);
	int i = 0;
	while (p[i])
	{
		i++;
		p[i] = strtok_s(NULL, ".", &buf);
	}
	for (int i = 0; i < 4; i++)
	{
		if (atoi(p[i])<0 || atoi(p[i])>255)
		{
			cout << "数值大于255,或小于0" << endl;
			return false;

		}
	}

	return true;
}
int main()
{
	string IP = "192.254.1.100";
	if (isIP4(IP))
	{
		cout << "true" << endl;
	}else
		cout << "false" << endl;
	
	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值