#include <iostream>
#include <string>
#include <cassert>
// 提取 URL 中的 IP 地址、端口号和路径
bool parseUrl(const std::string& url, std::string& scheme, std::string& host, std::string& port, std::string& path) {
size_t schemeEnd = url.find("://");
size_t atSign = url.find("@"); // 寻找可能存在的 @ 符号,用于区分用户名密码和主机名
size_t slashAfterScheme = url.find('/', schemeEnd + 3);
// 提取 scheme
if (schemeEnd == std::string::npos) {
return false;
}
scheme = url.substr(0, schemeEnd);
// 提取 host 和 port
size_t colonPos = url.find(':', atSign == std::string::npos ? schemeEnd + 3 : atSign + 1);
if (colonPos == std::string::npos) {
host = url.substr(schemeEnd + 3, slashAfterScheme - (schemeEnd + 3));
} else {
host = url.substr(schemeEnd + 3, colonPos - (schemeEnd + 3));
port = url.substr(colonPos + 1, slashAfterScheme - (colonPos + 1));
}
// 提取 path
if (slashAfterScheme == std::string::npos) {
path.clear();
} else {
path = url.substr(slashAfterScheme);
}
// 成功解析
return true;
}
int main() {
std::string url = "http://192.168.0.188:8088/svr/api/pub/auto";
std::string scheme, host, port, path;
bool success = parseUrl(url, scheme, host, port, path);
if (success) {
std::cout << "Scheme: " << scheme << std::endl;
std::cout << "Host: " << host << std::endl;
std::cout << "Port: " << port << std::endl;
std::cout << "Path: " << path << std::endl;
// 断言检查 http://192.168.0.188:8088/svr/api/pub/auto
assert(scheme == "http");
assert(host == "192.168.0.188");
assert(port == "8088");
assert(path == "/svr/api/pub/auto");
} else {
std::cout << "Failed to parse URL." << std::endl;
}
return 0;
}
提取URL中的ip,端口,路径,协议
最新推荐文章于 2024-09-13 20:37:35 发布