Novell Home

BSD gethost functions

From Developer Community

Demonstrates calls: gethostbyname, gethostname, gethostbyaddr calls from CLIB's BSD functions.

Sample Code

//if the following is not defined just the host file will be checked!!
#define NETDB_USE_INTERNET 
#include <stdio.h>
#include <nwthread.h> //for ResumeThread, ThreadSwitchWithDelay, GetThreadID
#include <signal.h>  //for SIGTERM, signal
#include <sys/types.h> //for gethostbyname
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h> //for in_addr
#include <arpa/inet.h> //for inet_ntoa and inet_addr
#include <netdb.h> //for NETDB res functions
#include <malloc.h> //for malloc and free
#include <errno.h> //errno


NETINET_DEFINE_CONTEXT // for inet_ntoa
NETDB_DEFINE_CONTEXT  // for ? but it is needed

int NLM_exiting = FALSE;
int NLM_threadCnt = 0;
int NLM_mainThreadID = 0;

void NLM_signalHandler(int sig)
{
	switch (sig)
	{
		case SIGTERM:
			NLM_exiting = TRUE;
			ResumeThread(NLM_mainThreadID);
			while (NLM_threadCnt != 0)
				ThreadSwitchWithDelay();
			break;
	}
 	return;
}

int main (int argc, char **argv)
{
	struct hostent *hostent2;
	struct in_addr serverAddr;
	struct hostent *hostent1;
	
	memset((char *)&serverAddr, 0, sizeof(struct in_addr));
	
	if(argc != 3)
	{
	   printf("Usage: %s <www> <ip>\r\n", argv[0]);
	   return (-1);
	}
		
/*
 * setup for proper unload of nlm
 * includes catching SIGTERM (unload)
 */
	++NLM_threadCnt;
	NLM_mainThreadID = GetThreadID();
	signal(SIGTERM, NLM_signalHandler);

	printf("starting gethostbyname()\r\n");
    hostent1 = gethostbyname(argv[1]);	
	if(hostent1 == NULL){
		printf("gethostbyname failed with %d\r\n", errno);
	}
	else{
		memset((char *)&serverAddr, 0, sizeof(struct in_addr));
		serverAddr.s_addr = * (u_long *)hostent1->h_addr_list[0];
		printf("hostAddr: %s\r\n", inet_ntoa(serverAddr));
		printf("gethostbyname success\r\n");
	}
    
	serverAddr.s_addr = inet_addr(argv[2]);

	printf("\r\nstarting gethostbyaddr()\r\n");
	hostent2 = gethostbyaddr((char *)&serverAddr, sizeof(serverAddr), AF_INET);


	if(hostent2 == NULL){
		printf("gethostbyaddr failed with %d\r\n", h_errno);
	}
	else{
		printf("hostname: %s\r\n", hostent2->h_name);
		printf("gethostbyaddr success\r\n");
	}

	--NLM_threadCnt;
	return 0;
}

--Benjamin Fjeldsted

Novell® Making IT Work As One

© 2008 Novell, Inc. All Rights Reserved.