Wednesday, 10 June 2015

Linux routing: How to add/delete route in a Linux machine

Route command is closely related to kernel's IP routing table. This is used to set up a static route to a specific network.

How to see the machine's current routing table:

The current routing table of a Linux machine can be found using the "route"  command.


How to add a new route:

Use the below command to add a new route to the routing table.

-------
route add -net 192.168.125.0 netmask 255.255.255.0 gw 192.168.125.1 dev eth0
-------

The above command will add network "192.168.125.0" with netmask "255.255.255.0" and gateway "192.168.125.1"  to the device eth0.

Syntax: 
---------
route add -net/-host <IPaddress> netmask <subnetmask> gw <Gateway IPaddress> dev <Ethernet Interface>
--------

As the syntax states the (-net/-host) can be a host IP address or a network itself.

How to delete a route from routing table:

Syntax:
---------
route del -net/-host <IPaddres> netmask <subnetmask> gw <GatewayIP address> dev <Ethernet Interface>
-----------

An example is below:

-------
route del -net 192.168.125.0 netmask 255.255.255.0 gw 192.168.125.1 dev eth0
-------

How to add a default route:

Example:
--------
route add default gw 192.168.5.0 dev eth0
--------

The above command will add default gateway as "192.168.5.0".

How to add static routes permanently: 

The newly added routes will be deleted if we restart network service.

To make it  permanent even after restarting network services add the routing rule in file “/etc/sysconfig/network-scripts/route-eth0″.

This file will not be available by default we have to create it manually.

Syntax:
----------
<Target host/network address>  via  <gateway_address> dev <ethX>
----------

An example of such file is as below:
-------------
cat /etc/sysconfig/network-scripts/route-eth0
192.168.150.0/23 via 255.255.254.0 dev eth0
-------

Then restart the network service, The route will not be removed.


How to add a reject rule:

To add a reject rule for a certain subnet:

Example:
-------
route add -net 192.168.150.0 netmask 255.255.254.0 reject
--------

This command will add a rejecting route for the private network “192.168.150.0.” So if any packets come in from "192.168.150.0" they will be rejected out prior to hitting the default route.

Kool :)



No comments:

Post a comment

Note: only a member of this blog may post a comment.