138 } |
136 } |
139 |
137 |
140 // ----------------------------------------------------------------------------- |
138 // ----------------------------------------------------------------------------- |
141 // |
139 // |
142 STATIC METHOD |
140 STATIC METHOD |
143 IPAddress::from_string (String input, bool* ok) -> IPAddress |
141 IPAddress::from_string (String input) -> IPAddress |
144 { |
142 { |
145 unsigned int parts[4]; |
143 unsigned int parts[4]; |
146 int colonpos = input.find (":"); |
144 int colonpos = input.find (":"); |
147 String addressString = colonpos == -1 ? input : input.mid (0, colonpos); |
145 String addressString = colonpos == -1 ? input : input.mid (0, colonpos); |
148 IPAddress value; |
146 IPAddress value; |
154 value.set_octet (i, parts[i]); |
152 value.set_octet (i, parts[i]); |
155 } |
153 } |
156 else |
154 else |
157 { |
155 { |
158 // Possibly a hostname, try resolve it |
156 // Possibly a hostname, try resolve it |
159 value = IPAddress::resolve (addressString, ok); |
157 value = IPAddress::resolve (addressString); |
160 |
|
161 if (*ok == false) |
|
162 return value; |
|
163 } |
158 } |
164 |
159 |
165 if (colonpos != -1) |
160 if (colonpos != -1) |
166 value.port = input.mid (colonpos + 1, -1).to_int(); |
161 value.port = input.mid (colonpos + 1, -1).to_int(); |
167 |
162 |
169 } |
164 } |
170 |
165 |
171 // ----------------------------------------------------------------------------- |
166 // ----------------------------------------------------------------------------- |
172 // |
167 // |
173 STATIC METHOD |
168 STATIC METHOD |
174 IPAddress::resolve (String node, bool* ok) -> IPAddress |
169 IPAddress::resolve (String node) -> IPAddress |
175 { |
170 { |
176 addrinfo hints; |
171 addrinfo hints; |
177 addrinfo* lookup; |
172 addrinfo* lookup; |
178 memset (&hints, 0, sizeof hints); |
173 memset (&hints, 0, sizeof hints); |
179 hints.ai_family = AF_INET; |
174 hints.ai_family = AF_INET; |
180 |
175 |
181 if (getaddrinfo (node, nullptr, &hints, &lookup) != 0) |
176 if (getaddrinfo (node, nullptr, &hints, &lookup) != 0) |
182 { |
177 throw StringParseError ("unknown host " + node); |
183 *ok = false; |
|
184 return IPAddress(); |
|
185 } |
|
186 |
178 |
187 IPAddress result; |
179 IPAddress result; |
188 assert (lookup != nullptr); |
180 assert (lookup != nullptr); |
189 sockaddr_in* addr = reinterpret_cast<sockaddr_in*> (lookup[0].ai_addr); |
181 sockaddr_in* addr = reinterpret_cast<sockaddr_in*> (lookup[0].ai_addr); |
190 result.host = ntohl (addr->sin_addr.s_addr); |
182 result.host = ntohl (addr->sin_addr.s_addr); |