IPv4 to binary conversion

This is my first attempt to create a IPv4 to Binary conversion

Page 1 of 1

8 Replies - 7523 Views - Last Post: 19 January 2009 - 06:54 PM Rate Topic: -----

#1 msg270  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 16-January 09

IPv4 to binary conversion

Post icon  Posted 16 January 2009 - 10:01 AM

I want to create a IP Data base program. Something that will help admins keep track of what is assigned, what they available, etc. To that end I realized that in order to effectly do checking on the input, verify what subnets go together, determine if one subnet is part of another, etc I need to be able to take in an IPV4 address and get it's Binary representation. I put this code together and it works fine. I'm posting here as I don't know any other developers and the book i'm reading doesn't give me much feed back when I ask it questions :)

I would apprectiate any opinions on this, is there a better way to do this or structure it?

// strings and c-strings
#include <iostream>
#include <cstring>
#include <string>
using namespace std;

//This function converts each string piece into an int
//for evaluation later
 int GetIntVal(string p) 
  {
		int intReturn;
		intReturn = atoi(p.c_str());
	  return(intReturn);
  }

string IntToString(int intValue) {
  char *myBuff;
  string strRetVal;

  // Create a new char array
  myBuff = new char[100];

  // Set it to empty
  memset(myBuff,'\0',100);

  // Convert to string
  itoa(intValue,myBuff,10);

  // Copy the buffer into the string object
  strRetVal = myBuff;
  
  // Delete the buffer
  delete[] myBuff;

  return(strRetVal);
}
int MIKE1 (int & NUM,  int & COL)
{
	int BIT;
	BIT = NUM/COL;
	NUM= NUM % COL;
	COL=COL/2;
	return (BIT);
}


string BINARYCONVERSION (int NUM)
{
	int COL, mBIT;
	string IP;
	COL = 128;
	while (COL > 0 )
	{
	mBIT = MIKE1(NUM, COL);
	IP.append( IntToString(mBIT));
   	}
	return IP;
}


int main ()
{
  string OutString;
  int TEMP;
  char * cstr, *p;
  char InString[32];
  cout << "Enter an IP: ";
  cin >> InString;
  //This checks for proper IP V4 string length 
  while (strlen(InString) > 15)
  { 
	  cout << "Error in IP size" << endl;
	  cout << "Enter a String: ";
	  cin >> InString;
  };
   // cstr now contains a c-string copy of str
  string str (InString);
  cstr = new char [str.size()+1];
  strcpy (cstr, str.c_str());
  //This line pulls each token out of the string and assigns them each to P.

  p=strtok (cstr,".");
  while (p!=NULL)
  {
// This is a check for proper IP format
   if (GetIntVal(p) > 255)
	{
		cout <<"Invalid IP." << endl;
		return 0;
	}
 
   TEMP = GetIntVal(p);
	p=strtok(NULL,".");
	OutString.append(BINARYCONVERSION(TEMP));
  }
  //output commands. 
  cout << InString << endl;
  cout << OutString <<endl;
  delete[] cstr;  
  return 0;
 }



Is This A Good Question/Topic? 0
  • +

Replies To: IPv4 to binary conversion

#2 matthew180  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 51
  • View blog
  • Posts: 202
  • Joined: 07-January 09

Re: IPv4 to binary conversion

Posted 16 January 2009 - 12:37 PM

That seems like a hell of a lot of work just to convert a string of 4 octets into its binary representation. Personally I like a more direct route.

Matthew

#include <stdio.h>

int char_to_ipv4(char *src);

int
main(void)
{
	char ip[16];
	unsigned int ipv4;

	printf("Enter and IP address: ");
	scanf("%15s", ip);
	printf("[%s]\n", ip);

	ipv4 = char_to_ipv4(ip);
	if ( ipv4 == 0 )
		printf("Illegal IP address\n");
	else
		printf("The binary IP address is: %u [0x%08X]\n", ipv4, ipv4);

	return 0;
}
// main()


