Linux gateway how to

How to set the Default gateway

You can use route like in route add default gw 192.168.0.254 for example.

And if route is not present, but ip is, you can use it like this: ip route add default via 192.168.0.254 dev eth0 , assuming that 192.168.0.254 is the ip of your gateway

ifconfig is deprecated on Linux and furthermore, it’s the wrong tool for the job. To set the default gateway on Linux use the ip command as follows:

ip route add default via dev # e.g. ip route add default via 192.168.0.101 dev eth0 

For remove gateway in Linux Command : route delete default gw 192.168.1.1 eth1

For add gateway in Linux Command : route add default gw 192.168.1.250 eth1

example: route add default gw 192.168.1.2 eth0

OR use hostname such as dsl-router:

route add default gw dsl-router eth0 

Or use the ip command (newer syntax) to route all traffic via 192.168.1.254 gateway connected via eth0 network interface for example:

ip route add 192.168.1.0/24 dev eth0 
ip route add 192.168.1.0/24 via 192.168.1.254 

You must log in to answer this question.

Highly active question. Earn 10 reputation (not counting the association bonus) in order to answer this question. The reputation requirement helps protect this question from spam and non-answer activity.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.17.43535

Linux is a registered trademark of Linus Torvalds. UNIX is a registered trademark of The Open Group.
This site is not affiliated with Linus Torvalds or The Open Group in any way.

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Интернет шлюз на Ubuntu / Debian

Обновлено

Обновлено: 16.02.2023 Опубликовано: 23.01.2019

  1. Включение redirect на уровне ядра.
  2. Настройкой брандмауэра.
  3. Опционально, настройка проброса портов.

Настройка ядра системы

sysctl -p /etc/sysctl.d/gateway.conf

Если мы получим ошибку sysctl command not found, либо нужно установить пакет:

либо перезайти в режим суперпользователя с загрузкой его окружения:

В случае с единственным сетевым адаптером больше ничего делать не потребуется — Ubuntu начнет работать как Интернет-шлюз.

В случае с несколькими сетевыми адаптерами, настраиваем сетевой экран.

Настройка брандмауэра

Как правило, управление брандмауэром netfilter в Linux на базе Debian выполняется с помощью утилиты iptables.

Iptables

Предположим, что сеть Интернет настроена через интерфейс ens160, а локальная сеть доступна через ens32. Создадим правило:

iptables -t nat -I POSTROUTING -o ens160 -j MASQUERADE

Если на сервере для доступа в локальную и глобальную сети используются разные сетевые интерфейсы, нам может понадобиться создать еще два правила.

Читайте также:  Установка linux os zorin os

iptables -I FORWARD -i ens32 -o ens160 -m state —state RELATED,ESTABLISHED -j ACCEPT

iptables -I FORWARD -i ens32 -o ens160 -j ACCEPT

* интерфейс ens160, как условились ранее, используется для доступа в Интернет. Интерфейс ens32 — локальная сеть.

Сохраняем настройки iptables:

apt install iptables-persistent

Проброс портов (Port Forwarding)

Необходим для перенаправление сетевых запросов на сервер, стоящий за NAT и не имеющий прямого выхода во внешнюю сеть.

Iptables

Настройка выполняется двумя командами:

iptables -t nat -A PREROUTING -p tcp -m tcp -d 10.8.232.111 —dport 25 -j DNAT —to-destination 192.168.0.15:8025

iptables -t nat -A POSTROUTING -p tcp -m tcp -s 192.168.0.15 —sport 8025 -j SNAT —to-source 10.8.232.111:25

iptables -t nat -A PREROUTING -p tcp -i eth0 —dport 25 -j DNAT —to-destination 192.168.0.15:8025

iptables -A FORWARD -p tcp -d 192.168.0.15 —dport 8025 -m state —state NEW,ESTABLISHED,RELATED -j ACCEPT

* где eth0 — внешний сетевой интерфейс.

iptables -I INPUT 1 -p tcp —dport 8025 -j ACCEPT

