Finding gateway address

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
I'm writing a subroutine that will derive the gateway address for a
specified IP address and subnet mask.

I started writing it using elsif for each subnet mask with nested if
statements, but the code is getting very long due to the number of possible
subnet masks.

Question: Does anybody know of a module or cleanly written code segment
that will take the subnet mask and IP address, then return the gateway
address? (Reinventing the wheel is great for practice, but it is
devistating on productivity.)



Re: Finding gateway address

Quoted text here. Click to load it

How are you determining the gateway address for a given network? Which
machine is gateway is a matter of local network policy: there is no way
to determine it numerically in general. Presumably your network has some
rule like 'the gateway is always the .1 address on the network' but we
have no way of knowing what.

Finding the network number from an address and mask is easy:

    my ($paddr, $pmask) = map {
        pack "C4", split /\./
    } $addr, $mask;

    my $pnet = $paddr & $pmask;

    my $net = join ".", unpack "C4", $pnet;

If you need to manipulate ip addreses as numbers, you will find the "N"
pack/unpack format useful as well; for instance, to find the .1 address
on the above network you can use something like

    my $gw =
        join ".",
        unpack "C4",
        pack "N",
        1 + unpack "N",

It's important here not to fall into the trap of using inet_aton and the
associated functions from They produce address packed
suitably for passing to your system's socket functions, and the exact
format is system-dependant.


Re: Finding gateway address

Quoted text here. Click to load it


That is far simplier then the 60+ lines I wrote. They both give the same
results, but your code is much cleaner, efficient, and scalable.

As you mentioned, our policy is to use the .1 address on the network.
Therefore, $gw is the targetted value.

Thank you very much!


Site Timeline