2012-07-31 117 views
1

我使用的Visual C++,如何在C++中使用域名獲取域名IP地址?

我想從域名域IP地址.. 我如何得到它.. 我已經嘗試過gethostbyname函數... 這裏我的代碼...

HOSTENT* remoteHost;   
    IN_ADDR addr;  
    hostName = "domainname.com"; 
    printf("Calling gethostbyname with %s\n", hostName); 
remoteHost =gethostbyname(hostName); 
memcpy(&addr.S_un.S_addr, remoteHost->h_addr, remoteHost->h_length); 
printf("The IP address is: %s\n", inet_ntoa(addr)); 

但我得到一個錯誤的IP地址。

+0

什麼是「域名IP地址」?主機具有主機名(這是域名的特例)和主機IP地址,但大多數具有域名的實體沒有IP地址。例如。 .com的IP地址是什麼? – MSalters 2012-07-31 14:32:40

回答

1

這是完整的源代碼到一個我覺得有時有用的小實用程序(我已將它命名爲「resolve」)。它所做的只是將域名解析爲數字IP(v4)地址,然後將其打印出來。原來,它適用於Windows - 對於Linux(或類似的),你只需要擺脫use_WSA類(及其對象)。

#include <windows.h> 
#include <winsock.h> 
#include <iostream> 
#include <iterator> 
#include <exception> 
#include <algorithm> 
#include <iomanip> 
#include "infix_iterator.h" 

class use_WSA { 
    WSADATA d; 
    WORD ver; 
public: 
    use_WSA() : ver(MAKEWORD(1,1)) { 
     if ((WSAStartup(ver, &d)!=0) || (ver != d.wVersion)) 
      throw(std::runtime_error("Error starting Winsock")); 
    } 
    ~use_WSA() { WSACleanup(); }  
}; 

int main(int argc, char **argv) { 
    if (argc < 2) { 
     std::cerr << "Usage: resolve <host-name>"; 
     return EXIT_FAILURE; 
    } 

    try { 
     use_WSA x; 

     hostent *h = gethostbyname(argv[1]); 
     unsigned char *addr = reinterpret_cast<unsigned char *>(h->h_addr_list[0]); 
     std::copy(addr, addr+4, infix_ostream_iterator<unsigned int>(std::cout, ".")); 
    } 
    catch (std::exception const &exc) { 
     std::cerr << exc.what() << "\n"; 
     return EXIT_FAILURE; 
    } 

    return 0; 
} 

這也使用我以前發佈的infix_ostream_iterator