Go to the documentation of this file.00001
00021 #include <winsock2.h>
00022 #include <ws2tcpip.h>
00023 #include <iphlpapi.h>
00024
00025 #pragma comment(lib, "iphlpapi.lib")
00026 #pragma comment(lib, "ws2_32.lib")
00027
00028 #include <coil/Routing.h>
00029 #include <coil/stringutil.h>
00030 #include <coil/config_coil.h>
00031
00032 #define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
00033 #define FREE(x) HeapFree(GetProcessHeap(), 0, (x))
00034
00035 namespace coil
00036 {
00037
00038 class Winsock
00039 {
00040 public:
00041 Winsock() {
00042 WSADATA wsaData;
00043 int iResult;
00044 iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
00045 }
00046 virtual ~Winsock()
00047 {
00048 WSACleanup();
00049 }
00050 };
00051
00059 bool dest_to_endpoint(std::string dest_addr, std::string& endpoint)
00060 {
00061 Winsock winsock;
00062 {
00063 struct hostent* hp;
00064 hp = ::gethostbyname(dest_addr.c_str());
00065 if (hp == 0) { return false; }
00066
00067 int i(0);
00068 while (hp->h_addr_list[i] != 0)
00069 {
00070 if(hp->h_addrtype == AF_INET)
00071 {
00072 struct sockaddr_in addr;
00073 memset((char*)&addr, 0, sizeof(addr));
00074 memcpy((char*)&addr.sin_addr, hp->h_addr_list[i], hp->h_length);
00075 dest_addr = inet_ntoa(addr.sin_addr);
00076 break;
00077 }
00078 ++i;
00079 }
00080 }
00081
00082 UINT ipaddress(inet_addr(dest_addr.c_str()));
00083 if (ipaddress == INADDR_NONE) { return false; }
00084
00085 DWORD bestifindex;
00086 if (NO_ERROR != GetBestInterface(ipaddress, &bestifindex)) { return false; }
00087
00088 PMIB_IPADDRTABLE ipaddr_table;
00089 ipaddr_table = (MIB_IPADDRTABLE *) MALLOC(sizeof (MIB_IPADDRTABLE));
00090 if (ipaddr_table == 0) { return false; }
00091
00092
00093
00094 DWORD size(0);
00095 if (GetIpAddrTable(ipaddr_table, &size, 0) == ERROR_INSUFFICIENT_BUFFER)
00096 {
00097 FREE(ipaddr_table);
00098 ipaddr_table = (MIB_IPADDRTABLE *) MALLOC(size);
00099 }
00100 if (ipaddr_table == 0) { return false; }
00101 if (GetIpAddrTable(ipaddr_table, &size, 0) != NO_ERROR) { return false; }
00102
00103 for (int i(0); i < (int) ipaddr_table->dwNumEntries; ++i)
00104 {
00105 if (bestifindex == ipaddr_table->table[i].dwIndex)
00106 {
00107 IN_ADDR inipaddr;
00108 inipaddr.S_un.S_addr = (u_long) ipaddr_table->table[i].dwAddr;
00109 endpoint = inet_ntoa(inipaddr);
00110 return true;
00111 }
00112 }
00113 return false;
00114 }
00115
00116
00117 };