From: Mikko Rasa Date: Wed, 10 Aug 2011 17:49:39 +0000 (+0300) Subject: Add an overload for resolve that takes host and service separately X-Git-Url: http://git.tdb.fi/?a=commitdiff_plain;h=21c596567e3b6fd794ed6af73d304ce2bc70e58f;p=libs%2Fnet.git Add an overload for resolve that takes host and service separately --- diff --git a/source/resolve.cpp b/source/resolve.cpp index 6e17a1a..e8aad66 100644 --- a/source/resolve.cpp +++ b/source/resolve.cpp @@ -15,40 +15,20 @@ using namespace std; namespace Msp { namespace Net { -SockAddr *resolve(const string &s, Family family) +SockAddr *resolve(const string &host, const string &serv, Family family) { - string host, serv; - if(s[0]=='[') - { - unsigned bracket = s.find(']'); - host = s.substr(1, bracket-1); - unsigned colon = s.find(':', bracket); - if(colon!=string::npos) - serv = s.substr(colon+1); - } - else - { - unsigned colon = s.find(':'); - if(colon!=string::npos) - { - host = s.substr(0, colon); - serv = s.substr(colon+1); - } - else - host = s; - } - + const char *chost = (host.empty() ? 0 : host.c_str()); + const char *cserv = (serv.empty() ? 0 : serv.c_str()); unsigned flags = 0; if(host=="*") { flags = AI_PASSIVE; - host = string(); + chost = 0; } addrinfo hints = { flags, family_to_sys(family), 0, 0, 0, 0, 0, 0 }; addrinfo *res; - const char *chost = (host.empty() ? 0 : host.c_str()); - const char *cserv = (serv.empty() ? 0 : serv.c_str()); + int err = getaddrinfo(chost, cserv, &hints, &res); if(err==0) { @@ -69,6 +49,32 @@ SockAddr *resolve(const string &s, Family family) #endif } +SockAddr *resolve(const string &str, Family family) +{ + string host, serv; + if(str[0]=='[') + { + unsigned bracket = str.find(']'); + host = str.substr(1, bracket-1); + unsigned colon = str.find(':', bracket); + if(colon!=string::npos) + serv = str.substr(colon+1); + } + else + { + unsigned colon = str.find(':'); + if(colon!=string::npos) + { + host = str.substr(0, colon); + serv = str.substr(colon+1); + } + else + host = str; + } + + return resolve(host, serv, family); +} + /*sockaddr sa; unsigned size = fill_sockaddr(sa); char hst[128]; diff --git a/source/resolve.h b/source/resolve.h index 0afc9ad..256455f 100644 --- a/source/resolve.h +++ b/source/resolve.h @@ -9,6 +9,15 @@ namespace Net { class SockAddr; +/** Resolves host and service names into a socket address. If host is empty, +the loopback address will be used. If host is "*", the wildcard address will +be used. If service is empty, a socket address with a null service will be +returned. With the IP families, these are not very useful. */ +SockAddr *resolve(const std::string &, const std::string &, Family = UNSPEC); + +/** And overload of resolve() that takes host and service as a single string, +separated by a colon. If the host part contains colons, such as is the case +with a numeric IPv6 address, it must be enclosed in brackets. */ SockAddr *resolve(const std::string &, Family = UNSPEC); } // namespace Net