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

#define PROGRAM_NAME_IPINFO     "ipinfo"
#define PROGRAM_NAME_IPMATCH    "ipmatch"
#define PROGRAM_RELEASE         "1.2"
#define PROGRAM_RELEASE_DATE    "2004 - 2014"
#define PROGRAM_AUTHOR_NAME     "C. McCohy"
#define PROGRAM_AUTHOR_EMAIL    "mccohy@kyberdigi.cz"
#define PROGRAM_AUTHOR_HOMEPAGE "http://www.kyberdigi.cz/projects/ipinfo/"

#define DISPLAY_CNT        12
#define DISPLAY_IP         0
#define DISPLAY_DECIMAL    1
#define DISPLAY_CLASS      2
#define DISPLAY_NETMASK    3
#define DISPLAY_PREFIX     4
#define DISPLAY_NETWORK    5
#define DISPLAY_WILDCARD   6
#define DISPLAY_BROADCAST  7
#define DISPLAY_IPCOUNT    8
#define DISPLAY_HOSTCOUNT  9
#define DISPLAY_HOSTMIN    10
#define DISPLAY_HOSTMAX    11

#define DISPLAY_VALUES_LEN 32
#define DISPLAY_LEGEND_LEN 32

#define CLASS_CNT          13
#define CLASS_NAMES_LEN    32

#define NETMASK_PREFIX     1
#define NETMASK_LONG       2
#define NETMASK_AUTO       3

#define CHECK_RANGE        0
#define CHECK_NETWORK      1
#define CHECK_HOST         2
#define CHECK_BROADCAST    3

int netmask_values[9] = {0, 128, 192, 224, 240, 248, 252, 254, 255};
int netmask_type = 0, netmask_max = 8;

int class = CLASS_CNT - 1;
unsigned long class_limits[CLASS_CNT] = {
  0,          // 0.0.0.0
  0x1000000,  // 1.0.0.0
  0xa000000,  // 10.0.0.0
  0xb000000,  // 11.0.0.0
  0x7f000000, // 127.0.0.0
  0x80000000, // 128.0.0.0
  0xac100000, // 172.16.0.0
  0xac200000, // 172.32.0.0
  0xc0000000, // 192.0.0.0
  0xc0a80000, // 192.168.0.0
  0xc0a90000, // 192.169.0.0
  0xe0000000, // 224.0.0.0
  0xf0000000  // 240.0.0.0
};
char class_names[CLASS_CNT][CLASS_NAMES_LEN] = {
  "Invalid",
  "A",
  "A (private 10/8)",
  "A",
  "A (localhost)",
  "B",
  "B (private 172.16/12)",
  "B",
  "C",
  "C (private 192.168/16)",
  "C",
  "D (multicast)",
  "E (reserved)"
};
int class_prefix[CLASS_CNT] = {0, 8, 8, 8, 8, 16, 16, 16, 24, 24, 24, 0, 0};

char *int2ip(unsigned long ip) {
  int i, values[4];
  char *result;

  for(i = 0; i < 4; i++)
    values[i] = ((ip >> ((3 - i) * 8)) & 255);

  result=(char *)malloc(16);
  snprintf(result, 16, "%d.%d.%d.%d", values[0], values[1], values[2], values[3]);
  return(result);
}

int out(char *progname, char *errstr) {
  fprintf(stderr, "%s: %s\nTry `%s --help' for more information.\n", progname, errstr, progname);
  exit(1);
}

