win32/coil/Routing.cpp
Go to the documentation of this file.
1 // -*- C++ -*-
21 #include <winsock2.h>
22 #include <ws2tcpip.h>
23 #include <iphlpapi.h>
24 
25 #pragma comment(lib, "iphlpapi.lib")
26 #pragma comment(lib, "ws2_32.lib")
27 
28 #include <coil/Routing.h>
29 #include <coil/stringutil.h>
30 #include <coil/config_coil.h>
31 
32 #define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
33 #define FREE(x) HeapFree(GetProcessHeap(), 0, (x))
34 
35 namespace coil
36 {
37  // Winsock initializer
38  class Winsock
39  {
40  public:
41  Winsock() {
42  WSADATA wsaData;
43  int iResult;
44  iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
45  }
46  virtual ~Winsock()
47  {
48  WSACleanup();
49  }
50  };
51 
59  bool dest_to_endpoint(std::string dest_addr, std::string& endpoint)
60  {
61  Winsock winsock;
62  {
63  struct hostent* hp;
64  hp = ::gethostbyname(dest_addr.c_str());
65  if (hp == 0) { return false; }
66 
67  int i(0);
68  while (hp->h_addr_list[i] != 0)
69  {
70  if(hp->h_addrtype == AF_INET)
71  {
72  struct sockaddr_in addr;
73  memset((char*)&addr, 0, sizeof(addr));
74  memcpy((char*)&addr.sin_addr, hp->h_addr_list[i], hp->h_length);
75  dest_addr = inet_ntoa(addr.sin_addr);
76  break;
77  }
78  ++i;
79  }
80  }
81 
82  UINT ipaddress(inet_addr(dest_addr.c_str()));
83  if (ipaddress == INADDR_NONE) { return false; }
84 
85  DWORD bestifindex;
86  if (NO_ERROR != GetBestInterface(ipaddress, &bestifindex)) { return false; }
87 
88  PMIB_IPADDRTABLE ipaddr_table;
89  ipaddr_table = (MIB_IPADDRTABLE *) MALLOC(sizeof (MIB_IPADDRTABLE));
90  if (ipaddr_table == 0) { return false; }
91 
92  // Make an initial call to GetIpAddrTable to get the
93  // necessary size into the size variable
94  DWORD size(0);
95  if (GetIpAddrTable(ipaddr_table, &size, 0) == ERROR_INSUFFICIENT_BUFFER)
96  {
97  FREE(ipaddr_table);
98  ipaddr_table = (MIB_IPADDRTABLE *) MALLOC(size);
99  }
100  if (ipaddr_table == 0) { return false; }
101  if (GetIpAddrTable(ipaddr_table, &size, 0) != NO_ERROR) { return false; }
102 
103  for (int i(0); i < (int) ipaddr_table->dwNumEntries; ++i)
104  {
105  if (bestifindex == ipaddr_table->table[i].dwIndex)
106  {
107  IN_ADDR inipaddr;
108  inipaddr.S_un.S_addr = (u_long) ipaddr_table->table[i].dwAddr;
109  endpoint = inet_ntoa(inipaddr);
110  return true;
111  }
112  }
113  return false;
114  }
115 
116 
117 }; // 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 Jun 10 2019 14:07:54