Commits

Palmer, 2E0EOL committed e148ef3

Code from cidr-0.3.0 Subversion tag, with cruft stripped and binaries removed where practical.
Although there is a binary .res I need to convert to .rc somehow.

  • Participants
  • Tags cidr-0.3.0

Comments (0)

Files changed (22)

+0.3 - Add netmask output
+
+0.2 - Fix bit counting bug from going in the wrong direction
+
+0.1 - Initial release
+$Id: LICENSE,v 0.1 2003/04/20 20:33:00 ddrp Exp $
+
+Copyright (C) 2003 Daybo Logic.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+1. Redistributions of source code must retain the above copyright
+   notice, this list of conditions and the following disclaimer.
+2. Redistributions in binary form must reproduce the above copyright
+   notice, this list of conditions and the following disclaimer in the
+   documentation and/or other materials provided with the distribution.
+3. Neither the name of the project nor the names of its contributors
+   may be used to endorse or promote products derived from this software
+   without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGE.
+OPTIONS=-O2 -s -ansi -pedantic -Wall
+ERASE=rm -f
+STATIC=
+
+all : cidr
+
+cidr : cidr.o cidr_cmd.o
+	$(CC) $(OPTIONS) -o cidr cidr.o cidr_cmd.o $(STATIC)
+
+cidr.o : cidr.c cidr.h cidr_config.h
+	$(CC) -c $(OPTIONS) -o cidr.o cidr.c
+
+cidr_cmd.o : cidr_cmd.c cidr.h cidr_config.h
+	$(CC) -c $(OPTIONS) -o cidr_cmd.o cidr_cmd.c
+
+
+clean:
+	-$(ERASE) cidr.o
+	-$(ERASE) cidr_cmd.o
+	-$(ERASE) cidr
+	-$(ERASE) cidr.core
+	-$(ERASE) core
+
+install : all
+	cp cidr /usr/local/bin/
+
+uninstall : deinstall
+deinstall:
+	rm /usr/local/bin/cidr

File Makefile.bor

