Skip to content

Instantly share code, notes, and snippets.

@mpenick
Last active October 19, 2015 16:52
Show Gist options
  • Select an option

  • Save mpenick/90fde41a4ef6b468b77c to your computer and use it in GitHub Desktop.

Select an option

Save mpenick/90fde41a4ef6b468b77c to your computer and use it in GitHub Desktop.
#include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
int invalid_compare(uint32_t a, uint32_t b) {
// Note: Conversion from unsigned to signed int. This will fail for any
// spread of a - b that's greater than INT32_MAX.
return a - b;
}
uint32_t from_string(const char* addr) {
uint8_t a = 0, b = 0, c = 0, d = 0;
sscanf(addr, "%hhu. %hhu.%hhu.%hhu", &a, &b, &c, &d);
return (a << 24) | (b << 16) | (c << 8) | d;
}
bool is_fail(const char* addr1, const char * addr2) {
uint32_t a = from_string(addr1);
uint32_t b = from_string(addr2);
return (a > b && invalid_compare(a, b) <= 0) || (a < b && invalid_compare(a, b) >= 0);
}
void test_compare(const char* addr1, const char * addr2) {
printf("%16s <=> %16s (%s)\n", addr1, addr2, is_fail(addr1, addr2) ? "fail" : "success");
}
int main() {
test_compare("10.10.10.10", "10.10.10.9");
test_compare("10.10.10.9", "10.10.10.10");
test_compare("190.0.0.0", "10.0.0.0");
test_compare("10.0.0.0", "190.0.0.0");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment