/**********************************************************************
 
	Copyright (C) 2003 Hirohisa MORI <joshua@nichibun.ac.jp>
 
	This program is free software; you can redistribute it 
	and/or modify it under the terms of the GLOBALBASE 
	Library General Public License (G-LGPL) as published by 

	http://www.globalbase.org/
 
	This program is distributed in the hope that it will be 
	useful, but WITHOUT ANY WARRANTY; without even the 
	implied warranty of MERCHANTABILITY or FITNESS FOR A 
	PARTICULAR PURPOSE.

**********************************************************************/


#include	<netdb.h>
#include	"task.h"
#include	"memory_debug.h"
#include	"netutils.h"

extern SEM netutils_lock;

int
get_localhostip()
{
static int ret_ip;
struct hostent * hp;
char ** q;
int len;
int ret;

	lock_task(netutils_lock);
	if ( ret_ip ) {
		unlock_task(netutils_lock,"get_localhostip");
		return ret_ip;
	}
	sethostent_rr(0);
	for ( ; ; ) {
		hp = gethostent_rr();
		if ( hp == 0 ) {
			endhostent_rr();
			ret_ip = 0x7f000001;
			break;
		}
		q = hp->h_aliases;
		for ( ; *q ; q ++ ) {
			if ( strcmp((*q),"localhost") == 0 ) {
				q = 0;
				break;
			}
			if ( strcmp((*q),"loghost")
					== 0 )
				break;
		}
		if ( q == 0 )
			continue;
		if ( *q == 0 )
			continue;
		ret_ip = ntohl(*(int*)hp->h_addr_list[0]);
		endhostent_rr();
		break;
	}
	unlock_task(netutils_lock,"get_localhostip");

	return ret_ip;
}
