The Battle for Wesnoth  1.17.0-dev
parse_network_address.cpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2019 by Sergey Popov <loonycyborg@gmail.com>
3  Part of the Battle for Wesnoth Project https://www.wesnoth.org/
4 
5  This program is free software; you can redistribute it and/or modify
6  it under the terms of the GNU General Public License as published by
7  the Free Software Foundation; either version 2 of the License, or
8  (at your option) any later version.
9  This program is distributed in the hope that it will be useful,
10  but WITHOUT ANY WARRANTY.
11 
12  See the COPYING file for more details.
13 */
15 
16 #include <regex>
17 #include <string>
18 
19 std::pair<std::string, std::string> parse_network_address(const std::string& address, const std::string& default_port)
20 {
21  const char* address_re = "\\[([[:xdigit:]:]*)\\](:([[:alnum:]]*))?|([[:alnum:]-_\\.]{1,253})(:([[:alnum:]]*))?";
22 
23  std::smatch m;
24  std::regex_match(address, m, std::regex(address_re));
25 
26  if(!m[1].str().empty()) {
27  return { m[1], m[3].str().empty() ? default_port : m[3] };
28  }
29  if(!m[4].str().empty()) {
30  return { m[4], m[6].str().empty() ? default_port : m[6] };
31  }
32 
33  throw std::runtime_error("invalid address");
34 }
std::pair< std::string, std::string > parse_network_address(const std::string &address, const std::string &default_port)
Parse a host:port style network address, supporting [] notation for ipv6 addresses.