从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地址。读者可以自行完成。