方法1:
bool is_ip_valid(char * IPAddr)
{
int i = 0;
int j=0;
int length;
char *p= NULL;
char ipddd[20];
length = strlen(IPAddr);
if (length < 7 ||length > 15)
{
return FALSE;
}
memset(ipddd,'\0',sizeof(ipddd));
strcpy(ipddd,IPAddr);
p = strtok(ipddd,".");
while (p)
{
length = strlen (p);
if (length > 3 || length == 0)
{
printf("2\n");
return FALSE;
}
for (j = 0;j < length;j++)
{
if (!isdigit(p[j]))
{
return FALSE;
}
}
if (atoi(p) > 255 || atoi(p) < 0)
{
return FALSE;
}
if (i == 0 && atoi (p) < 1)
{
return FALSE;
}
if (i++> 3)
{
return FALSE;
}
p = strtok(NULL,".");
}
if (i == 4)
return TRUE;
else
return FALSE;
}
方法2:
int inet_aton(const char *cp, struct in_addr *inp);使用该函数时需要做一些简单的判断。
inet_aton() converts the Internet host address cp from the IPv4 numbers-and-dots notation into binary form (in network byte order) and stores it in the
structure that inp points to. inet_aton() returns nonzero if the address is valid, zero if not. The address supplied in cp can have one of the following
forms:
a.b.c.d Each of the four numeric parts specifies a byte of the address; the bytes are assigned in left-to-right order to produce the binary address.
a.b.c Parts a and b specify the first two bytes of the binary address. Part c is interpreted as a 16-bit value that defines the rightmost two bytes of
the binary address. This notation is suitable for specifying (outmoded) Class B network addresses.
a.b Part a specifies the first byte of the binary address. Part b is interpreted as a 24-bit value that defines the rightmost three bytes of the
binary address. This notation is suitable for specifying (outmoded) Class C network addresses.
a The value a is interpreted as a 32-bit value that is stored directly into the binary address without any byte rearrangement.
In all of the above forms, components of the dotted address can be specified in decimal, octal (with a leading 0), or hexadecimal, with a leading 0X).
Addresses in any of these forms are collectively termed IPV4 numbers-and-dots notation. The form that uses exactly four decimal numbers is referred to as
IPv4 dotted-decimal notation (or sometimes: IPv4 dotted-quad notation).
阅读(1405) | 评论(0) | 转发(0) |