source: trunk/FACT++/src/Dim.cc@ 10652

Last change on this file since 10652 was 10645, checked in by tbretz, 14 years ago
New namespace to host some common Dim helper functions.
File size: 1.9 KB
Line 
1#include "Dim.h"
2
3#include <netdb.h>
4#include <sys/types.h>
5#include <sys/socket.h>
6#include <arpa/inet.h>
7
8#include <iostream>
9
10using namespace std;
11
12string Dim::GetLocalIp()
13{
14 const char *kDnsIp = getenv("DIM_DNS_NODE");
15
16 struct addrinfo hints, *servinfo, *p;
17
18 memset(&hints, 0, sizeof hints);
19 hints.ai_family = AF_INET; //AF_UNSPEC; // use AF_INET6 to force IPv6
20 hints.ai_socktype = SOCK_STREAM;
21
22 int rv;
23 if ((rv = getaddrinfo(kDnsIp, NULL, &hints, &servinfo)) != 0)
24 {
25 cout << "WARNING - getaddrinfo: " << gai_strerror(rv) << endl;
26 return kDnsIp;
27 }
28
29 // loop through all the results and connect to the first we can
30 for (p=servinfo; p; p=p->ai_next)
31 {
32 const int sock = socket(AF_INET, SOCK_DGRAM, 0);
33 if (sock==-1)
34 continue;
35
36 if (connect(sock, p->ai_addr, p->ai_addrlen)==-1)
37 {
38 cout << "WARNING - connect: " << strerror(errno) << endl;
39 close(sock);
40 continue;
41 }
42
43 sockaddr_in name;
44 socklen_t namelen = sizeof(name);
45 if (getsockname(sock, (sockaddr*)&name, &namelen)==-1)
46 {
47 cout << "WARNING - getsockname: " << strerror(errno) << endl;
48 close(sock);
49 continue;
50 }
51
52 char buffer[16];
53 if (!inet_ntop(AF_INET, &name.sin_addr, buffer, 16))
54 {
55 cout << "WARNING - inet_ntop: " << strerror(errno) << endl;
56 close(sock);
57 continue;
58 }
59
60 close(sock);
61
62 freeaddrinfo(servinfo); // all done with this structure
63
64 cout << "DIM_HOST_NODE=" << buffer << endl;
65 return buffer;
66 }
67
68 freeaddrinfo(servinfo); // all done with this structure
69
70 return kDnsIp;
71}
72
73void Dim::Setup(const std::string &dns)
74{
75 setenv("DIM_DNS_NODE", dns.c_str(), 1);
76 setenv("DIM_HOST_NODE", GetLocalIp().c_str(), 1);
77}
Note: See TracBrowser for help on using the repository browser.