+OPTIONS=-O2 -s
+ERASE=erase
+
+all : cidr.exe
+
+cidr.exe : cidr.obj cidr_cmd.obj
+	$(CC) $(OPTIONS) -ecidr.exe cidr.obj cidr_cmd.obj
+
+cidr.obj : cidr.c cidr.h cidr_config.h
+	$(CC) -c $(OPTIONS) cidr.c
+
+cidr_cmd.obj : cidr_cmd.c cidr.h cidr_config.h
+	$(CC) -c $(OPTIONS) cidr_cmd.c
+
+
+clean:
+	-$(ERASE) cidr.obj
+	-$(ERASE) cidr_cmd.obj
+	-$(ERASE) cidr.exe
+	-$(ERASE) cidr.core
+	-$(ERASE) core
+	-$(ERASE) cidr.cms
+	-$(ERASE) cidr.il?
+	-$(ERASE) cidr.tds
+/*
+Copyright (C) 2003 Daybo Logic.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+1. Redistributions of source code must retain the above copyright
+   notice, this list of conditions and the following disclaimer.
+2. Redistributions in binary form must reproduce the above copyright
+   notice, this list of conditions and the following disclaimer in the
+   documentation and/or other materials provided with the distribution.
+3. Neither the name of the project nor the names of its contributors
+   may be used to endorse or promote products derived from this software
+   without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGE.
+*/
+
+#include "cidr_config.h"
+#define USE_CIDR_INTERNAL_TYPES
+#ifdef CIDR_DEBUG
+# include <stdio.h>
+#endif /*CIDR_DEBUG*/
+#include <stddef.h>
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+#ifdef HDRSTOP
+# pragma hdrstop
+#endif /*HDRSTOP*/
+
+#include "cidr.h"
+/*-------------------------------------------------------------------------*/
+#ifdef RCS_STAMPS
+static const char rcsid[] = "$Id: cidr.c,v 0.3 2003/04/23 16:12:00 ddrp Exp $";
+#endif /*RCS_STAMPS*/
+
+static unsigned char CountNetBits(const struct cidr_ipv4* IP1, const struct cidr_ipv4* IP2);
+static void CopyBits(struct cidr_ipv4* TargetBits, const struct cidr_ipv4* SourceBits, const unsigned char NumberOfBits);
+static unsigned char CopyOctalWithLimit(const unsigned char SourceOctal, unsigned char Limit);
+/*-------------------------------------------------------------------------*/
+enum cidr_errNum CIDR_CompileIP(struct cidr_ipv4* PIPOut, const char* IPStrIn)
+{
+  const char* ptr = IPStrIn;
+  unsigned int i;
+
+  if ( !PIPOut || !IPStrIn )
+    return cidr_errInvalidParam;
+
+  if ( PIPOut->size != sizeof(struct cidr_ipv4) )
+    return cidr_errVerMisMatch;
+
+  for ( i = 0U; i < sizeof(PIPOut->parts)/sizeof(PIPOut->parts[0]); i++ ) {
+    int numeric; /* For atoi() conversion */
+    char octal[4]; /* Just enough space for the string version of a single octal */
+    unsigned int j;
+
+    memset(octal, 0, sizeof(octal));
+    for ( j = 0U; j < sizeof(octal)/sizeof(octal[0]); j++ ) {
+      bool willBreak = false;
+      if ( *(ptr) != '.' && *(ptr) != '\0' )
+        octal[j] = *(ptr);
+      else
+        willBreak = true;
+
+      ptr++;
+      if ( willBreak ) break;
+    }
+    numeric = atoi(octal);
+    if ( numeric > 255 )
+      return cidr_errOctalRange;
+    else
+      PIPOut->parts[i] = (unsigned char)numeric;
+  }
+  return cidr_errSuccess;
+}
+/*-------------------------------------------------------------------------*/
+enum cidr_errNum CIDR_RoutingFormat(
+  const struct cidr_ipv4* StartRange,
+  const struct cidr_ipv4* EndRange,
+  struct cidr_ipv4* NetBlock
+)
+{
+  if ( !StartRange || !EndRange || !NetBlock )
+    return cidr_errInvalidParam;
+
+  /* Check integrity */
+  if ( StartRange->size != sizeof(struct cidr_ipv4) ||
+       EndRange->size != sizeof(struct cidr_ipv4) ||
+       NetBlock->size != sizeof(struct cidr_ipv4) )
+    return cidr_errVerMisMatch;
+
+  memset(NetBlock, 0, sizeof(struct cidr_ipv4)); /* Re-initialise output incase caller forgot to clean it properly, as we don't overwrite it all in the following code, (CopyBits() doesn't zero stuff out) */
+  NetBlock->size = sizeof(struct cidr_ipv4);
+  NetBlock->netBits = CountNetBits(StartRange, EndRange);
+  CopyBits(NetBlock, EndRange, NetBlock->netBits); /* It is important we use the end range */
+
+  return cidr_errSuccess;
+}
+/*-------------------------------------------------------------------------*/
+enum cidr_errNum CIDR_CreateMask(
+  struct cidr_ipv4* Mask,
+  const unsigned char NetBits
+)
+{
+  unsigned char bits = NetBits;
+  unsigned int i;
+
+  if ( !Mask ) return cidr_errInvalidParam;
+  if ( Mask->size != sizeof(struct cidr_ipv4) )
+    return cidr_errVerMisMatch;
+
+  memset(Mask->parts, 0, sizeof(Mask->parts));
+
+  for ( i = 0U; i < sizeof(Mask->parts)/sizeof(Mask->parts[0]); i++ ) {
+    if ( bits ) {
+      Mask->parts[i] = CopyOctalWithLimit(255, bits);
+      if ( bits >= 8 ) bits -= (unsigned char)8;
+      else bits -= bits;
+    }
+    else
+      break;
+  }
+  return cidr_errSuccess;
+}
+/*-------------------------------------------------------------------------*/
+static unsigned char CountNetBits(const struct cidr_ipv4* IP1, const struct cidr_ipv4* IP2)
+{
+  unsigned int i;
+  unsigned char count = 0U;
+  for ( i = 0U; i < sizeof(IP1->parts)/sizeof(IP1->parts[0]); i++ ) {
+    unsigned char mask = 128U;
+    bool ultimateBreak = false;
+    do {
+      if ( (IP1->parts[i] & mask) == (IP2->parts[i] & mask) )
+        count++;
+      else {
+        ultimateBreak = true;
+        break; /* Break out of both loops */
+      }
+
+      mask /= (unsigned char)2;
+    } while ( mask );
+    if ( ultimateBreak ) break;
+  }
+  return count;
+}
+/*-------------------------------------------------------------------------*/
+static void CopyBits(struct cidr_ipv4* TargetBits, const struct cidr_ipv4* SourceBits, const unsigned char NumberOfBits)
+{
+  unsigned char bitsToCopy = NumberOfBits;
+# ifdef CIDR_DEBUG
+    printf("NumberOfBits == %u\n", NumberOfBits);
+# endif /*CIDR_DEBUG*/
+  assert(NumberOfBits <= 32 );
+  if ( NumberOfBits ) {
+    TargetBits->parts[0] = CopyOctalWithLimit(SourceBits->parts[0], (unsigned char)(bitsToCopy));
+    if ( NumberOfBits > 8 )
+      TargetBits->parts[1] = CopyOctalWithLimit(SourceBits->parts[1], (unsigned char)(bitsToCopy -= (unsigned char)8));
+    if ( NumberOfBits > 16 )
+      TargetBits->parts[2] = CopyOctalWithLimit(SourceBits->parts[2], (unsigned char)(bitsToCopy -= (unsigned char)8));
+    if ( NumberOfBits > 24 )
+      TargetBits->parts[3] = CopyOctalWithLimit(SourceBits->parts[3], (unsigned char)(bitsToCopy -= (unsigned char)8));
+  }
+}
+/*-------------------------------------------------------------------------*/
+static unsigned char CopyOctalWithLimit(const unsigned char SourceOctal, unsigned char Limit)
+{
+  unsigned char copied = 0U;
+  unsigned char mask = 128;
+  unsigned char iLimit = 0U;
+
+# ifdef CIDR_DEBUG
+    printf("Limit == %u\n", Limit);
+# endif /*CIDR_DEBUG*/
+  assert(Limit);
+  if ( Limit > 8 ) Limit = 8;
+
+  if ( Limit == 8 )
+    copied = SourceOctal;
+  else {
+    do {
+      if ( (SourceOctal & mask) == mask )
+        copied |= mask;
+
+      mask /= (unsigned char)2;
+      iLimit++;
+    } while ( mask && (iLimit < Limit) );
+  }
+  return copied;
+}
+/*-------------------------------------------------------------------------*/
+/*
+$Id: cidr.h,v 0.2 2003/04/26 15:24:00 ddrp Exp $
+
+Copyright (C) 2003 Daybo Logic.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+1. Redistributions of source code must retain the above copyright
+   notice, this list of conditions and the following disclaimer.
+2. Redistributions in binary form must reproduce the above copyright
+   notice, this list of conditions and the following disclaimer in the
+   documentation and/or other materials provided with the distribution.
+3. Neither the name of the project nor the names of its contributors
+   may be used to endorse or promote products derived from this software
+   without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGE.
+*/
+
+#ifndef __INC_CIDR_H
+#define __INC_CIDR_H
+/*-------------------------------------------------------------------------*/
+#ifdef USE_CIDR_INTERNAL_TYPES
+# ifndef __cplusplus /* For C only */
+    typedef enum {
+      false = 0,
+      true = 1
+    } bool;
+
+#   ifndef __bool_true_false_are_defined
+#     define false false
+#     define true true
+#     define __bool_true_false_are_defined (1)
+#   endif /*!__bool_true_false_are_defined*/
+# endif /*!__cplusplus*/
+
+#endif /*USE_CIDR_INTERNAL_TYPES*/
+
+enum cidr_errNum {
+  cidr_errSuccess,      /* Success */
+  cidr_errOctalRange,   /* Octal portion of an IP out of range */
+  cidr_errBadIPFormat,  /* Bad IP format */
+  cidr_errInvalidParam, /* Invalid parameters */
+  cidr_errVerMisMatch   /* Version mismatch, possibly structure misalignment */
+};
+
+struct cidr_ipv4 {
+  unsigned short int size; /* Structure integrity test */
+  unsigned char parts[4]; /* Main IP */
+  unsigned char netBits; /* Number of bits which are part of the network */
+};
+
+#ifdef __cplusplus
+  extern "C" {
+#endif /*__cplusplus*/
+
+/*
+  This function is used to compile an IP from user-readable format
+  eg. 201.64.115.2 to the equivillant binary structrue used by the library.
+  It makes it much easier for the library to process the IP later on.
+*/
+enum cidr_errNum CIDR_CompileIP(
+  struct cidr_ipv4* PIPOut,
+  const char* IPStrIn
+);
+
+/*
+  This function is the main point of this library.  To convert a net
+  range defined in starting and ending addresses into an address designed
+  for route(8).  The StartRange and EndRange are input values.  netBits
+  is ignored in these values.  The NetBlock which is returned is the
+  address which can be used to address the block with the number of bits
+  which match between the blocks set in netBits.  It should be printed as
+  0.0.0.0/0 where the number after the forward slash is the value of
+  netBits.
+*/
+enum cidr_errNum CIDR_RoutingFormat(
+  const struct cidr_ipv4* StartRange,
+  const struct cidr_ipv4* EndRange,
+  struct cidr_ipv4* NetBlock
+);
+
+/*
+  The CIDR_CreateMask() function generates a netmask based on how many
+  bits long the network address is compared to host address.
+  For example, if the network address is 17 bits long in a 32-bit
+  IPv4 address, the mask is 255.255.128.0.
+*/
+enum cidr_errNum CIDR_CreateMask(
+  struct cidr_ipv4* Mask,
+  const unsigned char NetBits
+);
+
+#ifdef __cplusplus
+  } /* extern "C" */
+#endif /*__cplusplus*/
+
+#ifdef __cplusplus /* This class is for C++ only */
+enum cidr_range {
+  cidrStartRange,
+  cidrEndRange
+};
+
+class TCidr {
+private:
+  enum cidr_errNum lastError;
+  struct cidr_ipv4 startRange, endRange;
+  void InitRanges();
+  void Init();
+public:
+  TCidr();
+  TCidr(const struct cidr_ipv4* PStartRange, const struct cidr_ipv4* PEndRange);
+  TCidr(const char* StartRange, const char* EndRange);
+  // For setting either range (see enum cidr_range) from a string or struct.
+  enum cidr_errNum SetRange(const enum cidr_range Range, const struct cidr_ipv4* PRange);
+  enum cidr_errNum SetRange(const enum cidr_range Range, const char* RangeStr);
+  enum cidr_errNum GetRange(const enum cidr_range Range, struct cidr_ipv4* PRangeOut);
+  enum cidr_errNum GetNetBlock(struct cidr_ipv4* PNetBlockOut);
+  enum cidr_errNum CreateMask(const struct cidr_ipv4* PNetBlockIn, struct cidr_ipv4* PMaskOut);
+  enum cidr_errNum GetLastError();
+};
+#endif /*__cplusplus*/
+/*-------------------------------------------------------------------------*/
+#endif /*!__INC_CIDR_H*/
+/*
+Copyright (C) 2003 Daybo Logic.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+1. Redistributions of source code must retain the above copyright
+   notice, this list of conditions and the following disclaimer.
+2. Redistributions in binary form must reproduce the above copyright
+   notice, this list of conditions and the following disclaimer in the
+   documentation and/or other materials provided with the distribution.
+3. Neither the name of the project nor the names of its contributors
+   may be used to endorse or promote products derived from this software
+   without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGE.
+*/
+
+#include "cidr_config.h"
+#define USE_CIDR_INTERNAL_TYPES
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <ctype.h>
+#ifdef HDRSTOP
+# pragma hdrstop
+#endif /*HDRSTOP*/
+
+#include "cidr.h"
+/*-------------------------------------------------------------------------*/
+#ifdef RCS_STAMPS
+static const char rcsid[] = "$Id: cidr_cmd.c,v 0.2 2003/04/23 16:28:00 ddrp Exp $";
+#endif /*RCS_STAMPS*/
+
+static void Title(void);
+static void Help(const char* ProgName);
+static void Version(void);
+static bool StringCompareIC(const char* Str1, const char* Str2);
+static char* MakeLowerCase(char* Str);
+static char* MyStrDup(const char* Str);
+static bool SetRange(struct cidr_ipv4* PIPOut, const char* IPStrIn);
+static void PrintRange(const char* Label, const struct cidr_ipv4* PIP);
+static bool RoutingFormat(const struct cidr_ipv4* StartRange, const struct cidr_ipv4* EndRange, struct cidr_ipv4* NetBlock);
+static bool CreateMask(struct cidr_ipv4* Mask, const unsigned char NetBits);
+static void PrintErrorEnum(const enum cidr_errNum ErrNum);
+/*-------------------------------------------------------------------------*/
+int main(const int argc, const char* argv[])
+{
+  int argi;
+  struct cidr_ipv4 startRange, endRange, netBlock, netMask;
+  bool setStart, setEnd, ok, run;
+
+  /* Initialise structures */
+  memset(&startRange, 0, sizeof(startRange));
+  memset(&endRange, 0, sizeof(endRange));
+  memset(&netBlock, 0, sizeof(netBlock));
+  memset(&netMask, 0, sizeof(netMask));
+  startRange.size = sizeof(startRange);
+  endRange.size = sizeof(endRange);
+  netBlock.size = sizeof(netBlock);
+  netMask.size = sizeof(netMask);
+
+  run = ok = setStart = setEnd = false;
+
+  Title();
+  for ( argi = 1; argi < argc; argi++ ) {
+    if ( StringCompareIC(argv[argi], "--help") ||
+         StringCompareIC(argv[argi], "-h") ) {
+      Help(argv[0]);
+      ok = true; /* OK but don't run */
+      break;
+    }
+    if ( StringCompareIC(argv[argi], "--version") ||
+         StringCompareIC(argv[argi], "-v") ) {
+      Version();
+      ok = true; /* OK but don't run */
+      break;
+    }
+    if ( !setStart ) {
+      if ( !SetRange(&startRange, argv[argi]) ) break;
+      setStart = true;
+    }
+    else if ( !setEnd ) {
+      if ( !SetRange(&endRange, argv[argi]) ) break;
+      setEnd = true;
+      ok = run = true; /* OK and run */
+    }
+    else {
+      printf("Too many arguments.\n");
+      break;
+    }
+  }
+
+  if ( ok && run ) {
+    PrintRange("Start range: ", &startRange);
+    PrintRange("End range: ", &endRange);
+    if ( RoutingFormat(&startRange, &endRange, &netBlock) ) {
+      PrintRange("Net block: ", &netBlock);
+      if ( CreateMask(&netMask, netBlock.netBits) )
+        PrintRange("Net mask: ", &netMask);
+    }
+  }
+  else if ( !ok )
+    printf("Not enough parameters, -h for help.\n");
+
+  return EXIT_SUCCESS;
+}
+/*-------------------------------------------------------------------------*/
+static void Title()
+{
+  puts("CIDR netrange to netblock conversion tool for digiServ");
+  puts("(C)2003 David Duncan Ross Palmer, Daybo Logic\n");
+}
+/*-------------------------------------------------------------------------*/
+static void Help(const char* ProgName)
+{
+  printf(
+         "%s [options] [Start of range] [End of range]\n\n"
+         "\tOptions:\n"
+         "\t\t-h/--help : This help page\n"
+         "\t\t-v/--version : Version information\n"
+         "\n"
+         "\tStart of range:\n"
+         "\t\tThis must be an IP start range in standard notation\n"
+         "\t\teg. 201.64.115.0\n"
+         "\n"
+         "\tEnd of range:\n"
+         "\t\tThis must be an IP end range in standard notation\n"
+         "\t\teg. 201.64.115.255\n"
+         "\n",
+         (ProgName) ? (ProgName) : ("cidr")
+  );
+}
+/*-------------------------------------------------------------------------*/
+static void Version()
+{
+  printf(
+         "Version 0.3 built %s - %s\n",
+         __DATE__,
+         __TIME__
+  );
+}
+/*-------------------------------------------------------------------------*/
+static bool StringCompareIC(const char* Str1, const char* Str2)
+{
+  char* copy1;
+  char* copy2;
+  bool same = false; /* Not the same */
+
+  copy1 = MyStrDup(Str1);
+  copy2 = MyStrDup(Str2);
+
+  if ( !copy1 || !copy2 ) {
+    if ( copy1 ) free(copy1);
+    if ( copy2 ) free(copy2);
+    abort();
+  }
+
+  MakeLowerCase(copy1);
+  MakeLowerCase(copy2);
+
+  if ( strcmp(copy1, copy2) == 0 )
+    same = true; /* Matched */
+
+  free(copy1);
+  free(copy2);
+
+  return same;
+}
+/*-------------------------------------------------------------------------*/
+static char* MakeLowerCase(char* Str)
+{
+  if ( Str ) {
+    unsigned int i = 0U;
+    while ( Str[i] ) {
+      Str[i] = (char)tolower((int)(Str[i]));
+      i++;
+    }
+  }
+  return Str;
+}
+/*-------------------------------------------------------------------------*/
+static char* MyStrDup(const char* Str)
+{
+  char* duplicatedString;
+  if ( Str ) {
+    duplicatedString = (char*)malloc( strlen(Str) + 1 );
+    if ( duplicatedString )
+      strcpy(duplicatedString, Str);
+  }
+  else
+    duplicatedString = NULL;
+
+  return duplicatedString;
+}
+/*-------------------------------------------------------------------------*/
+static bool SetRange(struct cidr_ipv4* PIPOut, const char* IPStrIn)
+{
+  enum cidr_errNum err = CIDR_CompileIP(PIPOut, IPStrIn);
+  switch ( err ) {
+    case cidr_errOctalRange: {
+      printf("Octal out of range, remember, 255 is the maximum\n");
+      break;
+    }
+    case cidr_errBadIPFormat : {
+      printf("Bad IPv4 format - \'%s\'\n", IPStrIn);
+      break;
+    }
+    case cidr_errInvalidParam : {
+      printf("Invalid parameter - ");
+      if ( !PIPOut ) {
+        printf("cidr_ipv4 structure pointer not supplied\n");
+      }
+      else if ( !IPStrIn ) {
+        printf("IPv4 string pointer not supplied\n");
+      }
+      else {
+        printf("Unknown, run debugger\n");
+      }
+      break;
+    }
+    case cidr_errVerMisMatch : {
+      printf("Version mismatch detected.  Rebuild library\n");
+      break;
+    }
+    case cidr_errSuccess : {
+      break;
+    }
+    default : {
+      printf("Unknown error\n");
+    }
+  }
+  if ( err == cidr_errSuccess ) {
+    return true;
+  }
+  return false;
+}
+/*-------------------------------------------------------------------------*/
+static void PrintRange(const char* Label, const struct cidr_ipv4* PIP)
+{
+  printf(
+    "%s : %u.%u.%u.%u",
+    (Label) ? (Label) : ("Address"), /* Use a default caption if not supplied */
+    PIP->parts[0],
+    PIP->parts[1],
+    PIP->parts[2],
+    PIP->parts[3]
+  );
+
+  if ( PIP->netBits )
+    printf("/%u", PIP->netBits);
+
+  printf("\n");
+  return;
+}
+/*-------------------------------------------------------------------------*/
+static bool RoutingFormat(
+  const struct cidr_ipv4* StartRange,
+  const struct cidr_ipv4* EndRange,
+  struct cidr_ipv4* NetBlock
+)
+{
+  enum cidr_errNum err = CIDR_RoutingFormat(StartRange, EndRange, NetBlock);
+  if ( err != cidr_errSuccess ) {
+    PrintErrorEnum(err);
+    return false;
+  }
+  return true;
+}
+/*-------------------------------------------------------------------------*/
+static bool CreateMask(struct cidr_ipv4* Mask, const unsigned char NetBits)
+{
+  enum cidr_errNum err = CIDR_CreateMask(Mask, NetBits);
+  if ( err != cidr_errSuccess ) {
+    PrintErrorEnum(err);
+    return false;
+  }
+  return true;
+}
+/*-------------------------------------------------------------------------*/
+static void PrintErrorEnum(const enum cidr_errNum ErrNum)
+{
+  printf("CIDR error: ");
+  switch ( ErrNum ) {
+    case cidr_errSuccess : {
+      puts("Success");
+      break;
+    }
+    case cidr_errOctalRange : {
+      puts("Value exceeds oclet representation, is over 255");
+      break;
+    }
+    case cidr_errBadIPFormat : {
+      puts("The IP address is not in standard notation.");
+      break;
+    }
+    case cidr_errInvalidParam : {
+      puts("Internal error, invalid parameter");
+      break;
+    }
+    case cidr_errVerMisMatch : {
+      puts("cidr tool / library version mismatch (structures are not correctly sized.");
+      break;
+    }
+    default : {
+      puts("Unknown error");
+    }
+  }
+}
+/*-------------------------------------------------------------------------*/

File cidr_config.h

+/*
+$Id: cidr_config.h,v 0.2 2003/04/23 17:01:00 ddrp Exp $
+
+Copyright (C) 2003 Daybo Logic.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+1. Redistributions of source code must retain the above copyright
+   notice, this list of conditions and the following disclaimer.
+2. Redistributions in binary form must reproduce the above copyright
+   notice, this list of conditions and the following disclaimer in the
+   documentation and/or other materials provided with the distribution.
+3. Neither the name of the project nor the names of its contributors
+   may be used to endorse or promote products derived from this software
+   without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGE.
+*/
+
+/*
+  This can be editing to change options
+  - DDRP
+*/
+
+/* Un comment this macro for extra debug printf()'s */
+/*#define CIDR_DEBUG*/
+
+/* Un comment this macro for extra version info */
+/*#define RCS_STAMPS*/
+
+/* Un comment this macro for Borland features */
+/*#define HDRSTOP*/
+
+
+/* Don't change this bit, this logic makes it easier to switch between
+debugging or release modes.  Remember to also change switches though. */
+
+#ifndef CIDR_DEBUG /* Release? */
+# define NDEBUG /* Disable assertions */
+#endif /*CIDR_DEBUG*/

File cidr_oop.cpp

+/*
+Copyright (C) 2003 Daybo Logic.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+1. Redistributions of source code must retain the above copyright
+   notice, this list of conditions and the following disclaimer.
+2. Redistributions in binary form must reproduce the above copyright
+   notice, this list of conditions and the following disclaimer in the
+   documentation and/or other materials provided with the distribution.
+3. Neither the name of the project nor the names of its contributors
+   may be used to endorse or promote products derived from this software
+   without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGE.
+*/
+
+#include "cidr_config.h"
+#define USE_CIDR_INTERNAL_TYPES
+#ifdef CIDR_DEBUG
+# include <stdio.h>
+#endif /*CIDR_DEBUG*/
+#include <stddef.h>
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+#ifdef HDRSTOP
+# pragma hdrstop
+#endif /*HDRSTOP*/
+
+#include "cidr.h"
+//---------------------------------------------------------------------------
+#ifdef RCS_STAMPS
+static const char rcsid[] = "$Id: cidr_oop.cpp,v 0.1 2003/04/26 15:03:00 ddrp Exp $";
+#endif /*RCS_STAMPS*/
+//---------------------------------------------------------------------------
+#if 0
+enum cidr_errNum lastError;
+  struct cidr_ipv4 startRange, endRange;
+
+#endif /*0*/
+//---------------------------------------------------------------------------
+void TCidr::InitRanges()
+{
+  memset(&startRange, 0, sizeof(startRange));
+  memset(&endRange, 0, sizeof(endRange));
+  startRange.size = sizeof(startRange);
+  endRange.size = sizeof(endRange);
+}
+//---------------------------------------------------------------------------
+void TCidr::Init()
+{
+  lastError = cidr_errSuccess;
+  InitRanges();
+}
+//---------------------------------------------------------------------------
+TCidr::TCidr()
+{
+  Init();
+}
+//---------------------------------------------------------------------------
+TCidr::TCidr(const struct cidr_ipv4* PStartRange, const struct cidr_ipv4* PEndRange)
+{
+  Init();
+  SetRange(cidrStartRange, PStartRange);
+  SetRange(cidrEndRange, PEndRange);
+}
+//---------------------------------------------------------------------------
+TCidr::TCidr(const char* StartRange, const char* EndRange)
+{
+  Init();
+  SetRange(cidrStartRange, StartRange);
+  SetRange(cidrEndRange, EndRange);
+}
+//---------------------------------------------------------------------------
+enum cidr_errNum TCidr::SetRange(const enum cidr_range Range, const struct cidr_ipv4* PRange)
+{
+  lastError = cidr_errSuccess; // Reset error condition
+  if ( PRange ) {
+    if ( PRange->size == sizeof(struct cidr_ipv4) ) {
+      struct cidr_ipv4* structPtr;
+      switch ( Range ) {
+        case cidrStartRange : {
+          structPtr = &startRange;
+          break;
+        }
+        case cidrEndRange : {
+          structPtr = &endRange;
+          break;
+        }
+        default : {
+          structPtr = NULL;
+        }
+      }
+      if ( structPtr ) {
+        *structPtr = *PRange;
+      }
+    }
+    else
+      lastError = cidr_errVerMisMatch;
+  }
+  else
+    lastError = cidr_errInvalidParam;
+
+  return lastError;
+}
+//---------------------------------------------------------------------------
+enum cidr_errNum TCidr::SetRange(const enum cidr_range Range, const char* RangeStr)
+{
+  struct cidr_ipv4 range;
+  struct cidr_ipv4* pTargetRange;
+
+  memset(&range, 0, sizeof(range));
+  range.size = sizeof(range);
+
+  lastError = CIDR_CompileIP(&range, RangeStr);
+  switch ( Range ) {
+    case cidrStartRange : {
+      pTargetRange = &startRange;
+      break;
+    }
+    case cidrEndRange : {
+      pTargetRange = &endRange;
+      break;
+    }
+    default : {
+      pTargetRange = NULL;
+    }
+  }
+  if ( lastError == cidr_errSuccess ) {
+    if ( pTargetRange )
+      memcpy(pTargetRange, &range, sizeof(range));
+    else
+      lastError = cidr_errInvalidParam;
+  }
+
+  return lastError;
+}
+//---------------------------------------------------------------------------
+enum cidr_errNum TCidr::GetRange(const enum cidr_range Range, struct cidr_ipv4* PRangeOut)
+{
+  if ( PRangeOut ) {
+    if ( PRangeOut->size == sizeof(struct cidr_ipv4) ) {
+      switch ( Range ) {
+        case cidrStartRange : {
+          *PRangeOut = startRange;
+          break;
+        }
+        case cidrEndRange : {
+          *PRangeOut = endRange;
+          break;
+        }
+        default : {
+          lastError = cidr_errInvalidParam;
+          return lastError;
+        }
+      }
+      lastError = cidr_errSuccess;
+    }
+    else
+      lastError = cidr_errVerMisMatch;
+  }
+  else
+    lastError = cidr_errInvalidParam;
+
+  return lastError;
+}
+//---------------------------------------------------------------------------
+enum cidr_errNum TCidr::GetNetBlock(struct cidr_ipv4* PNetBlockOut)
+{
+  if ( PNetBlockOut ) {
+    if ( PNetBlockOut->size == sizeof(struct cidr_ipv4) ) {
+      lastError = CIDR_RoutingFormat(&startRange, &endRange, PNetBlockOut);
+    }
+    else
+      lastError = cidr_errVerMisMatch;
+  }
+  else
+    lastError = cidr_errInvalidParam;
+    
+  return lastError;
+}
+//---------------------------------------------------------------------------
+enum cidr_errNum TCidr::CreateMask(const struct cidr_ipv4* PNetBlockIn, struct cidr_ipv4* PMaskOut)
+{
+  if ( PNetBlockIn && PMaskOut ) {
+    if ( PNetBlockIn->size == (unsigned short int)(sizeof(struct cidr_ipv4)) &&
+         PMaskOut->size == (unsigned short int)(sizeof(struct cidr_ipv4)) )
+    {
+      lastError = CIDR_CreateMask(PMaskOut, PNetBlockIn->netBits);
+    }
+    else
+      lastError = cidr_errVerMisMatch;
+  }
+  else
+    lastError = cidr_errInvalidParam;
+
+  return lastError;
+}
+//---------------------------------------------------------------------------
+enum cidr_errNum TCidr::GetLastError()
+{
+  return lastError;
+}
+//---------------------------------------------------------------------------

File freebsd.bin/readme.txt

+CIDR for FreeBSD
+Built by David Duncan Ross Palmer
+Built on FreeBSD 4.7-STABLE, statically linked.
+If you have no compiler installed, which isn't very likely on FreeBSD,
+you can use this binary, simply cp cidr /usr/local/bin as root.
+I recommend compiling your own though, as this will dynamically link
+your code to the installed run time libraries, making a much smaller
+executable.
+
+http://www.daybologic.co.uk/mailddrp/

File linux_ppc.bin/readme.txt

+CIDR for Linux on PPC
+Built by David Duncan Ross Palmer
+Built on Linux 2.2 for the PowerPC, statically linked.
+(Yellow Dog Linux, chapion server 1.2).
+If you have no compiler installed,
+you can use this binary, simply cp cidr /usr/local/bin as root.
+I recommend compiling your own though, as this will dynamically link
+your code to the installed run time libraries, making a much smaller
+executable.
+
+http://www.daybologic.co.uk/mailddrp/

File linux_x86.bin/readme.txt

+CIDR for Linux on 386
+Built by David Duncan Ross Palmer
+Built on Linux 2.2 for the IBM PC, statically linked.
+Compressed with UPX (http://upx.sourceforge.net)
+(Debian GNU/Linux potato 3.0).
+If you have no compiler installed,
+you can use this binary, simply cp cidr /usr/local/bin as root.
+I recommend compiling your own though, as this will dynamically link
+your code to the installed run time libraries, making a much smaller
+executable.
+
+http://www.daybologic.co.uk/mailddrp/
+CIDR - Classless Inter-Domain Routing
+Tool for calculating masks from address ranges.
+
+Introduction:
+In the old days, IPv4 addressing was easy.  If you had network 10.0.0.0/8,
+you knew that 10 was the network address and 0.0.0 to 255.255.255 were
+addresses for your hosts.  Well, it's not so easy not, classless
+addressing means that the standard classes of /8, /16 and /24 are gone.
+That number can now be anything, it's a good thing (TM) but difficult to
+calculate.  When digiServ (http://www.digiserv.net/) asked me if I could
+code a tool to calculate the network addresses for rangers of addresses to
+help them firewall troublesome users without affecting people from other
+netblocks, I jumped at the task.  This tool will works like this:
+
+Usage:
+cidr [starting address] [ending address].
+If I specify cidr 201.64.115.0 201.64.115.255
+I will get the following information back:
+  Block: 201.64.115.0/24
+  Mask: 255.255.255.0
+
+That is what this tool is for.  It can also help you specify the smallest
+netblock you should be using to contain your hosts.  The tool consists of
+two main files:
+
+cidr.c <- The main library code
+cidr_cmd.c <- The command line interface
+
+The less important files are:
+
+cidr_oop.cpp <- The C++ wrapper class code
+cidr.h <- The header for the cidr.c library and class
+cidr_config.h <- Miscellaneous options for building the code.
+
+Under win32/ you will also find a GUI program for Windows users.
+It is recommended that you use the binaries for Win32 as you may
+have difficulty building the GUI.
+
+Building
+========
+To build the command line tool:
+
+On GNU / UNIX systems, type:
+
+make
+as root, then:
+make install
+then make clean.
+
+You will have compiled and installed cidr.  Then just type cidr -h for
+information.
+
+On Borland C++, type:
+make -f Makefile.bor
+Then copy cidr.exe to whereever you wish.  Though win32.bin/cidr.exe might
+be smaller due to UPC compression, so I recommend you use that version.

File win32.bin/readme.txt

+CIDR for Win32 on 386
+Built by David Duncan Ross Palmer
+Built on Windows NT 5.0 for the IBM PC, statically linked.
+Compressed with UPX (http://upx.sourceforge.net)
+(Microsoft Windows 2000 [Version 5.00.2195]).
+
+WinCidr32 for Win32 on 486 (GUI version)
+Built by David Duncan Ross Palmer
+Built on Windows NT 5.0 for the IBM PC, statically linked.
+Compressed with UPX (http://upx.sourceforge.net)
+(Microsoft Windows 2000 [Version 5.00.2195]).
+
+Due to the lack of standard compilers on Win32, I have built a command
+line tool, staticlly linked and a GUI version statically linked.
+You can copy them both to your Windows command directory or specialist
+tools directory and execute them from there.  If you want to build the
+source yourself, you can find the source in the parent directory for the
+command line tool and the GUI code is in ../win32.
+The main source should compile on any compiler but the GUI source
+requires Borland C++Builder 4.
+
+http://www.daybologic.co.uk/mailddrp/

File win32/MainFormUnit.cpp

+//---------------------------------------------------------------------------
+#include <assert.h>
+#include <vcl.h>
+#include <shellapi.h>
+#pragma hdrstop
+
+#include "cidr.h"
+#include "MainFormUnit.h"
+//---------------------------------------------------------------------------
+#pragma package(smart_init)
+#pragma link "CSPIN"
+#pragma resource "*.dfm"
+TMainForm *MainForm;
+//---------------------------------------------------------------------------
+__fastcall TMainForm::TMainForm(TComponent* Owner)
+        : TForm(Owner)
+{
+  unsigned int i;
+  for ( i = 0U; i < sizeof(SpinEdits)/sizeof(SpinEdits[0]); i++ )
+    SpinEdits[i] = NULL;
+  for ( i = 0U; i < sizeof(Edits)/sizeof(Edits[0]); i++ )
+    Edits[i] = NULL;
+}
+//---------------------------------------------------------------------------
+void __fastcall TMainForm::CloseBtnClick(TObject *Sender)
+{
+  Close();        
+}
+//---------------------------------------------------------------------------
+void __fastcall TMainForm::FormCreate(TObject *Sender)
+{
+  unsigned int i;
+  TCSpinEdit* spinEdits[] = {
+    CSpinEdit1, CSpinEdit2, CSpinEdit3, CSpinEdit4,
+    CSpinEdit5, CSpinEdit6, CSpinEdit7, CSpinEdit8
+  };
+  TEdit* edits[] = {
+    NetBlockEdit, NetMaskEdit
+  };
+
+  assert(sizeof(spinEdits) == sizeof(SpinEdits));
+  for ( i = 0U; i < sizeof(SpinEdits)/sizeof(SpinEdits[0]); i++ )
+    SpinEdits[i] = spinEdits[i]; // Copy pointers to class
+
+  assert(sizeof(edits) == sizeof(Edits));
+  for ( i = 0U; i < sizeof(Edits)/sizeof(Edits[0]); i++ )
+    Edits[i] = edits[i]; // Copy pointers to class
+}
+//---------------------------------------------------------------------------
+void __fastcall TMainForm::ClearBtnClick(TObject *Sender)
+{
+  unsigned int i;
+  for ( i = 0U; i < sizeof(SpinEdits)/sizeof(SpinEdits[0]); i++ ) {
+    assert(SpinEdits[i]);
+    SpinEdits[i]->Value = 0U;
+  }
+
+  for ( i = 0U; i < sizeof(Edits)/sizeof(Edits[0]); i++ ) {
+    assert(Edits[i]);
+    Edits[i]->Text = "";
+  }
+}
+//---------------------------------------------------------------------------
+void __fastcall TMainForm::CalcBtnClick(TObject *Sender)
+{
+  Calculate();
+}
+//---------------------------------------------------------------------------
+void TMainForm::FormToCidrIPv4(const enum cidr_range Range, struct cidr_ipv4* PRangeOut)
+{
+  unsigned int base = 0;
+  unsigned int i;
+  if ( Range == cidrEndRange )
+    base += 4; // Move onto the other fields ;)
+
+  for ( i = 0U; i < sizeof(PRangeOut->parts)/sizeof(PRangeOut->parts[0]); i++ )
+    PRangeOut->parts[i] = (unsigned char)SpinEdits[base+i]->Value;
+}
+//---------------------------------------------------------------------------
+void TMainForm::PrintCidrError(const enum cidr_errNum ErrNum)
+{
+  char* msgPtr = NULL;
+  unsigned int messageTableOffset;
+  const struct {
+    enum cidr_errNum err;
+    char* msg;
+  } messageTable[] = {
+    { cidr_errSuccess, "No error" },
+    { cidr_errOctalRange, "Oclet out of range in under input" },
+    { cidr_errBadIPFormat, "The IP is badly formatted (IPv4)" },
+    { cidr_errInvalidParam, "Bad or missing parameter sent to CIDR library" },
+    { cidr_errVerMisMatch, "CIDR library version mismatch, you need to rebuild all" }
+  };
+
+  for ( messageTableOffset = 0U;
+        messageTableOffset < sizeof(messageTable)/sizeof(messageTable[0]);
+        messageTableOffset++
+      )
+  {
+    if ( messageTable[messageTableOffset].err == ErrNum ) {
+      msgPtr = messageTable[messageTableOffset].msg;
+      break;
+    }
+  }
+  if ( msgPtr )
+    Application->MessageBox(msgPtr, Application->Title.c_str(), MB_OK | MB_ICONSTOP);
+}
+//---------------------------------------------------------------------------
+void TMainForm::NetBlockToForm(const struct cidr_ipv4* PNetBlock)
+{
+  unsigned int i, c;
+
+  NetBlockEdit->Text = "";
+  c = sizeof(PNetBlock->parts)/sizeof(PNetBlock->parts[0]);
+  for ( i = 0U; i < c; i++ ) {
+    NetBlockEdit->Text = NetBlockEdit->Text + (AnsiString)PNetBlock->parts[i];
+    if ( i != (c - 1) )
+      NetBlockEdit->Text = NetBlockEdit->Text + (AnsiString)".";
+  }
+  NetBlockEdit->Text = NetBlockEdit->Text + (AnsiString)"/" + (AnsiString)PNetBlock->netBits;
+}
+//---------------------------------------------------------------------------
+void TMainForm::MaskToForm(const struct cidr_ipv4* PMask)
+{
+  unsigned int i, c;
+
+  NetMaskEdit->Text = "";
+  c = sizeof(PMask->parts)/sizeof(PMask->parts[0]);
+  for ( i = 0U; i < c; i++ ) {
+    NetMaskEdit->Text = NetMaskEdit->Text + (AnsiString)PMask->parts[i];
+    if ( i != (c - 1) )
+      NetMaskEdit->Text = NetMaskEdit->Text + (AnsiString)".";
+  }
+}
+//---------------------------------------------------------------------------
+void __fastcall TMainForm::AutoChkClick(TObject *Sender)
+{
+  //CalcBtn->Enabled = !AutoChk->Checked;
+  //if ( AutoChk->Checked )
+  //  Application->MessageBox("NOTE: This makes the spin edits slightly difficult to edit,\nI think they are buggy, I might replace them with normal edits.\n\n\t -- DDRP", "Auto mode", MB_OK | MB_ICONINFORMATION);
+}
+//---------------------------------------------------------------------------
+void __fastcall TMainForm::AutoCalculate(TObject *Sender)
+{
+  if ( AutoChk->Checked )
+    Calculate();
+}
+//---------------------------------------------------------------------------
+void TMainForm::Calculate()
+{
+  enum cidr_errNum errNum;
+  struct cidr_ipv4 range;
+
+  memset(&range, 0, sizeof(range));
+  range.size = sizeof(range);
+  FormToCidrIPv4(cidrStartRange, &range);
+  errNum = Cidr.SetRange(cidrStartRange, &range);
+  if ( errNum != cidr_errSuccess )
+    PrintCidrError(errNum);
+  else {
+    memset(&range, 0, sizeof(range));
+    range.size = sizeof(range);
+    FormToCidrIPv4(cidrEndRange, &range);
+    errNum = Cidr.SetRange(cidrEndRange, &range);
+    if ( errNum != cidr_errSuccess )
+      PrintCidrError(errNum);
+    else {
+      // OK, the ranges are in the class, now to do the conversion.
+      memset(&range, 0, sizeof(range));
+      range.size = sizeof(range);
+      errNum = Cidr.GetNetBlock(&range);
+      if ( errNum != cidr_errSuccess )
+        PrintCidrError(errNum);
+      else {
+        struct cidr_ipv4 mask;
+        NetBlockToForm(&range);
+        memset(&mask, 0, sizeof(mask));
+        mask.size = sizeof(mask);
+        errNum = Cidr.CreateMask(&range, &mask);
+        if ( errNum != cidr_errSuccess )
+          PrintCidrError(errNum);
+        else {
+          MaskToForm(&mask);
+          // Complete
+        }
+      }
+    }
+  }
+}
+//---------------------------------------------------------------------------
+void TMainForm::LaunchSite()
+{
+  HINSTANCE handle;
+  int i;
+  const char* msg = NULL;
+  char* bastardisableMsg; // A bastardisable version compatible with Application->MessageBox()
+  static const char defMsg[] = "Unknown error code";
+
+  static const struct {
+    int code;
+    char* message;
+  } messageTable[] = {
+    { 0, "The operating system is out of memory or resources." },
+    { ERROR_FILE_NOT_FOUND, "The specified file was not found." },
+    { ERROR_PATH_NOT_FOUND, "The specified path was not found." },
+    { ERROR_BAD_FORMAT, "The .exe file is invalid (non-Microsoft Win32 .exe orr error in .exe image)." },
+    { SE_ERR_ACCESSDENIED, "The operating system denied access to the specified file." },
+    { SE_ERR_ASSOCINCOMPLETE, "The file name association is incomplete or invalid." },
+    { SE_ERR_DDEBUSY, "The Dynamic Data Exchange (DDE) transaction could not becompleted because other DDE\ntransactions were being processed." },
+    { SE_ERR_DDEFAIL, "The DDE transaction failed." },
+    { SE_ERR_DDETIMEOUT, "The DDE transaction could not be completed because the request timed out." },
+    { SE_ERR_DLLNOTFOUND, "The specified dynamic-link library (DLL) was not found." },
+    { SE_ERR_FNF, "The specified file was not found." },
+    { SE_ERR_NOASSOC, "There is no application associated with the given file name extension. This error will also be\nreturned if you attempt to print a file that is not printable." },
+    { SE_ERR_OOM, "There was not enough memory to complete the operation." },
+    { SE_ERR_PNF, "The specified path was not found." },
+    { SE_ERR_SHARE, "A sharing violation occurred." }
+  };
+
+  handle = ShellExecute(Handle, "open", "http://www.gradwell.com/", NULL, NULL, SW_MAXIMIZE);
+  if ( (int)handle > 32 ) return; /* OK (according to http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/shell/reference/functions/shellexecute.asp) */
+
+  // Not OK, let's lookup the error code
+  for ( i = 0; i < sizeof(messageTable)/sizeof(messageTable[0]); i++ ) {
+    if ( messageTable[i].code == (int)handle )
+      msg = messageTable[i].message;
+  }
+  if ( !msg ) msg = defMsg; // No code matched our known error code table
+  bastardisableMsg = new char[strlen(msg)+1];
+  if ( bastardisableMsg ) {
+    strcpy(bastardisableMsg, msg);
+    Application->MessageBox(Application->Title.c_str(), bastardisableMsg, MB_ICONSTOP | MB_OK);
+    delete[] bastardisableMsg;
+  }
+  return;
+}
+//---------------------------------------------------------------------------
+void __fastcall TMainForm::PopSiteClick(TObject *Sender)
+{
+  LaunchSite();        
+}
+//---------------------------------------------------------------------------
+void __fastcall TMainForm::PopAboutClick(TObject *Sender)
+{
+  Application->MessageBox(
+    "CIDR netrange to netblock conversion tool for Win32 version 0.3\n"
+    "(c)2003 David Palmer for Gradwell dot com Ltd\n"
+    "THE PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL,\n"
+    "BUT WITHOUT ANY WARRANTY. IT IS PROVIDED \"AS IS\" WITHOUT\n"
+    "WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n"
+    "BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n"
+    "FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY\n"
+    "AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE\n"
+    "DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR\n"
+    "OR CORRECTION.",
+    "About wincidr32",
+    MB_OK
+  );
+}
+//---------------------------------------------------------------------------
+void __fastcall TMainForm::PopCopyAddressClick(TObject *Sender)
+{
+  if ( Sender ) {
+    TEdit* edit = dynamic_cast<TEdit*>(PopupMenu->PopupComponent);
+    if ( edit ) {
+      edit->SelectAll();
+      edit->CopyToClipboard();
+    }
+  }
+}
+//---------------------------------------------------------------------------
+

File win32/MainFormUnit.dfm

Binary file added.

File win32/MainFormUnit.h

+//---------------------------------------------------------------------------
+#ifndef MainFormUnitH
+#define MainFormUnitH
+//---------------------------------------------------------------------------
+#include <Classes.hpp>
+#include <Controls.hpp>
+#include <StdCtrls.hpp>
+#include <Forms.hpp>
+#include "CSPIN.h"
+#include <Menus.hpp>
+//---------------------------------------------------------------------------
+class TMainForm : public TForm
+{
+__published:	// IDE-managed Components
+        TLabel *Label1;
+        TLabel *Label2;
+        TLabel *Label3;
+        TLabel *Label4;
+        TCSpinEdit *CSpinEdit1;
+        TCSpinEdit *CSpinEdit2;
+        TCSpinEdit *CSpinEdit3;
+        TCSpinEdit *CSpinEdit4;
+        TCSpinEdit *CSpinEdit5;
+        TCSpinEdit *CSpinEdit6;
+        TCSpinEdit *CSpinEdit7;
+        TCSpinEdit *CSpinEdit8;
+        TEdit *NetBlockEdit;
+        TEdit *NetMaskEdit;
+        TButton *CalcBtn;
+        TButton *ClearBtn;
+        TButton *CloseBtn;
+        TCheckBox *AutoChk;
+        TPopupMenu *PopupMenu;
+        TMenuItem *PopAbout;
+        TMenuItem *PopSite;
+        TMenuItem *N1;
+        TMenuItem *PopCopyAddress;
+        void __fastcall CloseBtnClick(TObject *Sender);
+        void __fastcall FormCreate(TObject *Sender);
+        void __fastcall ClearBtnClick(TObject *Sender);
+        void __fastcall CalcBtnClick(TObject *Sender);
+        void __fastcall AutoChkClick(TObject *Sender);
+        void __fastcall AutoCalculate(TObject *Sender);
+        void __fastcall PopSiteClick(TObject *Sender);
+        void __fastcall PopAboutClick(TObject *Sender);
+        void __fastcall PopCopyAddressClick(TObject *Sender);
+private:	// User declarations
+        TCSpinEdit* SpinEdits[8];
+        TEdit* Edits[2];
+        TCidr Cidr;
+        void FormToCidrIPv4(const enum cidr_range Range, struct cidr_ipv4* PRangeOut); // Convert one of the user fields on the form into the structure suitable for the library
+public:		// User declarations
+        __fastcall TMainForm(TComponent* Owner);
+        void PrintCidrError(const enum cidr_errNum ErrNum);
+        void NetBlockToForm(const struct cidr_ipv4* PNetBlock); // Copies the netblock onto the form
+        void MaskToForm(const struct cidr_ipv4* PMask); // Copies the mask onto the form
+        void Calculate();
+        void LaunchSite();
+};
+//---------------------------------------------------------------------------
+extern PACKAGE TMainForm *MainForm;
+//---------------------------------------------------------------------------
+#endif

File win32/daybo.ico

Added
New image

File win32/gradwell.ico

Added
New image

File win32/wincidr32.bpr

+# ---------------------------------------------------------------------------
+!if !$d(BCB)
+BCB = $(MAKEDIR)\..
+!endif
+
+# ---------------------------------------------------------------------------
+# IDE SECTION
+# ---------------------------------------------------------------------------
+# The following section of the project makefile is managed by the BCB IDE.
+# It is recommended to use the IDE to change any of the values in this
+# section.
+# ---------------------------------------------------------------------------
+
+VERSION = BCB.04.04
+# ---------------------------------------------------------------------------
+PROJECT = wincidr32.exe
+OBJFILES = wincidr32.obj MainFormUnit.obj ..\cidr.obj ..\cidr_oop.obj
+RESFILES = wincidr32.res
+RESDEPEN = $(RESFILES) MainFormUnit.dfm
+LIBFILES =
+LIBRARIES = VCLX40.lib bcbsmp40.lib Vcl40.lib
+SPARELIBS = Vcl40.lib bcbsmp40.lib VCLX40.lib
+PACKAGES = Vcl40.bpi Vclx40.bpi vcljpg40.bpi bcbsmp40.bpi Qrpt40.bpi Vcldb40.bpi \
+  ibsmp40.bpi vcldbx40.bpi TeeUI40.bpi teedb40.bpi tee40.bpi nmfast40.bpi \
+  dclocx40.bpi
+DEFFILE =
+# ---------------------------------------------------------------------------
+PATHCPP = .;..
+PATHPAS = .;
+PATHASM = .;
+PATHRC = .;
+DEBUGLIBPATH = $(BCB)\lib\debug
+RELEASELIBPATH = $(BCB)\lib\release
+USERDEFINES =
+SYSDEFINES = NO_STRICT
+# ---------------------------------------------------------------------------
+CFLAG1 = -I..\;..;$(BCB)\include;$(BCB)\include\vcl -Og -Ov -OS -Hc \
+  -H=$(BCB)\lib\vcl40.csm -w -Ve -a8 -4 -d -k- -vi -c -b- -w-par -w-inl -Vx -tW \
+  -tWM -D$(SYSDEFINES);$(USERDEFINES)
+PFLAGS = -U..\;..;$(BCB)\lib\obj;$(BCB)\lib;$(RELEASELIBPATH) \
+  -I..\;..;$(BCB)\include;$(BCB)\include\vcl -$Y- -$L- -$D- -v -JPHNE -M
+RFLAGS = -i..\;..;$(BCB)\include;$(BCB)\include\vcl
+AFLAGS = /i..\ /i.. /i$(BCB)\include /i$(BCB)\include\vcl /mx /w2 /zn
+LFLAGS = -L..\;..;$(BCB)\lib\obj;$(BCB)\lib;$(RELEASELIBPATH) -aa -Tpe -m -Gn
+# ---------------------------------------------------------------------------
+ALLOBJ = c0w32.obj sysinit.obj $(OBJFILES)
+ALLRES = $(RESFILES)
+ALLLIB = $(LIBFILES) $(LIBRARIES) import32.lib cp32mt.lib
+# ---------------------------------------------------------------------------
+!ifdef IDEOPTIONS
+
+[Version Info]
+IncludeVerInfo=1
+AutoIncBuild=1
+MajorVer=0
+MinorVer=3
+Release=0
+Build=19
+Debug=0
+PreRelease=0
+Special=0
+Private=0
+DLL=0
+Locale=2057
+CodePage=1252
+
+[Version Info Keys]
+CompanyName=Gradwell dot com Ltd
+FileDescription=NetRange To NetBlock conversion tool
+FileVersion=0.3.0.19
+InternalName=cidr
+LegalCopyright=Copyright 2003-2008 Gradwell dot com Ltd
+LegalTrademarks=
+OriginalFilename=wincidr32.exe
+ProductName=wincidr32
+ProductVersion=1.0.0.0
+Comments=Licensed under a BSD compatible license
+Contact=http://www.gradwell.com/
+Programmer=David Duncan Ross Palmer
+
+[HistoryLists\hlIncludePath]
+Count=2
+Item0=..\;..;$(BCB)\include;$(BCB)\include\vcl
+Item1=..\;$(BCB)\include;$(BCB)\include\vcl
+
+[HistoryLists\hlLibraryPath]
+Count=2
+Item0=..\;..;$(BCB)\lib\obj;$(BCB)\lib
+Item1=..\;$(BCB)\lib\obj;$(BCB)\lib
+
+[HistoryLists\hlDebugSourcePath]
+Count=1
+Item0=$(BCB)\source\vcl
+
+[Debugging]
+DebugSourceDirs=$(BCB)\source\vcl
+
+[Parameters]
+RunParams=
+HostApplication=
+RemoteHost=
+RemotePath=
+RemoteDebug=0
+
+[Compiler]
+InMemoryExe=0
+ShowInfoMsgs=0
+
+!endif
+
+# ---------------------------------------------------------------------------
+# MAKE SECTION
+# ---------------------------------------------------------------------------
+# This section of the project file is not used by the BCB IDE.  It is for
+# the benefit of building from the command-line using the MAKE utility.
+# ---------------------------------------------------------------------------
+
+.autodepend
+# ---------------------------------------------------------------------------
+!if !$d(BCC32)
+BCC32 = bcc32
+!endif
+
+!if !$d(CPP32)
+CPP32 = cpp32
+!endif
+
+!if !$d(DCC32)
+DCC32 = dcc32
+!endif
+
+!if !$d(TASM32)
+TASM32 = tasm32
+!endif
+
+!if !$d(LINKER)
+LINKER = ilink32
+!endif
+
+!if !$d(BRCC32)
+BRCC32 = brcc32
+!endif
+
+# ---------------------------------------------------------------------------
+!if $d(PATHCPP)
+.PATH.CPP = $(PATHCPP)
+.PATH.C   = $(PATHCPP)
+!endif
+
+!if $d(PATHPAS)
+.PATH.PAS = $(PATHPAS)
+!endif
+
+!if $d(PATHASM)
+.PATH.ASM = $(PATHASM)
+!endif
+
+!if $d(PATHRC)
+.PATH.RC  = $(PATHRC)
+!endif
+# ---------------------------------------------------------------------------
+$(PROJECT): $(OBJFILES) $(RESDEPEN) $(DEFFILE)
+    $(BCB)\BIN\$(LINKER) @&&!
+    $(LFLAGS) +
+    $(ALLOBJ), +
+    $(PROJECT),, +
+    $(ALLLIB), +
+    $(DEFFILE), +
+    $(ALLRES)
+!
+# ---------------------------------------------------------------------------
+.pas.hpp:
+    $(BCB)\BIN\$(DCC32) $(PFLAGS) {$< }
+
+.pas.obj:
+    $(BCB)\BIN\$(DCC32) $(PFLAGS) {$< }
+
+.cpp.obj:
+    $(BCB)\BIN\$(BCC32) $(CFLAG1) -n$(@D) {$< }
+
+.c.obj:
+    $(BCB)\BIN\$(BCC32) $(CFLAG1) -n$(@D) {$< }
+
+.c.i:
+    $(BCB)\BIN\$(CPP32) $(CFLAG1) -n. {$< }
+
+.cpp.i:
+    $(BCB)\BIN\$(CPP32) $(CFLAG1) -n. {$< }
+
+.asm.obj:
+    $(BCB)\BIN\$(TASM32) $(AFLAGS) $<, $@
+
+.rc.res:
+    $(BCB)\BIN\$(BRCC32) $(RFLAGS) -fo$@ $<
+# ---------------------------------------------------------------------------

File win32/wincidr32.cpp

+//---------------------------------------------------------------------------
+#include <vcl.h>
+#pragma hdrstop
+USERES("wincidr32.res");
+USEFORM("MainFormUnit.cpp", MainForm);
+USEUNIT("..\cidr.c");
+USEUNIT("..\cidr_oop.cpp");
+//---------------------------------------------------------------------------
+WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
+{
+        try
+        {
+                 Application->Initialize();
+                 Application->Title = "CIDR networking calculator";
+                 Application->CreateForm(__classid(TMainForm), &MainForm);
+                 Application->Run();
+        }
+        catch (EConvertError &exception)
+        {
+                // Totally ignore this exception
+        }
+        catch (Exception &exception)
+        {
+                 Application->ShowException(&exception);
+        }
+        return 0;
+}
+//---------------------------------------------------------------------------

File win32/wincidr32.res

Binary file added.