对于一些常规标准的网络地址字符串中提取ip和port例子
demo.cpp
#include <iostream>
#include <string>
#include <cstring>
#include <arpa/inet.h>
std::pair<std::string, int> parse_address(const std::string addr_port) {
int port = 0;
std::string ip_str;
do{
char addr_str[40] = "";
struct in6_addr ipv6_addr;
sscanf(addr_port.c_str(), "[%40[^]]]:%d", addr_str, &port);
int ret = inet_pton(AF_INET6, addr_str, &ipv6_addr);
if (ret <= 0) {
struct in_addr ipv4_addr;
if(inet_pton(AF_INET, addr_str, &ipv4_addr) > 0){
ip_str = addr_str;
}
}else{
//check is IPv4-mapped IPv6
if (ipv6_addr.s6_addr[10] == 0xff && ipv6_addr.s6_addr[11] == 0xff) {
//is IPv4-mapped IPv6地址, get retrun IPv4
struct in_addr ipv4_addr;
memcpy(&ipv4_addr, &ipv6_addr.s6_addr[12], 4);
ip_str = inet_ntoa(ipv4_addr);
} else {
//isn't IPv4-mapped IPv6, return original IPv6
ip_str = addr_str;
}
}
}while(0);
return std::make_pair(ip_str, port);
}
int main() {
auto addr = parse_address("[::ffff:192.168.1.103]:12345");
std::cout << "IP: " << addr.first << ", Port: " << addr.second << std::endl;
addr = parse_address("[192.168.1.103]:12345");
std::cout << "IP: " << addr.first << ", Port: " << addr.second << std::endl;
addr = parse_address("[fe80::c560:dc01:e8aa:50a0]:12345");
std::cout << "IP: " << addr.first << ", Port: " << addr.second << std::endl;
return 0;
}