I've written a simple program returning the hostname of the IP address passed as an argument. The program uses two functions: getaddrinfo() and getnameinfo(). I'm using Linux Mint, Netbeans IDE and the G++ compiler. The output is alright, there are no errors, but when I declare an
std::string str;
then cout gives no output, nothing is printed on the screen. However when I comment out the std::string declaration or remove it, the statement
std::cout << "hostname: " << hostname << std::endl;
prints the returned hostnames successfully.
What may be the cause of such a strange error?
#include <netdb.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <iostream>
#include <string>
int main()
{
struct addrinfo* result;
struct addrinfo* res;
int error;
const char* host;
// When I comment out this line, cout prints the hostnames succesfully.
std::string str;
error = getaddrinfo("127.0.0.1", NULL, NULL, &result);
res = result;
while (res != NULL)
{
char* hostname;
error = getnameinfo(res->ai_addr, res->ai_addrlen, hostname, 1025, NULL, 0, 0);
std::cout << "hostname: " << hostname << std::endl;
res = res->ai_next;
}
freeaddrinfo(result);
// When I declare an std::string str variable, this cout doesn't either print anything
std::cout << "TEST" << std::endl;
return 0;
}
hostnameneeds allocated memory.char *and hope it points somewhere sensible. Look at this example for some inspiration.