How can I get the netmask from an IP address?

This is not possible. If it were possible there would be no reason to have a netmask at all as it could be automatically determined.

The netmask is used to specify the IP range a 'network' starts and stops at. This range is arbitrary.

For example, with the IP address 192.168.0.140:
With the netmask of 255.255.255.0 (/24 in cidr notation) the IP range would be 192.168.0.1 - 192.168.0.254.
With a netmask of 255.255.255.128 (/25 in cidr notation) the IP range would be 192.168.0.129 - 192.168.0.254.


You cannot in most cases, because of classless networks. A given IPv4 address can have 30 different netmasks.


netmask are mainly used to distinguish local addresses in the same sub-network from addresses outside which are reachable only over a gateway.

So if you know all (= currently or in the future used) IP addresses in the same sub-network, you can construct a netmask which contains them all. For example if 192.168.2.4 and 192.168.2.253 should be in the same sub-network, netmask 255.255.255.0 (equals to the ip range 192.168.2.0-255 or in cidr notation 192.168.2.0/24) works.