/* doscan - Denial Of Service Capable Auditing of Networks
 * Copyright (C) 2003 Florian Weimer
 *
 * 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 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 "config.h"
#include "ipv4.h"

#include <cstdio>

int
ipv4_string_to_address (const char *source, ipv4_t *result)
{
  unsigned a, b, c, d;

  if (sscanf(source, "%u.%u.%u.%u", &a, &b, &c, &d) != 4) {
    return 0;
  }
  if ((a > 255) || (b > 255) || (c > 255) || (d > 255)) {
    return 0;
  }

  *result = (a << 24) | (b << 16) | (c << 8) | d;
  return 1;
}

void
ipv4_address_to_string (ipv4_t source, ipv4_string_t result)
{
  unsigned a, b, c, d;
  a = source >> 24;
  b = (source >> 16) & 0xFF;
  c = (source >> 8) & 0xFF;
  d = source & 0xFF;

  sprintf (result, "%u.%u.%u.%u", a, b, c, d);
}

int
ipv4_string_to_prefix (const char *source, ipv4_prefix_t *result)
{
  unsigned a, b, c, d, l;

  if (sscanf(source, "%u.%u.%u.%u/%u", &a, &b, &c, &d, &l) != 5) {
    return 0;
  }
  if ((a > 255) || (b > 255) || (c > 255) || (d > 255) || (l > 32)) {
    return 0;
  }

  result->network = (a << 24) | (b << 16) | (c << 8) | d;
  result->length = l;
  return 1;
}

void
ipv4_prefix_to_string (const ipv4_prefix_t *source, char *result)
{
  unsigned a, b, c, d;
  a = source->network >> 24;
  b = (source->network >> 16) & 0xFF;
  c = (source->network >> 8) & 0xFF;
  d = source->network & 0xFF;

  sprintf (result, "%u.%u.%u.%u/%u", a, b, c, d, (unsigned)source->length);
}