int
char_to_ipv4(char *src)
{
	unsigned int ipv4;
	unsigned int octet;
	int count;
	int i;

	ipv4 = 0;
	octet = 0;
	count = 0;

	for ( i = 0; i < 16; i++, src++ )
	{
		if ( *src == '.' || *src == 0 || i == 15 )
		{
			if ( octet > 255 )
			{
				ipv4 = 0;
				break;
			}

			ipv4 <<= 8;
			ipv4 += octet;
			octet = 0;
			count++;

			if ( *src == 0 )
				break;
		}

		else if ( *src < '0' || *src > '9' )
		{
			ipv4 = 0;
			break;
		}

		else
		{
			octet *= 10;
			octet += (*src - '0');
		}

	}

	if ( count != 4 )
		ipv4 = 0;

	return ipv4;
}
// char_to_ipv4()


This post has been edited by matthew180: 16 January 2009 - 12:38 PM

Was This Post Helpful? 0
  • +
  • -

#3 msg270  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 16-January 09

Re: IPv4 to binary conversion

Posted 16 January 2009 - 01:24 PM

View Postmatthew180, on 16 Jan, 2009 - 11:37 AM, said:

That seems like a hell of a lot of work just to convert a string of 4 octets into its binary representation. Personally I like a more direct route.

Matthew

#include <stdio.h>

int char_to_ipv4(char *src);

int
main(void)
{
	char ip[16];
	unsigned int ipv4;

	printf("Enter and IP address: ");
	scanf("%15s", ip);
	printf("[%s]\n", ip);

	ipv4 = char_to_ipv4(ip);
	if ( ipv4 == 0 )
		printf("Illegal IP address\n");
	else
		printf("The binary IP address is: %u [0x%08X]\n", ipv4, ipv4);

	return 0;
}
// main()


int
char_to_ipv4(char *src)
{
	unsigned int ipv4;
	unsigned int octet;
	int count;
	int i;

	ipv4 = 0;
	octet = 0;
	count = 0;

	for ( i = 0; i < 16; i++, src++ )
	{
		if ( *src == '.' || *src == 0 || i == 15 )
		{
			if ( octet > 255 )
			{
				ipv4 = 0;
				break;
			}

			ipv4 <<= 8;
			ipv4 += octet;
			octet = 0;
			count++;

			if ( *src == 0 )
				break;
		}

		else if ( *src < '0' || *src > '9' )
		{
			ipv4 = 0;
			break;
		}

		else
		{
			octet *= 10;
			octet += (*src - '0');
		}

	}

	if ( count != 4 )
		ipv4 = 0;

	return ipv4;
}
// char_to_ipv4()




That works but there is one problem....
you implementation produces this for the ip 192.168.128.1
3232268289 [0xC0A88001]

I get
192.168.128.1
11000000101010001000000000000001
which is the 32Bit binary representation of this IP address.

However Your representation in Hex is correct.

I'm trying to see what is going on but i'm missing it.
Was This Post Helpful? 0
  • +
  • -

#4 msg270  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 16-January 09

Re: IPv4 to binary conversion

Posted 16 January 2009 - 01:32 PM

View Postmsg270, on 16 Jan, 2009 - 12:24 PM, said:

View Postmatthew180, on 16 Jan, 2009 - 11:37 AM, said:

That seems like a hell of a lot of work just to convert a string of 4 octets into its binary representation. Personally I like a more direct route.

Matthew



That works but there is one problem....
you implementation produces this for the ip 192.168.128.1
3232268289 [0xC0A88001]

I get
192.168.128.1
11000000101010001000000000000001
which is the 32Bit binary representation of this IP address.

However Your representation in Hex is correct.

I'm trying to see what is going on but i'm missing it.


Never mind I figured it out. your code is displaying the decimal and Hex representation of the binary number...
Was This Post Helpful? 0
  • +
  • -

#5 matthew180  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 51
  • View blog
  • Posts: 202
  • Joined: 07-January 09

Re: IPv4 to binary conversion

Posted 16 January 2009 - 02:48 PM

Ah, you want to display, as text, the binary ones and zeros of the "binary" number? Well, my function is step 1 in that process. Do you need an example of displaying the ones and zeros of the number?

Matthew
Was This Post Helpful? 0
  • +
  • -

#6 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5932
  • View blog
  • Posts: 12,855
  • Joined: 16-October 07

Re: IPv4 to binary conversion

Posted 16 January 2009 - 03:19 PM

This is one of those rare instances where a C union comes in real handy. Also, using scanf you can do that conversion will little effort.

Here's an example:
#include <stdio.h>

