如何在C++中使用域名获取域ip地址
How to get domain ip address using domain name in C++?
我使用的是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
。
相关文章:
- C++为构建时间获取QDateTime的可靠方法
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 使用指针从C++中的数组中获取最大值
- 如何获取std::result_of函数的返回类型
- 如何在openssl-ecc中获取十六进制格式的私钥
- 使用Unreal C++获取VR耳机的世界位置/方向
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 从C字符串中获取奇怪的字符串长度
- 为什么我的for循环不能正确获取argv
- 从python中调用C++函数并获取返回值
- 如何获取一个数字的前3位
- 获取字符串的长度并将其分配给数组
- 无法获取菜单选择以运行函数.C++
- 是否有任何窗口函数可以使用域名获取所有OU(组织单位)名称
- 如何从非管理员用户获取当前登录的用户名、域名和用户 sid
- 如何在C++中使用域名获取域ip地址
- 获取传入连接的域名
- 如何在 C++ 中获取 IP 地址的域名
- 如何在mongoose服务器c++中获取域名