url中找出IP地址

从url中找出ip地址

比如 http://192.168.1.111:3000/2.xml
比如 http://192.168.2.222/dddd.png

思路

设定接口函数为:

const char * findip(string &xmlip, int &num)

1 从中找出第一个数字,如果没有数字,那就返回NULL
2 从中找到末位是’:’ , ‘/’ 的,如果找不到,就返回NULL
此种为特定的函数,并没有把所有出错处理完成,也没有完成是否是IP地址
所以完成后,必须检测是否是ip地址

const char * findip(string &xmlip, int &num)
{
#define JUDGE if(pos==pend){num=0;return NULL;}
	const char *pos = xmlip.c_str();
	const char *pstart = pos;
	const char *pend = pos + xmlip.size();

	if (isdigit(*pos))
		pstart = pos;
	else 
		while (!::isdigit(*(++pos)) && (pos!=pend));
	JUDGE
	pstart = pos;
	while ((++pos != pend) && (*pos)!= '/' && (*pos) != ':');
	JUDGE
	num = pos - pstart;
	return  pstart;
}

但是这种没有考虑最后一位是数字的情况,修改一下判读虽然到了结尾但是结尾是数字的情况,这种边缘测试是非常需要的,对这个函数进行用例上的测试确实需要完整,当然我们的函数依然是不完整,不过大多数的情况已经覆盖:

const char * findip(string &xmlip, int &num)
{
	const char *pos = xmlip.c_str();
	const char *pstart = pos;
	const char *pend = pos + xmlip.size();

	if (isdigit(*pos))
		pstart = pos;
	else 
		while (!::isdigit(*(++pos)) && (pos!=pend));
	if (pos == pend) 
	{
		num = 0; 
		return NULL; 
	}
	pstart = pos;
	while ((++pos != pend) && (*pos)!= '/' && (*pos) != ':');
	if (pos == pend)
	{
		if (!isdigit(*(pend - 1)))
		{
			num =0;
			return NULL;
		}
	}
	
	num = pos - pstart;
	return  pstart;
}

测试

int main()
{
	string test;
	string ipxml = "http://192.168.1.123:3001/test.xml";
	int num = 0;
	const char * ip = findip(ipxml, num);
	test = string(ip, num);
	cout << test <<endl;

	ipxml = "192.168.1.123:3001";
	ip = findip(ipxml, num);
	test = string(ip, num);
	cout << test << endl;

	ipxml = "192.168.1.123/2.xml";
	ip = findip(ipxml, num);
	test = string(ip, num);
	cout << test << endl;

	ipxml = "http://192.168.1.123/2.xml";
	ip = findip(ipxml, num);
	test = string(ip, num);
	cout << test << endl;

	ipxml = "http://192.168.1.23";
	ip = findip(ipxml, num);
	test = string(ip, num);
	cout << test << endl;
	getchar();
}

输出

192.168.1.123
192.168.1.123
192.168.1.123
192.168.1.123
192.168.1.23

这样基本的情况已经判定了,需要的是接下去判定是否是真实的ip地址。读者可以自行完成。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qianbo_insist

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值