*BSD News Article 43929


Return to BSD News archive

Path: sserve!newshost.anu.edu.au!harbinger.cc.monash.edu.au!simtel!zombie.ncsc.mil!news.mathworks.com!usenet.eel.ufl.edu!jfh
From: jfh@ucet.ufl.edu ()
Newsgroups: comp.unix.bsd.freebsd.misc
Subject: Re: IP address of local machine
Date: 12 May 1995 12:40:08 GMT
Organization: IBM Writing Laboratory, University of Florida
Lines: 45
Message-ID: <3ovkv8$ejc@huron.eel.ufl.edu>
References: <D8Fs2t.Cr7@mv.mv.com>
NNTP-Posting-Host: trinh.ucet.ufl.edu

In article <D8Fs2t.Cr7@mv.mv.com> shaman@mv.mv.com (Coranth Gryphon) writes:

>The function "gethostbyname" returns a "struct hostent" which
>has the "h_addr" field. All well and good. However the bytes
>in this 4-byte string seem to have no relation to my ip address.
>
>The functions for converting between ip-addr-number and dot-form
>take a "struct in_addr". But I cannot find anything to convert
>from a hostent to an in_addr.

What a coincidence...I just ran into the same oddity.

It seems that h_addr (a macro for h_addr_list[0] on my machine) is
actually returned as a char* (why ?!?). But, it needs to be a 
struct in_addr for inet_ntoa...so, you need to cast h_addr to

	(struct in_addr) h_addr 

	or

	(struct in_addr) hostEntry->h_addr_list[whatever]

But, my compiler wouldn't let me do this...I had to cast the char *
to an in_addr * like:

	(struct in_addr *) hostEntry->h_addr_list[0]

Ick. Almost done...inet_ntoa wants an in_addr, so just dereference that:

	*( (struct in_addr *) hostEntry->h_addr_list[0] )

	or easier:

	struct in_addr *address = (struct in_addr *) hostEntry->h_addr_list[0];
	inet_ntoa(*address);

and there you are.

I have no idea why this convoluted scheme is necessary...why not just
return an array of unsigned longs instead of char *'s??
-- 
-------------------------------------------------------------------------------
| Jim Hranicky                                             Assistant Sysadmin |
| IBM Writing Laboratory       jfh@ucet.ufl.edu         University of Florida |
-------------------------------------------------------------------------------