gethostbyname

gethostbyname() is a socket library function that looks up the IPV4 address of a computer from it’s name.

Every now and then someone asks how to call gethostbyname().  The description is here: http://pubs.opengroup.org/onlinepubs/007908799/xns/gethostname.html

Here’s an example.

#ifdef _WIN32
	#include <WinSock2.h>
	#include <WS2tcpip.h>
	typedef unsigned uint32_t;
#else
	#include <netdb.h>
	#include <arpa/inet.h>
	#include <netinet/in.h>
	#include <sys/socket.h>  // BSD needs this
#endif

#include <iostream>
#include <string>
#include <stdexcept>
#include <vector>

typedef std::vector<std::string> strings_t;

strings_t getip(std::string hostname) 
{
	if (struct hostent* hent = gethostbyname(hostname.c_str()))
	{
		if (hent->h_addrtype == AF_INET  &&  hent->h_length == sizeof(uint32_t))
		{
			strings_t hosts;

			for (int i = 0; hent->h_addr_list[i]; ++i)
			{
				struct in_addr addr = { 0 };
				addr.s_addr = *(uint32_t*)hent->h_addr_list[i];
				hosts.push_back(inet_ntoa(addr));
			}
			return hosts;
		}

		std::string text = "cannot find ip4 address for host:" + hostname;
		throw std::runtime_error(text);
	}

	std::string text = "cannot find ip address for host:" + hostname;
	throw std::runtime_error(text);
}

int main()
{
#ifdef _WIN32
	WSADATA wsadata = { 0 };
	WSAStartup(MAKEWORD(2, 2), &wsadata);
#endif

	std::string line;
	while (std::cin >> line)
	{
		try
		{
			strings_t hosts = getip(line);
			for (strings_t::const_iterator p = hosts.begin(); p != hosts.end(); ++p)
				std::cout << *p << std::endl;
		}
		catch (const std::exception &e)
		{
			std::clog << e.what() << std::endl;
		}
	}

	return 0;
}
Advertisements

~ by kbw333 on July 19, 2012.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: