C语言实现判断输入的ip地址和掩码格式正确
时间: 2024-09-29 08:11:37 浏览: 51
在C语言中,验证IP地址和子网掩码的格式是否正确可以使用正则表达式库来匹配常见的IPv4和IPv6格式。这里是一个基本的示例,展示了如何使用`<regex>`库来检查IPv4和IPv6加上掩码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <regex.h>
// 定义正则表达式模式
const char *ipv4_pattern = "^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
const char *ipv6_pattern = "^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$";
const char *mask_pattern = "^(255|25[0-4]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(255|25[0-4]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(255|25[0-4]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(255|25[0-4]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
int is_valid_ip_subnet(char *input) {
regex_t ipv4_regex, ipv6_regex, mask_regex;
int rc;
// IPv4 validation
rc = regcomp(&ipv4_regex, ipv4_pattern, REG_EXTENDED);
if (rc == 0 && strncmp(input, "IPv4:", 5) == 0) {
size_t match_len = strlen(input) - 5;
if (regexec(&ipv4_regex, input + 5, 0, NULL, 0) == 0 && regfree(&ipv4_regex)) {
return match_len;
}
regfree(&ipv4_regex);
}
// IPv6 validation
rc = regcomp(&ipv6_regex, ipv6_pattern, REG_EXTENDED);
if (rc == 0 && strncmp(input, "IPv6:", 5) == 0) {
size_t match_len = strlen(input) - 5;
if (regexec(&ipv6_regex, input + 5, 0, NULL, 0) == 0 && regfree(&ipv6_regex)) {
return match_len;
}
regfree(&ipv6_regex);
}
// Mask validation
rc = regcomp(&mask_regex, mask_pattern, REG_EXTENDED);
if (rc == 0 && strncmp(input, "Mask:", 5) == 0) {
size_t match_len = strlen(input) - 5;
if (regexec(&mask_regex, input + 5, 0, NULL, 0) == 0 && regfree(&mask_regex)) {
return match_len;
}
regfree(&mask_regex);
}
return -1; // 输入无效
}
int main() {
char input[] = "IPv4:192.168.1.1/24";
printf("Input: %s\n", input);
int result = is_valid_ip_subnet(input);
if (result >= 0) {
printf("Valid IP subnet with length: %d\n", result);
} else {
printf("Invalid IP subnet.\n");
}
return 0;
}
```
这个程序首先定义了正则表达式模式,然后在`is_valid_ip_subnet`函数中分别对IPv4、IPv6和子网掩码进行匹配。如果输入符合相应的模式,并且以特定前缀开始(如"IPv4:"、“IPv6:”或“Mask:”),它会返回匹配的长度。否则,函数返回-1表示输入无效。
阅读全文