Subnets and
netmasks are both important practical issues in
internet routing, and it can sometimes be confusing to understand how they fit together and what they are supposed to do.
The best way to start is to explain what question subnets and netmasks answer. They basically answer the question: Do I just throw this packet of bytes on the wire (typically an Ethernet cable these days) and hope that the destination computer is going to pick it up, or, do I ask the special machine, called the gateway, that knows how to send it to the outside world, to take care of it?
Another way to put it: Let's say we want
to connect to another machine. Then I have to ask how to get pieces of
information to the machine - this is called routing. Typically on
Ethernet, there are two ways to get the information to another machine. If
it's on the same piece of wire, and this is what a subnet really is, then we just connect to it
directly, if it's not, we go through a gateway.
The question is then: How do I decide whether something's on the same piece of ethernet as me or not?
Answer: If the ip address looks similar to mine, then it must be on the
same subnet. Otherwise, go through the gateway.
Question: But what does "similar" mean?
Answer: This is where the subnet mask comes in. Say the netmask is
255.255.255.0. This is decimal for the binary
11111111111111111111111100000000. If the IP addresses match (ie. are
equal) on all the bits where the mask is one, it is assumed to be on the
same subnet. 255.255.255.0 basically means: The first three numbers of the
IP address have to be the same.
Example: 192.168.0.2 wants to talk to 192.168.0.3. The subnet mask is
255.255.255.0, so since the first three numbers of the IP address match,
it just connects directly through ethernet to 192.168.0.3 (in fact it uses ARP to work out how to do this).
But say 192.168.0.2 wants to talk to 192.168.1.2. Then it says "oh, that
IP address is not on the same subnet, I'll have to go through the
gateway." Let's say the gateway is 192.168.0.1. Then 192.168.0.2 sends the
packet to 192.168.0.1 expecting that 192.168.0.1 will pass it on to
192.168.1.2.
Of course the gateway has to be on the same subnet as the machine that's sending the packets.