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

How to get domain ip address using domain name in C++?

本文关键字:获取 域名 ip 地址 C++      更新时间:2023-10-16

我使用的是visual c++,

我想从域名中获取一个域ip地址。。我该怎么弄。。我已经试过gethostbyname函数。。。这是我的代码。。。

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

但是我的ip地址不对。

以下是我有时觉得很方便的一个小实用程序的完整源代码(我将其命名为"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