* обратите внимание, что мы разрешаем порт, на который переводим запрос, так как цепочки POSTROUTING и PREROUTING работают до цепочки FILTER, а потому открывать нужно не входящий порт (25), а тот, на который назначается пакет (8025).

Не забываем сохранить правила:

Источник

How to Set the Default Gateway on Ubuntu

All the devices on your network rely on the default gateway for communication. Data packets pass through the router to and from your network before being routed to the particular device that owns the packet.

Each operating system comes with a default gateway. However, you can temporarily or permanently change the default gateway to add another route for your network devices. You can use the IP command on Ubuntu to modify your default gateway.

Checking the Default Gateway

Changing the default gateway is common when you have different sub-networks or when you must point a specific machine to a particular gateway. Before changing the default gateway, let’s list the available routes.

Use the list option with the IP command or its shorthand r to stand for the route.

The default gateway has the default keyword in it. If you configured multiple routes on your network, you can use the grep command to filter the router and get the default gateway.

Use the following command:

The current default gateway is 192.168.88.1 on enp0s3 interface. Let’s proceed to set a new default gateway.

How to Set a New Default Gateway

The ip command uses the route option to set the new default gateway. You must specify the type of route that you want to add. In our case, it’s “default”.

For instance, let’s set the default gateway as 192.168.88.10.

Suppose we want to set the default gateway for a particular network interface. In that case, specify the network interface after the gateway. In our case, the interface is enp0s3.

Note that we must add sudo to use the administrator privileges since we are editing the routing table for Ubuntu which is an administrative task.

We can use the list or route options to verify the newly added default gateway.

Note how the currently added default gateway is the one that we specified earlier. In the previous output, we now have two default gateways. The keynote is that the changes we made are temporary until you add them to the network manager configuration files.

Читайте также:  Ora 27102 linux cannot allocate memory

In the previous case, we can delete the added gateway such that we remain with only one.

Use the delete keyword to remove the added gateway.

If we check the available default gateway after running the delete command, we confirm that we only have one default gateway remaining which is 192.168.88.1.

Suppose we want to make the permanent network changes to implement the new gateway. We must edit the configuration file. Open the network manager file using a file editor of your choice. In this case, let’s use gedit with the following command:

Add the new gateway using the following presented format. Make sure that the spacing is set to two whitespaces with the correct indention. Once edited, save the file and exit the editor.

Before applying the changes using the netplan command, run a dry test.

If you are sure with the new network configuration, press the enter key. Otherwise, the changes will revert to the previous settings after the specified seconds.

Conclusion

Ubuntu comes with a default gateway, but that doesn’t mean that you can’t set a new gateway. This guide covered everything about adding a new gateway using the ip command and how to save the changes permanently to the configuration file.

About the author

Denis Kariuki

Denis is a Computer Scientist with a passion for Networking and Cyber Security. I love the terminal, and using Linux is a hobby. I am passionate about sharing tips and ideas about Linux and computing.

Источник

How can I use Linux as a Gateway?

NOTE: If client devices ( computer B in this example) want to obtain internet through the gateway computer, maybe they still need to configure nameserver resolution. This is not explained here (a gateway does not necessarily serve internet).

I am trying to understand the fundamentals of networks routing.
So I am experimenting with my LAN (I don’t need internet for now, just LAN communications). I know the network configuration matters are a rather complex thing, but I am just trying to make a computer (say A) to act as a gateway for another (say B) (both running Ubuntu Linux).
I only need B to be capable to reach the router, that is only reachable for A. This is the case:

Router for computer A --> 192.168.0.1 Computer A - eth0 --> 192.168.0.2 Computer A - eth1 --> 192.168.1.1 Computer B - eth0 --> 192.168.1.2 

Computer A connects fine to router.
Computer A and B connect fine (ping, SSH. etc) between them.
Computer B can not reach the router for computer A. I was thinking that just adding on B Computer A as default gateway and activating IP Forwarding on A would make B to be able to reach the router for A:

