sources/network/ipaddress.cpp

changeset 188
5fc32e4b2a8c
parent 186
9330b93d9946
child 190
90bf9049e5eb
equal deleted inserted replaced
187:53f9c7b2c068 188:5fc32e4b2a8c
118 return {}; 118 return {};
119 errorStream << "could not parse port"s; 119 errorStream << "could not parse port"s;
120 } 120 }
121 } 121 }
122 122
123 std::optional<net::ip_address> net::ip_scan_octets(const char* address_string)
124 {
125 std::optional<net::ip_address> value;
126 net::octet_t parts[4];
127 if (std::sscanf(address_string, "%hhu.%hhu.%hhu.%hhu", &parts[0], &parts[1], &parts[2], &parts[3]))
128 {
129 value = net::ip_address{};
130 for (unsigned char i = 0; i < 4; i += 1)
131 ip_set_octet(&*value, i, parts[i]);
132 }
133 return value;
134 }
135
136 std::optional<net::ip_address> net::ip_resolve_hostname(const std::string& node, std::ostream& errorStream) 123 std::optional<net::ip_address> net::ip_resolve_hostname(const std::string& node, std::ostream& errorStream)
137 { 124 {
138 AddrInfo hints; 125 AddrInfo hints;
139 AddrInfo* lookup; 126 AddrInfo* lookup;
140 memset(&hints, 0, sizeof hints); 127 memset(&hints, 0, sizeof hints);
158 { 145 {
159 int colonpos = input_string.find(":"); 146 int colonpos = input_string.find(":");
160 std::string addressString = colonpos == -1 ? input_string : mid(input_string, 0, colonpos); 147 std::string addressString = colonpos == -1 ? input_string : mid(input_string, 0, colonpos);
161 std::optional<net::ip_address> value; 148 std::optional<net::ip_address> value;
162 // Try scanf the IPv4 host first 149 // Try scanf the IPv4 host first
163 value = ip_scan_octets(addressString.data()); 150 int parts[4];
164 if (not value.has_value()) 151 if (std::sscanf(addressString.data(), "%d.%d.%d.%d", &parts[0], &parts[1], &parts[2], &parts[3]))
152 {
153 value = net::ip_address{};
154 for (unsigned char i = 0; i < 4; i += 1)
155 {
156 if (parts[i] >= 0 and parts[i] < 256)
157 {
158 ip_set_octet(&*value, i, parts[i]);
159 }
160 else
161 {
162 value.reset();
163 errorStream << "IP address value out of range";
164 break;
165 }
166 }
167 }
168 else
165 { 169 {
166 // Possibly a hostname, try resolve it 170 // Possibly a hostname, try resolve it
167 value = ip_resolve_hostname(addressString, errorStream); 171 value = ip_resolve_hostname(addressString, errorStream);
168 } 172 }
169 if (value.has_value() and colonpos != -1) 173 if (value.has_value() and colonpos != -1)

mercurial