如何在C ++中使用域名获取域名IP地址?

时间:2012-07-31 09:30:03

标签: c++

我正在使用visual c ++,

我想从域名获取域名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地址。

1 个答案:

答案 0 :(得分: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