luis@ComputerB:~$ sudo route add default gw 192.168.1.1 luis@ComputerB:~$ sudo routel target gateway source proto scope dev tbl 127.0.0.0 broadcast 127.0.0.1 kernel link lo local 127.0.0.0 8 local 127.0.0.1 kernel host lo local 127.0.0.1 local 127.0.0.1 kernel host lo local 127.255.255.255 broadcast 127.0.0.1 kernel link lo local 192.168.1.0 broadcast 192.168.1.2 kernel link eth0 local 192.168.1.2 local 192.168.1.2 kernel host eth0 local 192.168.1.255 broadcast 192.168.1.2 kernel link eth0 local default 192.168.1.1 eth0 169.254.0.0 16 link eth0 192.168.1.0 24 192.168.1.2 kernel link eth0 
root@ComputerA:~$ echo 1 > /proc/sys/net/ipv4/ip_forward 
luis@ComputerB:~$ ping 192.168.0.1 PING 192.168.0.1 (192.168.0.1) 56(84) bytes of data. ^C 

(No ping response) Is this the correct procedure to make a computer running Linux to act as a gateway for another computer in a simple manner?

Читайте также:  Realtek ethernet driver linux

Источник

Setting Up Linux Network Gateway Using iptables and route

Sharing the networking is important and setting up a gateway is a good solution to it. Building up the gateway on a Linux box is easy, cost efficient and reliable. With a Linux box, you can share the internet connection or the only cable connected to the network.

The Linux box network configuration

The Linux box that we use has this configuration:

NIC1: eth0 with ip 192.168.0.1 connected to our small local area network.

NIC2: eth1 with ip 198.51.100.1 connected to another network such as a public network connected to Internet.

Now we want to share this Linux box’s connection with the other computers in the local area network with ip in 192.168.0.0/16.

Setting up the gateway

All the operations in this part is done under root on the Linux gateway.

Manipulate the IP route table

# ip route add 192.168.0.0/16 dev eth0
# route add -net 192.168.0.0/16 dev eth0

Enable Linux IP forwarding

# sysctl -w net.ipv4.ip_forward=1
# echo 1 > /proc/sys/net/ipv4/ip_forward

You can also make the setting permanent in `/etc/sysctl.conf by adding a line below to /etc/sysctl.conf:

Set up SNAT by iptables

Change the source IP of out packets to gateway’s IP. Don’t worry since iptables will automatically change the replied packet’s destination IP to the original source IP.

# iptables -t nat -A POSTROUTING ! -d 192.168.0.0/16 -o eth1 -j SNAT --to-source 198.51.100.1

Instead of using SNAT, another way is to use MASQUERADE:

# iptables -t nat -A POSTROUTING ! -d 192.168.0.0/16 -o eth1 -j MASQUERADE

However, please note that, for static IPs, SNAT is suggested as from the iptables man page:

> This target is only valid in the nat table, in the POSTROUTING chain. It should only be used with dynamically assigned IP (dialup) connections: if you have a static IP address, you should use the SNAT target. Masquerading is equivalent to specifying a mapping to the IP address of the interface the packet is going out, but also has the effect that connections are forgotten when the interface goes down. This is the correct behavior when the next dialup is unlikely to have the same interface address (and hence any established connections are lost anyway).

And then make sure that the other iptables tables do not deny these connections. If you have problem in this step, you can try

# iptables -F # iptables -t nat -F # iptables -t nat -A POSTROUTING ! -d 192.168.0.0/16 -o eth1 -j SNAT --to-source 198.51.100.1

to allow all connections in. But there may be security problems after open all ports to the public. Firewall should be carefully configured.

By now, the we have set up the Linux gateway.

Client side configuration

On client such as Linux or Windows with IP 192.168.0.4, set the network connection to use this profile:

The configuration profile:

Gateway: 192.168.0.1.

DNS Server: your ISP’s DNS server IP addresses.

The method to configure the network maybe different from using NetworkManager and network and Windows.

You can try this command on Linux:

# ip route add default via 192.168.0.1 dev eth0
# route add default gw 192.168.0.1 eth0

You can use this GUI/TUI tool on Fedora / RedHat / CentOS systems:

Источник

Оцените статью
Adblock
detector