0

I want to know if some address is in range 10.0.0.0 - 10.255.255.255.

int localAddress = 0;
struct sockaddr_in localOneFirst;
struct sockaddr_in localOneLast;

inet_pton(AF_INET, "11.0.0.0", &(address.sin_addr));
inet_pton(AF_INET, "10.0.0.0", &(localOneFirst.sin_addr));
inet_pton(AF_INET, "10.255.255.255", &(localOneLast.sin_addr));

if((address.sin_addr.s_addr >= localOneFirst.sin_addr.s_addr) && (address.sin_addr.s_addr <= localOneLast.sin_addr.s_addr)) {
    localAddress = 1;
}

My address 11.0.0.0 is greater than 10.255.255.255 but this program shows it's not.

Because value of "address.sin_addr.s_addr" is 11 and value of "localOneFirst.sin_addr.s_addr" is greater.

So how can I recognize if some address is in this range?

JJ DD
  • 15
  • 3
  • 1
    Possible duplicate of [How to compare socket address in C?](https://stackoverflow.com/questions/15461350/how-to-compare-socket-address-in-c) – v1bri Nov 09 '17 at 20:57
  • no, it's different – JJ DD Nov 09 '17 at 21:01
  • Not sure what the problem is. Compare either first octet of 32 bit integer, or, since you already have the dotted representation, a number before first dot. – SergeyA Nov 09 '17 at 21:34

1 Answers1

0

sockaddr_in addresses are stored in network byte order (big endian). If your code is running on a big endian system, the values will not compare correctly.

Use ntohl() when comparing the values:

bool localAddress = (
  (ntohl(address.sin_addr.s_addr) >= ntohl(localOneFirst.sin_addr.s_addr)) &&
  (ntohl(address.sin_addr.s_addr) <= ntohl(localOneLast.sin_addr.s_addr))
);
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770