-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathip_address.h
More file actions
91 lines (79 loc) · 2.68 KB
/
Copy pathip_address.h
File metadata and controls
91 lines (79 loc) · 2.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#ifndef CPP_ALGORITHM_IP_ADDRESS_H
#define CPP_ALGORITHM_IP_ADDRESS_H
#include <string>
#include <vector>
namespace IpAddress
{
/**
* \brief Validate IP address.
* \param str address string omitted with '.'
* \return valid ip addresses
*/
std::vector<std::string> GetValidIpAddress(const std::string& str);
}
// ----------------------------------------------------------------------------
inline bool IsValidPart(const std::string& str)
{
if (str.empty() || str.size() > 3)
{
return false;
}
if (str.size() > 1 && str[0] == '0')
{
return false;
}
const int value = std::stoi(str);
return value >= 0 && value <= 255;
}
// ----------------------------------------------------------------------------
#if defined(_MSC_VER)
#include <format>
inline std::vector<std::string> IpAddress::GetValidIpAddress(const std::string& str)
{
std::vector<std::string> result;
for (int i = 1; i < 4 && i < static_cast<int>(str.size()); ++i)
{
for (int j = 1; j < 4 && i + j < static_cast<int>(str.size()); ++j)
{
for (int k = 1; k < 4 && i + j + k < static_cast<int>(str.size()); ++k)
{
const std::string first = str.substr(0, i);
const std::string second = str.substr(i, j);
const std::string third = str.substr(i + j, k);
const std::string fourth = str.substr(i + j + k);
if (IsValidPart(first) && IsValidPart(second) && IsValidPart(third) && IsValidPart(fourth))
{
result.push_back(std::format("{}.{}.{}.{}", first, second, third, fourth));
}
}
}
}
return result;
}
#elif defined(__GNUG__)
#include <fmt/format.h>
inline std::vector<std::string> IpAddress::GetValidIpAddress(const std::string& str)
{
std::vector<std::string> result;
for (int i = 1; i < 4 && i < static_cast<int>(str.size()); ++i)
{
for (int j = 1; j < 4 && i + j < static_cast<int>(str.size()); ++j)
{
for (int k = 1; k < 4 && i + j + k < static_cast<int>(str.size()); ++k)
{
const std::string first = str.substr(0, i);
const std::string second = str.substr(i, j);
const std::string third = str.substr(i + j, k);
const std::string fourth = str.substr(i + j + k);
if (IsValidPart(first) && IsValidPart(second) && IsValidPart(third) && IsValidPart(fourth))
{
result.push_back(fmt::format("{}.{}.{}.{}", first, second, third, fourth));
}
}
}
}
return result;
}
#else
#endif
#endif