ip地址以字符串的形式给出,现在要求写一段代码来验证此ip地址是否合法。
#include
#include
#include
#include
#include
/* define macro BOOL, FALSE, TRUE */
#ifndef BOOL
typedef int BOOL;
#define FALSE 0
#define TRUE 1
#endif /* end of BOOL */
BOOL is_valid_ip_address(const char *addr);
int main(void)
{
char *addr = "10a.193.174.124";
if ( is_valid_ip_address(addr) )
{
printf("%s is a valid ip address.\n", addr);
}
else
{
printf("%s is a invalid ip address.\n", addr);
}
exit(EXIT_SUCCESS);
}
BOOL is_valid_ip_address(const char *addr)
{
int num= 0;
int i = 0, j = 0;
int value;
char buf[4] ;
memset(buf, 0, sizeof(buf));
while ( *(addr + i) != '\0' )
{
++num;
while ( *(addr + i) != '\0' && *(addr + i) != '.' )
{
if ( ! isdigit(*(addr + i)) )
{
return FALSE;
}
*(buf + j) = *(addr + i);
++i;
++j;
}
*(buf + j) = '\0';
value = atoi(buf);
if ( (value > 255) || (value < 0) )
{
return FALSE;
}
if ( *(addr + i) == '.' )
{
++i;
j = 0;
memset(buf, 0, sizeof(buf));
continue;
}
else
{
break;
}
}
if ( num == 4 )
return TRUE;
else
return FALSE;
}
阅读(402) | 评论(0) | 转发(0) |