/*
   cipelib - library routines common to CIPE (user-mode part) and PKCIPE

   Copyright 2000 Olaf Titz <olaf@bigred.inka.de>

   This program 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
   2 of the License, or (at your option) any later version.
*/
/* $Id: getaddr.c,v 1.3 2000/11/22 20:23:38 olaf Exp $ */

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cipelib.h"

int getaddr(const char *c, struct sockaddr_in *sa, const char *prot)
{
    struct hostent *h;
    struct servent *s;
    char *q=strchr(c, ':');

    sa->sin_family=AF_INET;
    sa->sin_port=0;
    sa->sin_addr.s_addr=htonl(INADDR_ANY);
    if (q) {
	if (!prot) {
	    cipe_syslog(LOG_ERR,
                        "getaddr: raw IP address has no port number");
	    return -1;
	}
	*q++='\0';
	if (!(sa->sin_port=htons(atoi(q)))) {
	    if ((s=getservbyname(q, prot)))
		sa->sin_port=s->s_port;
	    else {
		cipe_syslog(LOG_ERR,
                            "getaddr: port '%s' invalid/not found", q);
		return -1;
	    }
	}
    }
    if (!*c) {
	sa->sin_addr.s_addr=htonl(INADDR_LOOPBACK);
	return 0;
    }
    if ((sa->sin_addr.s_addr=inet_addr(c))==-1) {
	if ((h=gethostbyname(c)))
	    memcpy(&sa->sin_addr.s_addr, h->h_addr_list[0],
		   sizeof(sa->sin_addr.s_addr));
	else {
	    cipe_syslog(LOG_ERR, "getaddr: host '%s' invalid/not found", c);
	    return -1;
	}
    }
    return 0;
}
