解决主机名到ip的不必要的艰巨任务 [英] Unnecessarily difficult task of resolving hostname to ip

查看:63
本文介绍了解决主机名到ip的不必要的艰巨任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我正在做一件噩梦,在C ++中如此简单。我想要做的就是输入一个主机名,并获取其IP地址。这不是需要花费数小时才能完成的事情。



无论我使用弃用的gethostbyname()还是getaddrinfo(),都没有用。 gethostbyname()返回0.0.0.0,这显然是错误的,并且getaddrinfo()根本不返回任何内容。我不想使用已弃用的代码,但无论如何都不行。



我尝试了什么:



我已经尝试过了,相同代码的许多不同变体,现在超过20个。最新的是

Hi,

I'm having a nightmare doing something so, so simple in C++. All I want to do is input a hostname, and get its IP address. It is not something which should take hours and hours to work out.

Regardless whether I use the deprecated gethostbyname() or getaddrinfo(), nothing works. gethostbyname() returns 0.0.0.0, which is obviously wrong, and getaddrinfo() doesn't return anything at all. I don't want to use deprecated code, but neither works anyway.

What I have tried:

I've tried so, so many different variations of the same code, in excess of 20 by now. The most recent is

struct addrinfo hints {}, *res{}, *res0{};
		
		memset(&hints, 0, sizeof(hints));
		hints.ai_family = AF_UNSPEC;
		hints.ai_socktype = SOCK_STREAM;
		getaddrinfo("www.google.com", "http", &hints, &res0);
		ip_address = res->ai_addr->sa_data;
		freeaddrinfo(res0);

推荐答案

我希望访问违规,因为你传递 res0 但访问 res



如果某个功能未按预期工作,首先要做的是检查返回值(无论如何应该这样做)并重新阅读文档( getaddrinfo函数| Microsoft Docs [ ^ ], getaddrinfo( 3) - Linux手册页 [ ^ ])通常包含示例代码。
I would expect an access violation because you are passing res0 but accesses res.

If a function is not working as expected, the first thing to do is to check the return value (which should be done anyway) and re-read the documentation (getaddrinfo function | Microsoft Docs[^], getaddrinfo(3) - Linux manual page[^]) which usually contains example code.


这篇关于解决主机名到ip的不必要的艰巨任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