/* note, the byte array and the int take up the same space.
this trick will not work if your ints aren't 32bits. */
typedef union {
	unsigned char oct[4];
	unsigned int intValue;
} IpAddrType;

/* don't know how you want to see it, this covers most bases */
void printAddr(const IpAddrType *addr) {
	printf("int=%u\n", addr->intValue);
	printf("ip=%d.%d.%d.%d\n", 
		addr->oct[3], addr->oct[2], addr->oct[1], addr->oct[0]);
	printf("hex=%02X.%02X.%02X.%02X\n", 
		addr->oct[3], addr->oct[2], addr->oct[1], addr->oct[0]);
}

/* from a string */
void loadFromString(const char *s, IpAddrType *addr) {
	int i, d[4];
	
	sscanf(s, "%d.%d.%d.%d", &d[3], &d[2], &d[1], &d[0]);
	for(i=0; i<4; i++) { addr->oct[i] = d[i]; } 
}

/* in action */
int main() {
	IpAddrType addr;
	
	addr.intValue = 3232235777;
	printAddr(&addr);
	
	loadFromString("192.168.1.255", &addr);
	printAddr(&addr);
	return 0;
}



Hope this helps.
Was This Post Helpful? 0
  • +
  • -

#7 Bench  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 857
  • View blog
  • Posts: 2,343
  • Joined: 20-August 07

Re: IPv4 to binary conversion

Posted 17 January 2009 - 04:32 AM

Since the original post uses in C++, I'd suggest avoiding all the rough and ready 'C' style string manipulation. C++ offers facilities to convert strings to numbers, and numerical representation in other common bases (2, 8, 10, 16). getline is a handy tool for breaking down the initial string - you can just tell it that a full stop. is an end-of-line delimiter
class ipv4
{
    enum { num_octets = 4 };
    unsigned int octets[num_octets];
public:
    ipv4(std::string addr) 
    {
        std::istringstream buf(addr);
        std::string elem;
        for(size_t i(0); i!=num_octets; ++i)
        {
            std::getline(buf, elem, '.');
            std::istringstream(elem) >> octets[i];
        }
    }
    std::string to_bin() const
    {
        std::ostringstream buf;
        for(size_t i(0); i!=num_octets; ++i)
        {
            if(i) 
                buf << '.';
            buf << std::bitset<8>(octets[i]);
        }
        return buf.str();
    }
};

int main() 
{
    ipv4 address("192.168.128.1");
    std::cout << address.to_bin();
} 
There's dozens of ways you can represent an IP address - but stringstreams should be able to cater for most of them. If you wanted to see an ipv4::to_hex() function, it might look like this
std::ostringstream buf;
for(size_t i(0); i!=num_octets; ++i)
{
	if(i) 
		buf << '.';
	buf << std::hex << octets[i];
}
return buf.str(); 


All fairly minimal with no error checking. When using streams, its a good idea to check that the stream hasn't failed before doing anything with data you retrieve from it. eg
std::istringstream ibuf("192");
if( ibuf >> octets[i] )
    // OK
else
    // Error retrieving octets[i] from ibuf 

This post has been edited by Bench: 17 January 2009 - 04:33 AM

Was This Post Helpful? 0
  • +
  • -

#8 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5932
  • View blog
  • Posts: 12,855
  • Joined: 16-October 07

Re: IPv4 to binary conversion

Posted 17 January 2009 - 07:59 AM

View PostBench, on 17 Jan, 2009 - 05:32 AM, said:

Since the original post uses in C++, I'd suggest avoiding all the rough and ready 'C' style string manipulation.


I would normally agree, but the OP contained a whole lot of C style fusion. I was just going with the flow. I'm not sure that all the streaming and casting is easier to follow than a simple format string, in any case.

For completeness, and more "rough and ready" action, here's one way to spit out the binary representation.
void printByteAsBinary(unsigned char byte) {
	int i, mask = 0x80;
	for(i=0; i<8; i++) {
		printf("%d", (byte & mask)>0);
		mask >>= 1; 
	}
}


Was This Post Helpful? 0
  • +
  • -

#9 msg270  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 16-January 09

Re: IPv4 to binary conversion

Posted 19 January 2009 - 06:54 PM

Thanks everyone for your input. It looks like I got my answer, My code works but is HUGE compared to what I've seen here. I'm going to try put my code on a diet and learn from this. Thanks again baavgai, Bench and Matthew
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1