Consider the folowing snippet:
#define IPV4_MAX_BYTELEN 4
struct gen_entry
{
struct in_addr addr;
struct in_addr mask;
..
};
unsigned char key[40];
memcpy (key, &fec->addr, IPV4_MAX_BYTELEN);
memcpy (key + IPV4_MAX_BYTELEN, &fec->mask, IPV4_MAX_BYTELEN);
..
What I want is to merge both IP address and mask in a binary key.
Is it ok to merge it this way, provided that array size is enough for
this purpose? (or I’m missing something?)
Thanks !
This would normally be called “concatenate” rather than “merge”.
For portability, you could explicitly use the
s_addrfield ofstruct in_addr, rather than assuming it’s the first thing. Although maybe that’s guaranteed by Posix, I’m not sure. I think Posix also guarantees that thesizeofan IPv4 address is 4 bytes, so you’re OK there.Your code doesn’t clear the other 32 bytes of the array, so it can’t (yet) be used as a key in any useful way. Unless
keyis defined at file scope, in which case it’s initialized to zeroes.Other than those minor niggles, I don’t see anything wrong with what you’re doing.
As a hypothetical portability issue – even if there are no padding bytes before the
s_addrfield ofstruct in_addr, if there are padding bits in the value then you could in theory get false negatives. Suppose you construct two keys from different sources that have the same value but different padding bits – then they should yield the same key but in fact do not. I wouldn’t worry about it, though: any implementation weird enough to have padding bits in integer types is probably too weird to provide the Posix networking API.