win32/coil/Routing.cpp
Go to the documentation of this file.
1 // -*- C++ -*-
20 #ifndef NTDDI_VERSION
21 #define NTDDI_VERSION 0x05000000
22 #define WINVER _WIN32_WINNT
23 #ifdef _WIN32_WINNT
24 #undef _WIN32_WINNT
25 #endif // _WIN32_WINNT
26 #define _WIN32_WINNT 0x0500
27 #define _WIN32_WINDOWS _WIN32_WINNT
28 #define _WIN32_IE 0x0501
29 #endif // NTDDI_VERSION
30 
31 #include <winsock2.h>
32 #include <ws2tcpip.h>
33 #include <iphlpapi.h>
34 
35 #pragma comment(lib, "iphlpapi.lib")
36 #pragma comment(lib, "ws2_32.lib")
37 
38 #include <coil/Routing.h>
39 #include <coil/stringutil.h>
40 #include <coil/config_coil.h>
41 
42 #define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
43 #define FREE(x) HeapFree(GetProcessHeap(), 0, (x))
44 
45 namespace coil
46 {
47  // Winsock initializer
48  class Winsock
49  {
50  public:
51  Winsock() {
52  WSADATA wsaData;
53  int iResult;
54  iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
55  }
56  virtual ~Winsock()
57  {
58  WSACleanup();
59  }
60  };
61 
69  bool dest_to_endpoint(std::string dest_addr, std::string& endpoint)
70  {
71  Winsock winsock;
72  {
73  struct hostent* hp;
74  hp = ::gethostbyname(dest_addr.c_str());
75  if (hp == 0) { return false; }
76 
77  int i(0);
78  while (hp->h_addr_list[i] != 0)
79  {
80  if(hp->h_addrtype == AF_INET)
81  {
82  struct sockaddr_in addr;
83  memset((char*)&addr, 0, sizeof(addr));
84  memcpy((char*)&addr.sin_addr, hp->h_addr_list[i], hp->h_length);
85  dest_addr = inet_ntoa(addr.sin_addr);
86  break;
87  }
88  ++i;
89  }
90  }
91 
92  UINT ipaddress(inet_addr(dest_addr.c_str()));
93  if (ipaddress == INADDR_NONE) { return false; }
94 
95  DWORD bestifindex;
96  if (NO_ERROR != GetBestInterface(ipaddress, &bestifindex)) { return false; }
97 
98  PMIB_IPADDRTABLE ipaddr_table;
99  ipaddr_table = (MIB_IPADDRTABLE *) MALLOC(sizeof (MIB_IPADDRTABLE));
100  if (ipaddr_table == 0) { return false; }
101 
102  // Make an initial call to GetIpAddrTable to get the
103  // necessary size into the size variable
104  DWORD size(0);
105  if (GetIpAddrTable(ipaddr_table, &size, 0) == ERROR_INSUFFICIENT_BUFFER)
106  {
107  FREE(ipaddr_table);
108  ipaddr_table = (MIB_IPADDRTABLE *) MALLOC(size);
109  }
110  if (ipaddr_table == 0) { return false; }
111  if (GetIpAddrTable(ipaddr_table, &size, 0) != NO_ERROR) { return false; }
112 
113  for (int i(0); i < (int) ipaddr_table->dwNumEntries; ++i)
114  {
115  if (bestifindex == ipaddr_table->table[i].dwIndex)
116  {
117  IN_ADDR inipaddr;
118  inipaddr.S_un.S_addr = (u_long) ipaddr_table->table[i].dwAddr;
119  endpoint = inet_ntoa(inipaddr);
120  return true;
121  }
122  }
123  return false;
124  }
125 
126 
127 }; // namespace coil
#define MALLOC(x)
#define FREE(x)
bool dest_to_endpoint(std::string dest_addr, std::string &endpoint)
Getting network interface name from destination address.
Common Object Interface Layer.


openrtm_aist
Author(s): Noriaki Ando
autogenerated on Mon Feb 28 2022 23:00:44