From d4ccea4185f111970d8bb6144040caa0402720d9 Mon Sep 17 00:00:00 2001 From: Alan Conway Date: Thu, 31 Jan 2008 23:14:49 +0000 Subject: Generate URLs for local host. git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk/qpid@617286 13f79535-47bb-0310-9956-ffa450edef68 --- cpp/src/qpid/Url.cpp | 41 ++++++++++++++++++++++++++++++++++++++++- cpp/src/qpid/Url.h | 8 ++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) (limited to 'cpp/src') diff --git a/cpp/src/qpid/Url.cpp b/cpp/src/qpid/Url.cpp index d52fc71870..1e0e0b3603 100644 --- a/cpp/src/qpid/Url.cpp +++ b/cpp/src/qpid/Url.cpp @@ -16,16 +16,55 @@ * */ -#include "Url.h" +#include "qpid/Url.h" +#include "qpid/Exception.h" +#include "qpid/Msg.h" + #include #include #include +#include +#include +#include +#include +#include +#include + using namespace boost::spirit; using namespace std; namespace qpid { +Url Url::getHostnameUrl(uint16_t port) { + char name[HOST_NAME_MAX]; + if (::gethostname(name, sizeof(name)) != 0) + throw Exception(QPID_MSG("Cannot get host name: " << strError(errno))); + return Url(TcpAddress(name, port)); +} + +static const string LOCALHOST("127.0.0.1"); + +Url Url::getIpAddressesUrl(uint16_t port) { + Url url; + int s = socket (PF_INET, SOCK_STREAM, 0); + for (int i=1;;i++) { + struct ifreq ifr; + ifr.ifr_ifindex = i; + if (::ioctl (s, SIOCGIFNAME, &ifr) < 0) + break; + /* now ifr.ifr_name is set */ + if (::ioctl (s, SIOCGIFADDR, &ifr) < 0) + continue; + struct sockaddr_in *sin = (struct sockaddr_in *) &ifr.ifr_addr; + string addr(inet_ntoa(sin->sin_addr)); + if (addr != LOCALHOST) + url.push_back(TcpAddress(addr, port)); + } + close (s); + return url; +} + string Url::str() const { ostringstream os; os << *this; diff --git a/cpp/src/qpid/Url.h b/cpp/src/qpid/Url.h index 0cf54c493e..5cdd30399b 100644 --- a/cpp/src/qpid/Url.h +++ b/cpp/src/qpid/Url.h @@ -52,6 +52,14 @@ typedef boost::variant Address; /** An AMQP URL contains a list of addresses */ struct Url : public std::vector
{ + + /** Url with the hostname as returned by gethostname(2) */ + static Url getHostnameUrl(uint16_t port); + + /** Url with local IP address(es), may be more than one address + * on a multi-homed host. */ + static Url getIpAddressesUrl(uint16_t port); + struct InvalidUrl : public Exception { InvalidUrl(const std::string& s) : Exception(s) {} }; -- cgit v1.2.1