c++rangeipv4sockaddr-in

Compare ipv4 address - sockaddr_in


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?


Solution

  • 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))
    );