#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <ifaddrs.h>
#include <errno.h>

/**
 * This is a small c program to determine the 
 * hosts own outward facing ip address.
 * For now we rely on the fact that the 
 * name of the primary network interface doesn't begin
 * with either 'vm' or 'lo'.
 */
int main(int argc, char *argv[])
{

  char *vm, *lo;
  vm = "vm";
  lo = "lo";
  struct ifaddrs *myaddrs, *ifa;
  void *in_addr;
  char buf[64];

  if(getifaddrs(&myaddrs) != 0)
    {
      perror("getifaddrs");
      exit(1);
    }

  for (ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next)
    {
      if (ifa->ifa_addr == NULL)
	continue;
      if (!(ifa->ifa_flags & IFF_UP))
	continue;

      if (ifa->ifa_addr->sa_family == AF_INET)
	{

          struct sockaddr_in *s4 = (struct sockaddr_in *)ifa->ifa_addr;
	    in_addr = &s4->sin_addr;
	    
	}
      else
	{
	  continue;
	}
      
      if (!inet_ntop(ifa->ifa_addr->sa_family, in_addr, buf, sizeof(buf)))
        {
	  printf("%s: inet_ntop failed!\n", ifa->ifa_name);
        }
      else if(!(strncmp(ifa->ifa_name, vm, 2)==0 || strncmp(ifa->ifa_name,lo,2)==0)) 
        {
	  printf("%s", /*ifa->ifa_name,*/ buf);
        }
    }

  freeifaddrs(myaddrs);
  return 0;
}
