/*
 *  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.
 *
 *  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.  See the
 *  GNU Library 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include <net/if.h>
#include <sys/ioctl.h>
#include <unistd.h>

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

#include "iface.h"

#include "./include/wrapper.h"

int getaddrbyif(const char *ifname, struct sockaddr *sock_addr) {
/* -----------------------------------------------------------------------------
 * Get IP address from interface name
 *
 * @param char *, Name interface
 * @param sockaddr *, a "reference" to a sock_addr structure 
 * @return int
 * -------------------------------------------------------------------------- */
  struct ifreq ifr;
  int fd;
  
  /* Open a dummy socket */
  if ((fd = socket(PF_INET, SOCK_DGRAM, 0)) < 0)
    return 0;
  
  memset(&ifr, 0, sizeof(struct ifreq));
  strlcpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
  if (ioctl(fd, SIOCGIFADDR, &ifr) >= 0) {
    if (ifr.ifr_addr.sa_family == AF_INET) {
      memcpy(sock_addr, &ifr.ifr_addr, sizeof(struct sockaddr_in));
      close(fd);
      return 1;
    }
  }
  close(fd);
  return 0;
}

int getaddrbyname(char **ip, const char *hostname) {
/* -----------------------------------------------------------------------------
 * Get IP address from hostname
 *
 * @param char **, IP address to get
 * @param const char *, hostname to resolve
 * @return int
 * -------------------------------------------------------------------------- */
  struct addrinfo hints, *res = NULL;
  int err;
  
  memset(&hints, 0, sizeof(struct addrinfo));
  hints.ai_family = PF_UNSPEC;
  hints.ai_socktype = SOCK_STREAM;
  
  err = getaddrinfo(hostname, NULL, &hints, &res);
  if (err) {
    logmsg(LOG_ERR, "getaddrbyname() : %s", gai_strerror(err));
    return 0;
  }
  
  if (res->ai_family == PF_INET) {
  /* We grab only the first address */
    *ip = strdup(inet_ntoa(((struct sockaddr_in *)res->ai_addr)->sin_addr));
    freeaddrinfo(res);
    if (*ip != NULL)
      return 1;
  }
  else
    freeaddrinfo(res);
  return 0;
}



syntax highlighted by Code2HTML, v. 0.9.1