We know the IPv4 Address is 32-bit which consists of four integers from 0 to 255 inclusive. We can use a 32-bit integer to represent a valid IP address. The following is a C macro that #defines a procedure to convert a IP address (given four numbers) to a 32-bit integer.
1 2 | #define IPV4_ADDR(a, b, c, d)(((a & 0xff) << 24) | ((b & 0xff) << 16) | \ ((c & 0xff) << 8) | (d & 0xff)) |
#define IPV4_ADDR(a, b, c, d)(((a & 0xff) << 24) | ((b & 0xff) << 16) | \ ((c & 0xff) << 8) | (d & 0xff))
We can also use the function implementation:
1 2 3 4 | inline unsigned int getIPAddress(char a, char b, char c, char d) { return (((a & 0xff) << 24) | ((b & 0xff) << 16) | ((c & 0xff) << 8) | (d & 0xff)); } |
inline unsigned int getIPAddress(char a, char b, char c, char d) { return (((a & 0xff) << 24) | ((b & 0xff) << 16) | ((c & 0xff) << 8) | (d & 0xff)); }
To convert a 32-bit integer back to a IP Address, we can shift the number to the right for 24, 16 and 8 bits.
–EOF (The Ultimate Computing & Technology Blog) —
GD Star Rating
loading...
207 wordsloading...
Last Post: Teaching Kids Programming - ROT13 String Cipher Algorithm in Python
Next Post: Teaching Kids Programming - Implement the String.Find Method in Python