There are a few "layers" to get through to answer your question. Lets start at the beginning:
A device who wants to speak/access the Internet (or any network) must have an IP address. The IP address serves as the identity of the device on the network.
IP addresses, however, do not exist on islands. Instead, IP Addresses exist within groups known as Networks, or Local Networks, or Sub Networks, or a plethora of similar names.
The reason this is important is because if this wasn't the case, a Router would have to know the location of every IP address in the world. Which in IPv4, means 4.2~ billion different "routes". Being able to organize IP addresses into groups, means Routers don't have to learn NEARLY as many routes.
As such, anytime any device is configured with an IP address, it must also be configured with a Subnet Mask. The Subnet Mask will serve to tell the device just how many other IP addresses are within its grouping (or Network). This is all done through the process of what is called Subnetting -- you can read more about the process here.
For example, a device configured with the IP address 10.1.1.30
and the Subnet Mask 255.255.255.0
will intrinsically know the size of its Network contains every IP address in the range 10.1.1.0
through 10.1.1.255
.
A router configured with the same IP address would work the same way and also intrinsically know the size of the Network it is directly connected to. Which will then tell the Router what Directly Connected network it is attached to.
If a router has multiple interfaces, it will repeat the same process for each interface, until it knows ALL the Networks it is directly connected to.
That said, there is so much more to all this than what was summarized above. But I wanted to focus on just answering your question. For more information, I highly suggest reading through this article series that describes how packets move through a network, and specifically the article that picks apart how a Router routes packets. When you've done that, you can see it all tied together in this video.
Disclaimer: I wrote the aforementioned articles