吾爱程序员:这里有好玩的游戏和软件
当前位置:首页C语言教程 → C语言验证 IP 地址

C语言验证 IP 地址

来源:网络 | 更新时间:2022-02-04 09:29:41
编写一个程序来验证 IPv4 地址。  根据维基百科,IPv4 地址以点十进制表示法表示,它由四个十进制数字组成,每个数字的范围从 0 到 255,用点分隔,例如 172.16.254.1 以下是检查给定字符串是否为有效 IPv4 地址的步骤: 步骤 1)用“.”解析字符串 使用“ strtok() ”函数作为分隔符。 
egptr = strtok(str, DELIM);
步骤 2)  A) 如果 ptr 包含任何不是数字的字符,则返回 0  B) 将“ptr”转换为十进制数字,例如 'NUM'  C) 如果 NUM 不在 0-255 范围内,则返回 0  D) 如果 NUM 在范围为 0-255 且 ptr 为非 NULL 将“dot_counter”递增 1  E) 如果 ptr 为 NULL 则转到步骤 3 否则转到步骤 1 步骤 3)如果 dot_counter != 3 返回 0 否则返回 1
// Program to check if a given
// string is valid IPv4 address or not
#include <bits/stdc++.h>
using namespace std;
#define DELIM "."

/* function to check whether the
string passed is valid or not */
bool valid_part(char* s)
{
int n = strlen(s);

// if length of passed string is
// more than 3 then it is not valid
if (n > 3)
return false;

// check if the string only contains digits
// if not then return false
for (int i = 0; i < n; i++)
if ((s[i] >= '0' && s[i] <= '9') == false)
return false;
string str(s);

// if the string is "00" or "001" or
// "05" etc then it is not valid
if (str.find('0') == 0 && n > 1)
return false;
stringstream geek(str);
int x;
geek >> x;

// the string is valid if the number
// generated is between 0 to 255
return (x >= 0 && x <= 255);
}

/* return 1 if IP string is
valid, else return 0 */
int is_valid_ip(char* ip_str)
{
// if empty string then return false
if (ip_str == NULL)
return 0;
int i, num, dots = 0;
int len = strlen(ip_str);
int count = 0;

// the number dots in the original
// string should be 3
// for it to be valid
for (int i = 0; i < len; i++)
if (ip_str[i] == '.')
count++;
if (count != 3)
return false;

// See following link for strtok()

char *ptr = strtok(ip_str, DELIM);
if (ptr == NULL)
return 0;

while (ptr) {

/* after parsing string, it must be valid */
if (valid_part(ptr))
{
/* parse remaining string */
ptr = strtok(NULL, ".");
if (ptr != NULL)
++dots;
}
else
return 0;
}

/* valid IP string must contain 3 dots */
// this is for the cases such as 1...1 where
// originally the no. of dots is three but
// after iteration of the string we find
// it is not valid
if (dots != 3)
return 0;
return 1;
}

// Driver code
int main()
{
char ip1[] = "128.0.0.1";
char ip2[] = "125.16.100.1";
char ip3[] = "125.512.100.1";
char ip4[] = "125.512.100.abc";
is_valid_ip(ip1) ? cout<<"Validn" : cout<<"Not validn";
is_valid_ip(ip2) ? cout<<"Validn" : cout<<"Not validn";
is_valid_ip(ip3) ? cout<<"Validn" : cout<<"Not validn";
is_valid_ip(ip4) ? cout<<"Validn" : cout<<"Not validn";
return 0;
}
输出
Valid
Valid
Not valid
Not valid

最新文章

热点资讯

手游排行榜

CopyRight 2020-2030吾爱程序员

鄂ICP备2021004581号-8

本站资源收集于网络,如有侵权请联系我们:35492删除0109@qq.com