Re: [PLUG] determining my IP address in C

Tobias DiPasquale on 3 Mar 2004 13:57:02 -0000


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: [PLUG] determining my IP address in C


On Wed, 2004年03月03日 at 08:14, Jeff Abrahamson wrote:
> I want to determine my own IP address.
> 
> A kludgy way is to bind to a high port, send myself (on 127.0.0.1) a
> packet containing only a long random number, and look at the from
> address. Even then I might see 127.0.0.1, though.
> 
> I bet there's a better way. Anyone know?
> 
> If the box has multiple interfaces, the above fails. Is their a way
> to get all the addresses that are me?
A quick trip into UNIX Network Programming tells all...
<code_sample>
[...more #includes here...]
#include	<sys/param.h>
const char *Inet_ntop( int family, 
		 const void *addrptr, 
		 char *strptr, 
		 size_t len)
{
 const char *ptr;
	/* check for old code */
 if (strptr == NULL)
 err_quit( "NULL 3rd argument to inet_ntop");
 if ((ptr = inet_ntop( family, addrptr, strptr, len)) == NULL)
 err_sys( "inet_ntop error");
 return( ptr);
}
char **my_addrs( int *addrtype)
{
	struct hostent	*hptr;
	char		myname[MAXHOSTNAMELEN];
	if (gethostname(myname, sizeof(myname)) < 0)
		return(NULL);
	if ((hptr = gethostbyname(myname)) == NULL)
		return(NULL);
	*addrtype = hptr->h_addrtype;
	return(hptr->h_addr_list);
}
int main( int argc, char **argv)
{
 int addrtype;
 char **pptr, buf[INET6_ADDRSTRLEN];
 if ((pptr = my_addrs( &addrtype)) == NULL)
 err_quit( "my_addrs error");
 for (; *pptr != NULL; pptr++)
 printf( "\taddress: %s\n",
 Inet_ntop( addrtype, *pptr, buf, sizeof( buf)));
 exit(0);
}
</snip>
NOTES: You will have to add some #include macros to make this code work.
Also, you will have to replace err_quit() calls with something that
works (e.g. fprintf( stderr, ...)).
UNIX Network Programming is the ultimate reference for all things UNIX
and network. This book is a bargain at three times the price, due to its
highly-concentrated, no-nonsense,
covers-every-damn-thing-you'd-ever-want-to-know nature. This place has
good prices:
http://www.bookpool.com/.x/dbqfbmkxjr/sm/0131411551
-- 
Tobias DiPasquale, www.cbcg.net
202A 04C4 2CE6 B985 8520 88D6 CD25 1A6C B9B5 1595

Attachment: signature.asc
Description: This is a digitally signed message part




AltStyle によって変換されたページ (->オリジナル) /