目录
- boost::regex使用demo
- inet_pton函数来尝试将IP地址解析为IPv4或IPv6地址
- 总结
原本写了个同时识别IPv4和IPv6地址的C++函数:
#include <iostream>
#include <regex>
bool is_valid_ip(const std::string& ip) {
// 定义IPv4地址的正则表达式
std::regex pattern_ipv4("^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])$");
// 定义IPv6地址的正则表达式
std::regex pattern_ipv6("^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$");
// 使用正则表达式匹配IP地址
return std::regex_match(ip, pattern_ipv4) || std::regex_match(ip, pattern_ipv6);
}
int main() {
std::string ip1 = "192.168.0.1";
std::string ip2 = "2001:0db8:85a3:0000:0000:8a2e:0370:7334";
if (is_valid_ip(ip1)) {
std::cout << "IPv4地址合法" << std::endl;
} else {
std::cout << "IPv4地址不合法" << std::endl;
}
if (is_valid_ip(ip2)) {
std::cout << "IPv6地址合法" << std::endl;
} else {
std::cout << "IPv6地址不合法" << std::endl;
}
return 0;
}
编译时无报错,运行时抛异常regex_error
check后发现,gcc版本4.9以上才能使用std::regex 而我们一般gcc版本是4.8.5 所以这里不采用std::regex,gcc版本升级不现实,可采取的方案有两个:
1、使用boost::regex
2、使用inet_pton判断ip
boost::regex使用demo
#include <iostream>
#include <boost/regex.hpp>
bool is_valid_ip(const std::string& ip) {
// 定义IPv4地址的正则表达式
boost::regex pattern_ipv4("^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])$");
// 定义IPv6地址的正则表达式
boost::regex pattern_ipv6("^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$");
// 使用正则表达式匹配IP地址
return boost::regex_match(ip, pattern_ipv4) || boost::regex_match(ip, pattern_ipv6);
}
int main() {
std::string ip1 = "192.168.0.1";
std::string ip2 = "2001:0db8:85a3:0000:0000:8a2e:0370:7334";
if (is_valid_ip(ip1)) {
std::cout << "IPv4地址合法" << std::endl;
} else {
std::cout << "IPv4地址不合法" << std::endl;
}
if (is_valid_ip(ip2)) {
std::cout << "IPv6地址合法" << std::endl;
} else {
std::cout << "IPv6地址不合法" << std::endl;
}
return 0;
}
inet_pton函数来尝试将IP地址解析为IPv4或IPv6地址
#include <iostream>
#include <cstring>
#include <arpa/inet.h>
bool is_valid_ip(const std::string& ip) {
struct in_addr addr4;
struct in6_addr addr6;
// 尝试将IP地址解析为IPv4地址
if (inet_pton(AF_INET, ip.c_str(), &addr4) == 1) {
return true;
}
// 尝试将IP地址解析为IPv6地址
if (inet_pton(AF_INET6, ip.c_str(), &addr6) == 1) {
return true;
}
// IP地址既不是IPv4地址也不是IPv6地址
return false;
}
int main() {
std::string ip1 = "192.168.0.1";
std::string ip2 = "2001:0db8:85a3:0000:0000:8a2e:0370:7334";
if (is_valid_ip(ip1)) {
std::cout << "IPv4地址合法" << std::endl;
} else {
std::cout << "IPv4地址不合法" << std::endl;
}
if (is_valid_ip(ip2)) {
std::cout << "IPv6地址合法" << std::endl;
} else {
std::cout << "IPv6地址不合法" << std::endl;
}
return 0;
}
总结
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

评论(0)