// ************************************************************************** /** @namespace Dim @brief Namespace to host some global Dim helper functions */ // ************************************************************************** #include "Dim.h" #include #include #include #include #include using namespace std; // -------------------------------------------------------------------------- // //! Tries to determine the local IP address with which we will connect //! to the DIM dns. //! //! @param dns //! Address of the Dim-dns //! //! @returns //! The IP Address through which the connection to the DNS will //! take place. //! string Dim::GetLocalIp(const string &dns) { struct addrinfo hints, *servinfo, *p; memset(&hints, 0, sizeof hints); hints.ai_family = AF_INET; //AF_UNSPEC; // use AF_INET6 to force IPv6 hints.ai_socktype = SOCK_STREAM; int rv; if ((rv = getaddrinfo(dns.c_str(), NULL, &hints, &servinfo)) != 0) { cout << "WARNING - getaddrinfo: " << gai_strerror(rv) << endl; return dns; } // loop through all the results and connect to the first we can for (p=servinfo; p; p=p->ai_next) { const int sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock==-1) continue; if (connect(sock, p->ai_addr, p->ai_addrlen)==-1) { cout << "WARNING - connect: " << strerror(errno) << endl; close(sock); continue; } sockaddr_in name; socklen_t namelen = sizeof(name); if (getsockname(sock, (sockaddr*)&name, &namelen)==-1) { cout << "WARNING - getsockname: " << strerror(errno) << endl; close(sock); continue; } char buffer[16]; if (!inet_ntop(AF_INET, &name.sin_addr, buffer, 16)) { cout << "WARNING - inet_ntop: " << strerror(errno) << endl; close(sock); continue; } close(sock); freeaddrinfo(servinfo); // all done with this structure cout << "DIM_HOST_NODE=" << buffer << endl; return buffer; } freeaddrinfo(servinfo); // all done with this structure return dns; } // -------------------------------------------------------------------------- // //! Set the environment variable DIM_DNS_NODE to the given string and //! DIM_HOST_NODE to the IP-address through which this machine connects //! to the dns. //! //! @param dns //! Address of the Dim-dns //! void Dim::Setup(const std::string &dns) { setenv("DIM_DNS_NODE", dns.c_str(), 1); setenv("DIM_HOST_NODE", GetLocalIp(dns).c_str(), 1); }