Converting IP Address bytes to integer

2k Views Asked by At

For example:

1. To convert 32-bit IP address (IPv4):

unsigned char ByteAddress[4];
unsigned int* IntegerAddress;

IntegerAddress = reinterpret_cast<unsigned int*> &ByteAddress ;

Then I can use IntegerAddress to compare ip addresses.

2. To convert 128-bit IP address (IPv6):

unsigned char ByteAddress[16];
uint64_t* LongAddress;

LongAddress = reinterpret_cast<uint64_t*> &ByteAddress

Then I can use LongAddress [0] and LongAddress[1] to compare ip addresses.

Is it preferred over using bit shift operators (as it is quicker) ? Is it good programming practice? Would it work for all platforms (especially unix and windows 64) and compilers (C++, VS2010)

1

There are 1 best solutions below

4
dreamer On

I think, you can use unions for that

union Int32And4Bytes {
int32_t IntegerValue;
unsigned char ByteArray[4];
};

It should be aligned correctly, IIRC.