/*
 * Copyright (c) 2021, Erich Styger
 *
 * SPDX-License-Identifier: BSD-3-Clause
 */

/* taken from https://www.binarytides.com/hostname-to-ip-address-c-sockets-linux/ */
#include "hostname.h" /* own interface */
#include <stdio.h> /* printf */
#include <string.h> /* memset */
#include <stdlib.h> /* for exit(0); */
#include <sys/socket.h>
#include <errno.h> /* For errno - the error number */
#include <netdb.h> /* hostent */
#include <arpa/inet.h>

/* Get ip from domain name */
int hostname_to_ip(const char *hostname, char *ipBuf, size_t ipBufLen) {
 struct hostent *he;
 struct in_addr **addr_list;
 int i;

 if ((he = gethostbyname(hostname)) == NULL) {
  /* get the host info */
  herror("gethostbyname");
  return -1;
 }
 addr_list = (struct in_addr **) he->h_addr_list;
 for(i = 0; addr_list[i]!=NULL; i++) {
    /* Return the first one */
    strncpy(ipBuf,  inet_ntoa(*addr_list[i]), ipBufLen);
    ipBuf[ipBufLen-1] = '\0'; /* terminate string */
    return 0;
  }
  return -1;
}
