Marco said:
How to decide the IP typed by user is valid and match the subnet mask ?
Please show me some code. Thanks!
If the IP address is legal then there are only two cases that aren't legal,
broadcast and subnet address. That may not help you much. Just because it
isn't the broadcast or subnet address doesn't mean it is in the correct
subnet. Here's pseudo-code validation that it is an address within the
subnet:
// Convert the entered address and mask to binary
in_addr addr;
in_addr mask;
addr.S_un.S_addr = inet_addr(szAddr);
mask.S_un.S_addr = inet_addr(szMask);
// Extract the network address - zero address bits where mask bits are zero
u_long netaddr = addr.S_un.S_addr & mask.S_un.S_addr;
// The IP address can't be the network address
if (addr.S_un.S_addr == netaddr)
{
return FAIL;
}
// Extract the broadcast address - set all address bits that are zero in the
mask
u_long bcastaddr = addr.S_un.S_addr | ~mask.S_un.S_addr;
// The IP address can't be the broadcast address
if (addr.S_un.S_addr == bcastaddr)
{
return FAIL;
}
return SUCCESS;
Please remember that this doesn't guarantee that the address entered is in
the correct subnet for the cabling, that can't be determined from the subnet
mask. For example, if I have cabling using network 192.168.0.0/24 the
subnet is 192.168.0.0 and the broadcast is 192.168.0.255. If I enter
10.0.0.5 as my IP address I can only determine from a 24 bit mask that this
address is legal (subnet 10.0.0.0 and broadcast 10.0.0.255) given the mask
but it isn't in the same routing domain as the rest of the nodes on the
cabling. You might be able to use hand-crafted DHCP or ARP queries to
determine the appropriate subnet for the cabling and it should then be
possible to compare it with netaddr to validate the address completely.
I've done DHCP UINFORM queries by hand before and they can sometimes be used
to get the local router address and that can often be used to determine the
correct subnet address.