Skip to content

Instantly share code, notes, and snippets.

@Flushot
Last active April 22, 2016 21:01
Show Gist options
  • Save Flushot/600be899c807ea7caf6e6ea700e3417f to your computer and use it in GitHub Desktop.
Save Flushot/600be899c807ea7caf6e6ea700e3417f to your computer and use it in GitHub Desktop.
Some IP utility methods
#include <stdio.h>
#include <string.h>
#include <stdint.h>
/**
* Convert an IPv4 address string into a long
*
* @param ip_addr IPv4 address string to convert
* @return long representation of IP
*/
uint32_t ip2long(char *ip_addr) {
uint32_t long_addr = 0;
char *dot = ".";
char *token = strtok(ip_addr, dot);
while (token != NULL) {
long_addr <<= 8;
long_addr |= atoi(token) & 0xFF;
token = strtok(NULL, dot); // get next token
}
return long_addr;
}
/**
* Convert a long into an IPv4 address string
*
* @param long_addr long to convert
* @param ip_addr_out output buffer for IPv4 address string
*/
char *long2ip(uint32_t long_addr, char *ip_addr_out) {
uint8_t i;
char octet[4];
char *dot = ".";
ip_addr_out[0] = 0;
for (i = 0; i < 4; ++i) {
snprintf((char *)&octet, 4, "%d",
(long_addr >> (24 - 8 * i)) & 0xFF);
strcat(ip_addr_out, (char *)&octet);
if (i < 3) {
strcat(ip_addr_out, dot);
}
}
return ip_addr_out;
}
/**
* Matches IP addresses using net_bits significant bits.
*
* @param test_ip_addr IPv4 address to test
* @param match_ip_addr matching IPv4 address or network
* @param net_bits number of network bits to use when matching against match_ip_addr (0-32)
* @return 1 if match or 0 if no match
*/
int ip_matches(char *test_ip_addr, char *match_ip_addr, uint8_t net_bits) {
uint32_t mask = ~0UL << (32 - net_bits);
return ((ip2long(test_ip_addr) & mask) == (ip2long(match_ip_addr) & mask)) ? 1 : 0;
}
int main(int argc, char **argv) {
uint8_t net_bits = 24;
printf("matches? %d\n", ip_matches("192.168.2.1", "192.168.2.0", net_bits));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment