/*

    File: smtp/ip-lib.c
    Version 1.0
    
    Copyright (C) 1999 by Wolfgang Zekoll <wzk@quietsche-entchen.de>

    This source is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 1, or (at your option)
    any later version.

    This source 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.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

*/

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include <signal.h>

#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <netdb.h>
#include <errno.h>

#include "lib.h"
#include "ip-lib.h"


static void alarm_handler()
{
	return;
}


int openip(char *host, unsigned int port)
{
	int	socketd;
	struct sockaddr_in server;
	struct hostent *hostp, *gethostbyname();

	socketd = socket(AF_INET, SOCK_STREAM, 0);
	if (socketd < 0)
		return (-1);
  
	server.sin_family = AF_INET;
	hostp = gethostbyname(host);
	if (hostp == NULL)
		return (-1);
  
	memcpy(&server.sin_addr, hostp->h_addr, hostp->h_length);
	server.sin_port = htons(port);

	signal(SIGALRM, alarm_handler);
	alarm(10);
	if (connect(socketd, (struct sockaddr *) &server, sizeof(server)) < 0)
		return (-1);

	alarm(0);
	signal(SIGALRM, SIG_DFL);

 	return (socketd);
}	


unsigned int get_port(char *server, unsigned int def_port)
{
	unsigned int port;
	char	*p;

	if ((p = strchr(server, ':')) == NULL)
		return (def_port);

	*p++ = 0;
	port = atol(p);

	return (port);
}

int get_client_info(int pfd, char *ipnum, char *name)
{
	int	size;
	struct sockaddr_in saddr;
	struct in_addr *addr;
	struct hostent *hostp = NULL;

	*ipnum = 0;
	*name  = 0;

	size = sizeof(saddr);
	if (getpeername(pfd, (struct sockaddr *) &saddr, &size) < 0 ) {
		if (isatty(pfd) == 0) {
			strcpy(ipnum, "127.0.0.2");
			strcpy(name, "local.host");
			}

		strcpy(ipnum, "127.0.0.1");
		strcpy(name, "local.host");

		return (0);
		}		
		
	copy_string(ipnum, (char *) inet_ntoa(saddr.sin_addr), 80);
	addr = &saddr.sin_addr,
	hostp = gethostbyaddr((char *) addr,
			sizeof (saddr.sin_addr.s_addr), AF_INET);

	if (hostp == NULL)
		copy_string(name, ipnum, 200);
	else {
		copy_string(name, hostp->h_name, 200);
		strlwr(name);
		}

	return (0);
}



syntax highlighted by Code2HTML, v. 0.9.1