We have
documentation for this of course
The concept is really straight forward. More is described in the Handbook linked above, but quick intro is:
I am computer, I have packet to send, what I will do?
- Is it for local network address (mask is used here, that /24 or 255.255.255.0 for example). If it is, get MAC for this address and send directly.
- If not, is it for network I know route to? If it is, send it to gateway for given network. Routing tables are used here, you can see them by
netstat -r command. End user computer usually has only few entries related to local network(s).
- If both previous answers was negative, send it to default gateway.
And what about receiving? If packet is for me, process it, else drop it. And here start magic. If you enable gateway (which turns forwarding sysctl on on boot, see link above), it can be said in really simplified way, that such machine treats others computers packets as its own and apply procedure described above on them instead of dropping them.
However, it is not enough if you have address not routable on internet (private addresses like 192.168.x.x etc., see
RFC 1918). With such address, computer at destination would not be able to reply to you (besides fact that all routers on route should drop it on its way there already). So here magic part two start. With NAT enabled, router change source address in the packet header to its own (and keep information about it to reverse it for returning packets), because it is for sure, that device which will get this packet know route back. This may be done several times, consider following example
Home computer address 192.168.0.2/24 <------------> Home router internal interface 192.168.0.1/24|Home router external interface 10.0.0.2/24 <------------------------> Internet provider interface facing customer 10.0.0.1/24|Providers network|Providers interface facing internet with "public" address 8.8.8.8
In the example above, all addresses, excluding last, are not internet routable. Only last one is (Google DNS used as example here), so there would be at least two address translations, at home router and somewhere in the ISP network.