I am trying to write a function to check if my ip is within subnet mask, as below: -
bool isIPinSubnet(CString ip, CString network, int keepbits)
{
ULONG ip_addr = 0;
ULONG network_addr = 0;
UINT32 mask_addr = ~(~(UINT32)(0) >> keepbits);
ip_addr = inet_addr(ip);
network_addr = inet_addr(network);
ULONG net_lower = (network_addr & mask_addr);
ULONG net_upper = (net_lower | (~mask_addr));
if ( ip_addr >= net_lower && ip_addr <= net_upper ) {
return true;
}
return false;
}
Problem is its not working. On debugging, I saw that the inet_addr() function is returning the long for IP in reverse order.
For example, if I am doing this , isIPinSubnet("192.168.0.15","192.168.0.1",24);
the long inet_addr returns for IP: 192.168.0.15
is 251701440
and IP: 192.168.0.1
is 16820416
.
Checking here http://www.smartconversion.com/unit_conversion/IP_Address_Converter.aspx
251701440
corresponds to IP: 15.0.168.192
, and
16820416
corresponds to IP: 1.0.168.192
which clearly is the reverse of what we passed to inet_addr.
Why is this behaving this way? How to fix it?
From the comments by @Someprogrammerdude, on question,the issue is due to mismatch of Network byte order versus host byte order. To fix the problem in my code, we can use htonl and it works well.
bool isIPinSubnet(CString ip, CString network, int keepbits)
{
ULONG ip_addr = 0;
ULONG network_addr = 0;
UINT32 mask_addr = ~(~(UINT32)(0) >> keepbits);
ip_addr = htonl (inet_addr(ip)); //Thanks to @ChrisBecke
network_addr = htonl (inet_addr(network));
ULONG net_lower = (network_addr & mask_addr);
ULONG net_upper = (net_lower | (~mask_addr));
if ( ip_addr >= net_lower && ip_addr <= net_upper ) {
return true;
}
return false;
}