Click here to Skip to main content
15,891,629 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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
C++
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);
Posted
Updated 1-Jul-18 13:46pm
v2

1 solution

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.
 
Share this answer
 
Comments
[no name] 2-Jul-18 4:29am    
Chances are, if you link me to code, I've already seen it. In this case, I've already tried that code, and I can't remember the result but it was either 0.0.0.0 or nothing.
Jochen Arndt 2-Jul-18 4:51am    
I told you also that you are accessing a NULL pointer (at least in the posted code). What I have seen is that you have seen the example code and modified it in a way that it does not work.

Please note that all I can see is what you have posted. But you can try more like checking the return value. If the result is 0.0.0.0, that should be non zero.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900