c++将一个字符串ip转换成点分十进制的IP并且判断其是否合法
时间: 2024-03-09 20:48:47 浏览: 14
可以使用C++中的inet_pton函数将字符串IP转换为二进制形式的IP,然后再使用inet_ntoa函数将二进制形式的IP转换为点分十进制形式的IP。同时,可以使用正则表达式来判断输入的字符串是否符合IP地址的格式。
下面是一个示例代码:
```c++
#include <iostream>
#include <string>
#include <regex>
#include <arpa/inet.h>
using namespace std;
bool is_valid_ip(string ip_str) {
regex pattern("^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$");
if (!regex_match(ip_str, pattern)) {
return false;
}
struct in_addr addr;
int result = inet_pton(AF_INET, ip_str.c_str(), &addr);
return result != 0;
}
int main() {
string ip_str = "192.168.0.1";
if (is_valid_ip(ip_str)) {
struct in_addr addr;
inet_pton(AF_INET, ip_str.c_str(), &addr);
char ip[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &addr, ip, INET_ADDRSTRLEN);
cout << "IP address: " << ip << endl;
} else {
cout << "Invalid IP address" << endl;
}
return 0;
}
```
在上面的示例中,is_valid_ip函数用于判断输入的字符串是否为合法的IP地址。该函数首先使用正则表达式判断输入的字符串是否符合IP地址的格式,然后使用inet_pton函数将字符串IP转换为二进制形式的IP,并返回转换结果。如果返回值不为0,则表示转换成功,输入的字符串IP为合法的IP地址。
在主函数中,首先判断输入的字符串是否为合法的IP地址。如果是,则使用inet_pton和inet_ntop函数将字符串IP转换为点分十进制形式的IP,并输出结果;否则,输出错误信息。