简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM