Function:
/*
* Input:sip
* Output:ip
* Return:true/false
*
* Reference:
* cutApart-http://blog.csdn.net/smartup/article/details/8704094
*/
bool formatIP(const char* sip,unsigned long* ip)
{
char** p;
char* pend;
int i, fragements = 4;
unsigned long l;
if ( cutApart(sip, &p, '.',&fragements) )
{
for (i=0; i<fragements; i++)
{
//检查是否为[0,255]直接的数字
l = strtol(*p,&pend,10);
if (*pend) return false;
if ( l<0 || l>255 ) return false;
(*ip) = (*ip)|l;
if (i != fragements-1) *ip = (*ip)<<8;
p++;
}
return true;
}
return false;
}
TestCase:
void test_formatIP()
{
char s[6][20]={"192.168.25.900","",".100.","0.0.0.0","127.0.0.1","8.0.9.8"};
int i;
unsigned long ip;
printf("test_formatIP:\n");
for (i=0; i<6; i++)
{
ip = 0;
if( formatIP(s[i],&ip) ) printf("True:%08X\n",ip);
else printf("false!\n");
}
}
Result:
test_formatIP:
false!
false!
false!
True:00000000
True:7F000100
True:08090800