rby1-sdk
Loading...
Searching...
No Matches
network_util.h
1#pragma once
2
3#include <sys/socket.h>
4#include <regex>
5#include <string>
6
7namespace rb {
8
9inline std::string DecodeUrl(const std::string& encoded) {
10 std::string decoded;
11 char ch;
12 int i, j;
13 for (i = 0; i < encoded.length(); i++) {
14 if (encoded[i] == '%') {
15 sscanf(encoded.substr(i + 1, 2).c_str(), "%x", &j);
16 ch = static_cast<char>(j);
17 decoded += ch;
18 i += 2;
19 } else if (encoded[i] == '+') {
20 decoded += ' ';
21 } else {
22 decoded += encoded[i];
23 }
24 }
25 return decoded;
26}
27
28inline bool ParseIPAndFamily(std::string addr, std::string& ip, int& family) {
29 addr = DecodeUrl(addr);
30
31 std::regex ipv4_regex(R"(ipv4:([\d\.]+):\d+)");
32 std::regex ipv6_regex(R"(ipv6:\[([0-9a-fA-F:]+)\]:\d+)");
33 std::smatch match;
34
35 if (std::regex_search(addr, match, ipv4_regex)) {
36 ip = match[1];
37 family = AF_INET;
38 return true;
39 } else if (std::regex_search(addr, match, ipv6_regex)) {
40 ip = match[1];
41 family = AF_INET6;
42 return true;
43 }
44 return false;
45}
46
47} // namespace rb