这是我有时觉得很方便的一个小实用程序的完整源代码(我将其命名为“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
我之前发布的。