您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

C程序验证IP地址的代码

2024/5/13 9:06:32发布23次查看
在这个程序中,我们将看到如何使用c语言验证ip地址。ipv4地址以点十进制表示法表示。有四个十进制数(都在0到255之间)。这四个数字由三个点分隔。
一个有效的ip示例是:192.168.4.1
要验证ip地址,我们应该按照以下步骤进行:
使用点“.”作为分隔符对字符串(ip地址)进行标记化
如果子字符串包含任何非数字字符,则返回false
如果每个标记中的数字不在0到255的范围内,则返回false
如果有三个点和四个部分,则它是一个有效的ip地址
示例代码#include <stdio.h>#include <stdlib.h>#include <string.h>#include <ctype.h>int validate_number(char *str) { while (*str) { if(!isdigit(*str)){ //if the character is not a number, return false return 0; } str++; //point to next character } return 1;}int validate_ip(char *ip) { //check whether the ip is valid or not int i, num, dots = 0; char *ptr; if (ip == null) return 0; ptr = strtok(ip, "."); //cut the string using dor delimiter if (ptr == null) return 0; while (ptr) { if (!validate_number(ptr)) //check whether the sub string is holding only number or not return 0; num = atoi(ptr); //convert substring to number if (num >= 0 && num <= 255) { ptr = strtok(null, "."); //cut the next part of the string if (ptr != null) dots++; //increase the dot count } else return 0; } if (dots != 3) //if the number of dots are not 3, return false return 0; return 1;}int main() { char ip1[] = "192.168.4.1"; char ip2[] = "172.16.253.1"; char ip3[] = "192.800.100.1"; char ip4[] = "125.512.100.abc"; validate_ip(ip1)? printf("valid
"): printf("not valid
"); validate_ip(ip2)? printf("valid
"): printf("not valid
"); validate_ip(ip3)? printf("valid
"): printf("not valid
"); validate_ip(ip4)? printf("valid
"): printf("not valid
");}
输出validvalidnot validnot valid
以上就是c程序验证ip地址的代码的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product