Internet and linux ubuntu

Содержание
  1. Интернет шлюз на Ubuntu
  2. Настройка ядра системы
  3. Настройка брандмауэра
  4. Iptables
  5. Проброс портов (Port Forwarding)
  6. Iptables
  7. Как настроить интернет в Линуксе
  8. Настройка интернета в Linux
  9. Как настроить интернет в Ubuntu
  10. Как подключить интернет в Линукс Минт
  11. Классический вариант
  12. 1 вариация
  13. 2 вариация
  14. Частые ошибки при настройке сети в Linux
  15. Заключение
  16. Домашний интернет-шлюз. Начальная настройка 6-портового мини-компьютера на Ubuntu Server 20.04 LTS
  17. Введение
  18. Netplan
  19. DHCP-сервер
  20. Заключение
  21. Ubuntu Documentation
  22. Introduction
  23. GUI Method via Network Manager (Ubuntu 14.04, 16.04)
  24. GUI Method via Network Manager (Ubuntu 12.04)
  25. GUI Method via Network Manager (Ubuntu 11.10)
  26. GUI Method via Network Manager (Ubuntu 9.10 and up)
  27. Wireless Ad-Hoc connection sharing scenario
  28. Ubuntu Internet Gateway Method (iptables)
  29. Gateway set up
  30. Configure internal network card
  31. Enable routing
  32. Client set up
  33. Disable networking
  34. Give the client a static IP address
  35. Configure routing
  36. Configure DNS servers
  37. Restart networking
  38. Advanced Gateway Configuration
  39. DHCP/DNS server
  40. Other approaches
  41. Alternate server software (CLI)
  42. Alternate NAT
  43. Dedicated DHCP server
  44. Dedicated DNS server
  45. Alternate gateway software (GUI)
  46. Simple iptables example

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

Процесс настройки шлюза включает выполнение нескольких шагов:

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

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

Открываем следующий файл:

Добавляем в него строку:

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

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

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

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

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

Iptables

Настройка выполняется из расчета, что сеть Интернет настроена через интерфейс ens160:

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

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

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

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

* предполагается, что ens32 используется для внутренней сети, а ens160 — внешней.

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

apt-get 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).

Источник

Как настроить интернет в Линуксе

Часто у начинающих пользователей возникает проблема того, как правильно настроить Интернет на Линуксе. И это неудивительно, ведь это универсальная платформа помимо своих достоинств имеет ряд нюансов, которые обязательно стоит учитывать. Причем настройка Интернета на линуксе и настройка Интернета в ubuntu осуществляется различными методами. Кроме того, в ходе этого процесса могут возникать различные побочные эффекты, которые также требуют своеобразного решения. Чтобы впоследствии не допускать каких-либо плохих последствий, следует проанализировать частые ошибки при настройке Интернета на линуксе.

Настройка интернета в Linux

Прежде, чем говорить о настройке Интернета в убунту и рассматривать причины медленного Интернета ubuntu, отсутствия подключения linux mint к Интернету, а также того, что не работает Интернет в ubuntu, надо понять основные фатальные ошибки при работе с такими платформами:

  1. Использование внешних файлов программного обеспечения, а также их беспорядочное обновление может привести к сбою работы операционной системы, соответственно через определенный период времени платформа вообще перестанет нормально функционировать.
  2. С осторожностью на данных платформах следует работать с расширениями .deb и .rpm. Через файлы этих расширений возможна установка вирусных программ, а в итоге ноутбук или компьютер навсегда перестает работать.
  3. Учетная запись root противоречит условиям безопасности платформы Линукс, соответственно это приведет к неполадкам в работе Убунту. В данном случае придется скачивать дополнительный платный пакет программного обеспечения.
  4. Настройка сети в linux mint также требует отключения некоторых расширений браузеров, поскольку они могут повлиять на нормальную работу компьютера или ноутбука в целом.
  5. В данной платформе нельзя использовать приложения для очистки системы. Иначе может возникнуть проблема того, что server ubuntu не видит Интернет. В результате снова надо будет проводить установку линкус через интернет, а в качестве плохого побочного эффекта станет потеря важных данных гаджета и сбой в работе операционной системы.
  6. Нельзя устанавливать другие тестовые программные обеспечения.
  7. Не стоит удалять файлы, входящие в стандартные документы и приложения программного обеспечения линкуса или убунту.
  8. Не стоит проводить какие-либо эксперименты с рабочими гаджетами.

Что касается настройки Интернета, то это процесс будет простым для профессионалов и средним по сложности для новичков. Однако стоит понимать, что Интернет понадобиться не только в подключении самой платформы, но и для последующих скачиваний необходимых программ.

Существует 2 базовых способа подключения к сети. Об этом ниже.

Как настроить интернет в Ubuntu

Настроить подключение к сети может любой желающий.

Для начала нужно знать параметры:

Причем первые 3 пункта выдаются провайдером, а вот последний может быть любым.

Далее технология подключения к Интернету будет выглядеть следующим образом:

  1. Открыть рабочий стол.
  2. Найти значок, отображающий все подключения к сетям. Нажать на него правой кнопкой мыши и выбрать раздел «Изменить соединения…».
  3. После появления окна «Сетевые соединения» следует выбрать тип подключения. Выбрать нужное подключение, выделить его и выбрать раздел «Изменить».
  4. В появившемся окне найти вкладку «Параметры IPv4». В списке выбрать «Способ настройки». Выделить раздел «Вручную».
  5. Заполнить поля данными от провайдера. Нажать кнопку «Сохранить».
  6. Через рабочий стол кликнуть на значок интернет-подключения, найти необходимую сеть и нажать на левую клавишу мыши.

Если выполнено все верно, появится интернет-подключение на платформе убунту.

Как подключить интернет в Линукс Минт

Существует множество вариантов подключения Интернета на платформе Линукс Минт. Правда, распространенных методов всего 3.

Классический вариант

Настройка начинается с команды sudo pope.

Дальше шаги достаточно простые:

  1. Нужно выбрать сетевой адаптер. Наиболее оптимальный вариант – etho.
  2. Затем нужно пройти аутентификацию, нажав на соответствующий раздел.
  3. Дальше стоит удалить параметр pppoe. Нажать на проверку конфигурационного файла – pppoe-conf и подтвердить свои действия, кликнув на кнопку «да».
  4. Система подскажет об изменениях файлов. Нужно снова кликнуть «да».
  5. Потом стоит ввести логин и пароль, выданный провайдером. Потом их можно будет изменить.
  6. Согласиться с автоматической установкой адресов DNS.
  7. Согласиться с ограничением ММ
  8. Подтвердить свои действия.
Читайте также:  Операционная система linux особенности системы

Если сделано все правильно, то проводное интернет-подключение будет установлено.

Для беспроводных сетей потребуется настройка специальных девайсов – роутеров. Они подсоединяются к ноутбукам через кабели. Настройки происходят однотипно: нужно войти в интерфейс роутера, ввести данные от провайдера, сохранить изменения и выйти из интерфейса.

1 вариация

Здесь пойдет речь о подключении к беспроводной сети.

В большинстве случаев настройка Интернет-соединения обеспечивается с помощью программы Network Manager. При ее отключении можно вручную подключить необходимую локальную сеть. Это помогает в решении глобальных проблем с платформой Линкус Минт, а также позволяет решать проблемы несовместимости драйверов с определенной локальной сетью.

Настройка такого подключения нечем не отличается от классического способа установки Интернета. Правда, предварительно нужно отключить опцию автоматического подключения к сети во вкладке «Общие».

2 вариация

Есть еще один вариант подключения Интернета с помощью DSL- модема.

Тут также есть 2 варианта: либо непосредственно копаться в самом модеме, либо подключать через компьютер. 1-ый способ удобен для пользования сетью разными людьми. А вот 2-ой метод удобен для родителей, чьи дети бесконтрольно сидят в виртуальном мире.

Экономичней и проще выглядит первый способ.

  1. Открыть браузер. Ввести адрес модема, логин и пароль. Необходимые параметры указаны либо на самом модеме, либо на коробке из-под этого девайса.
  2. В настройках поменять режим с Bridge на PPPoE.
  3. Потом ввести новые параметры логина и пароля.
  4. Сохранить настройки.
  5. Перезагрузить все девайсы.

Должно появиться интернет-подключение. Тут же можно настроить вай-фай, если модем имеет соответствующие опции.

2-метод настройки еще проще. Достаточно выставить режим Bridge. Затем найти соответствующий значок сетевого подключения и изменить настройки для конкретной сети. Сохранить и перезагрузить компьютер.

Частые ошибки при настройке сети в Linux

Самые распространенные проблемы связаны с ошибками ввода необходимых параметров. Также подключение Интернета может быть проблематичным из-за несоответствия элементов электронного оборудования.

В любом случае новичку для решения проблем следует обратиться к специалистам.

Заключение

Настроить Интернет на Линуксе не так уж и сложно. Однако существуют различные нюансы, которые следует знать и учитывать начинающему пользователю. При возникновении проблем лучше обратиться в сервис-центр.

Источник

Домашний интернет-шлюз. Начальная настройка 6-портового мини-компьютера на Ubuntu Server 20.04 LTS

Введение

Обновил я интернет до 500 Мбит/с, и пришло время заняться 100 Мбитным сервером, который работал на Pentium 3 и был уже на грани. Выбор пал на китайского зверя. Все, что нужно — имеется, потребление в обычном режиме не превышает 15W, запас производительности для дополнительных задач есть.

Установку ОС расписывать не буду («ОК — Далее — Далее»), отмечу только, что при установке требуется сконфигурировать хотя бы один сетевой интерфейс для доступа в интернет.

Для удобства я использую Midnight Commander и его текстовый редактор. Работать будем от root-пользователя:

Итак, у нас есть установленная Ubuntu Server, начнем с конфигурации остальных сетевых интерфейсов.

Netplan

В последних версиях Ubuntu появилась утилита Netplan, позволяющая настроить сеть в унифицированном формате и выбирать сетевой менеджер для работы. По умолчанию используется Systemd-networkd, я же выбрал NetworkManager, так как установил Web-интерфейс Cockpit, который использует именно NM для отображения части информации.
Синтаксис конфигурации Netplan очень строгий и лишний пробел или табуляция может вызвать ошибку.

Подробнее о функционале уже расписывали habr.com/ru/post/448400, так же различные примеры есть на сайте netplan.io/examples.

Посмотрим названия интерфейсов:

Перейдем в директорию /etc/netplan и откроем (F4 для МС) файл 50-cloud-init.yaml. Для сетевого интерфейса, который будет использоваться для подключения к интернету, определим получение настроек по dhcp (dhcp4: true). В моем случае это enp6s0. Для остальных укажем false и добавим параметр optional: true, т.к. интерфейс может быть ни к чему не подключен.

Для объединения интерфейсов в локальную сеть я использовал bridge, но, возможно, правильнее было бы использовать vlan. Создадим мост lan-br, зададим общий IP-адрес, DNS-сервер и пропишем объединяемые интерфейсы:

У меня будет собственный DNS-сервер, поэтому указываю адрес своего сервера в поле nameservers, можно указать например 8.8.8.8 (Google). Указываем версию и менеджер. В итоге должно получиться примерно так:

Сохраняем файл и проверяем/применяем конфигурацию:

DHCP-сервер

Настроим DHCP-сервер для того, чтобы клиенты могли получать IP-адреса автоматически.

В файле /etc/default/isc-dhcp-server правим строчку:

Переходим в /etc/dhcp, открываем dhcpd.conf и прописываем настройки:

Теперь клиенты должны получать адреса автоматически.

UFW (Uncomplicated Firewall) — инструмент для более легкой настройки iptables. Настроим фаервол и пересылку пакетов между интерфейсами. Переходим в/etc/ufw и в файле sysctl.conf раскомментируем строку:

Если Вы подключены через ssh перед началом откройте 22 порт:

Включим UFW, проверим состояние:

Зададим политики по умолчанию:

Разрешим доступ из локальной сети:

Настроим NAT. Откроем файл before.rules и пишем следующее перед блоком *filter:

Сохраняемся и перезапускаем ufw:

Проверим iptables, должна появиться наша строчка:

На этом базовую настройку сервера можно считать законченной.

Заключение

Я не поднимал вопрос настройки DNS-сервера, так как планирую выпустить вторую часть, где будет изложена настройка Dnscrypt-proxy в роли DNS-сервера для локальной сети.

Источник

Ubuntu Documentation

Style Cleanup Required
This article does not follow the style standards in the Wiki Guide. More info.

Introduction

Internet Connection Sharing (ICS) provides the ability for one computer to share its Internet connection with another computer. To do this, a computer with an Internet connection must be configured to function as an Internet gateway. A second computer (or network of computers) connects to the Internet indirectly via the gateway computer.

Situations in which ICS may be necessary include:

  • Dial-up connection.
  • Authenticated (PPPoA/E) connection.
  • Wireless connection.
  • When it is impractical (such as with distance) to run multiple network cables to each computer.

GUI Method via Network Manager (Ubuntu 14.04, 16.04)

Assuming your Internet connection is on Wi-Fi, and you want to share via cable. On Ubuntu 14.04 open Network connections from the applet or via commandline nm-connection-editor, then add a connection, select type ethernet, create, then on tab IPv4 Settings select Method Shared to other computers. That should be all for connection sharing.

Assuming you have a cable connection and want to create a hotspot for other Wi-Fi devices. For Wi-Fi you need to set an SSID and Method Hotspot on tab Wi-Fi, as well as Security WPA and a password on Wi-Fi Security tab.

On 16.04 start the nm-connection-editor via commandline, configure as before, then the created connection appears and works from gnome3-shell network settings.

GUI Method via Network Manager (Ubuntu 12.04)

Open Settings->Network->Wireless and create a new Ad Hoc network. To use a common denominator for all devices choose WEP for security and create a 5 letters password from 0..9A..F. Note that this a least secure encryption standard.

Читайте также:  Hetzner windows server 2016

GUI Method via Network Manager (Ubuntu 11.10)

Follow the GUI Method via Network Manager (Ubuntu 9.10 and up) below but there is a bug which turn off and on the share connection. The workaround for now is to set IPv6 options to Ignore and then sudo killall dnsmasq. Reconnect and it should work.

GUI Method via Network Manager (Ubuntu 9.10 and up)

In order to share an Internet connection, the computer that will do the sharing must have two network cards or ports. This assumes that you are using at least one Ethernet port and that it is identified as «eth0». eth0 will be the port that other computers will connect to you on.

When you are logged in:

  • Go to «System» on your top bar.
  • Navigate to «Preferences» and select «Network Connections».
  • When that window opens, select «Auto eth0», and press «Edit» (This assumes that you are connected to the Internet on some other port, for example wlan0 using wireless).

A new window will open. Navigate to the tab titled «IPv4 Settings», and change the Method to «Shared to other computers». After restarting the computer, you should now be able to plug in any computer into your other Ethernet port or share through your wireless card.

Note: To clarify the above example, here is an example configuration that will work:

  1. You are already connected to the Internet using your wireless on port wlan0.
  2. The Ethernet port eth0 is connected to the PC that needs to share your Internet connection (or you could wire eth0 to a router for multiple machines).

Note: In the case of connecting a router, especially one with wireless, where you want the users to share your connection:

Check before you start (in Synaptic or with dpkg-query -l dnsmasq*) that dnsmasq-base is installed and that dnsmasq is not installed. Install or uninstall as appropriate (see next section).

  • After connecting the router, to enable masquerading, type:
  • Wireless Ad-Hoc connection sharing scenario

    Step-by-step guide:

    • dnsmasq-base has to be installed:

    Remove dnsmasq because it conflicts with NetworkManager:

    Add a new wireless network with NetworkManager (left-click on NetworkManager icon, then select «Create New Wireless Network»).

    Call the new network «UbuntuAdhoc» (Note: If you choose another name, you will have to turn on connection sharing later by editing the network that you just created).

    Set encryption to «WEP40. » (Note: You may have to experiment here according to what type of encryption with ad-hoc the device supports. WPA is not supported).

    NetworkManager now should connect to itself (which means it creates the ad-hoc wireless network and routes any Internet traffic to your wired network interface). Now, connect with the client(s), and you should have a working Internet connection.

    Ubuntu Internet Gateway Method (iptables)

    You will need two network cards in the gateway computer, or a PPP interface and a network card. One network card (or PPP interface) connects to the Internet. We will call this card eth0. The other card connects to your internal network. We will call this eth1. It is also possible to do ICS with a single network card. In this case, use eth0 for the Internet and eth0:0 for the internal network.

    Internet > eth0 <> Ubuntu gateway <> eth1 > Client PC

    Internet > ppp0 <> Ubuntu gateway <> eth1 > Client PC

    Internet > eth0 <> Ubuntu gateway <> eth0:0 > Client PC

    Gateway set up

    The following example will focus on the most common gateway setup: an Ubuntu computer with two wired network adapters (eth0 and eth1) hosting ICS to a static internal network configured for the 192.168.0.x subnet.

    For this example, eth0 is used to represent the network card connected to the Internet, and eth1 represents the network card connected to a client PC. You can replace eth0 and eth1 as needed for your situation. Also, any private IP subnet can be used for the internal network IP addresses.

    eth0 = the network adapter with internet (external or WAN).
    eth1 = the network adapter to which a second computer is attached (internal or LAN).
    192.168.0.x = IP subnet for eth1

    Your setup may be different. If so, make sure to change them accordingly in the following commands.

    Configure internal network card

    Configure your internal network card (eth1) for static IP like so:

    The external and internal network cards cannot be on the same subnet.

    Configure NAT

    Configure iptables for NAT translation so that packets can be correctly routed through the Ubuntu gateway.

    The first rule allows forwarded packets (initial ones). The second rule allows forwarding of established connection packets (and those related to ones that started). The third rule does the NAT.

    IPtables settings need to be set-up at each boot (they are not saved automatically), with the following commands:

    • Save the iptables:

    Edit /etc/rc.local and add the following lines before the «exit 0» line:

    Enable routing

    • Configure the gateway for routing between two interfaces by enabling IP forwarding:

    Edit /etc/sysctl.conf, and (up to 10.04) add these lines:

    The /etc/sysctl.conf edit is required because of the following bug in Hardy and later releases:Launchpad Bug Report

    From 10.10 onwards, it suffices to edit /etc/sysctl.conf and uncomment:

    . so that it reads:

    Client set up

    Any OS can connect to the Internet as an ICS client as long as networking has been configured correctly. The following example will focus on how to set up an Ubuntu ICS client. For this example, it is assumed that the client is connected to an Ubuntu gateway, which has been configured to share ICS on the 192.168.0.x subnet according to the gateway set up outlined above.

    For this example, eth0 is the network card on the client which is connected (by crossover cable) to eth1 on the Ubuntu gateway. You can replace eth0 as needed for your situation. Also, any private IP subnet can be used for the internal network IP address, as long as it matches the subnet on the gateway.

    Disable networking

    Give the client a static IP address

    This IP address can be anything within the gateway’s private IP range.

    Configure routing

    This address should match the IP address on the gateway’s internal network card (eth1 in the above example).

    Configure DNS servers

    Unless your ICS gateway can also perform DNS, you must manually configure the client with your ISP DNS servers. If you do not know your ISP’s DNS servers, you can use OpenDNS servers instead.

    Читайте также:  Sip клиент для windows zoiper

    Backup your current /etc/resolve.conf file:

    Open /etc/dhcp3/dhclient.conf with your favorite text editor:

    • Search for the line that starts «prepend domain-name-servers», and change it to look like this:

    208.67.222.222 and 208.67.220.220 are OpenDNS DNS servers. If you wish to use your ISP’s DNS servers, use them here instead of the OpenDNS servers.

    Restart networking

    Once this is finished, your client will now have access to the Internet via ICS. Please direct any questions/comments to the Internet Connection Sharing Documentation thread.

    A beginner’s working example of a Ubuntu Desktop with 2 NIC cards, sharing Internet connection: http://ubuntuforums.org/showthread.php?p=3713684

    Advanced Gateway Configuration

    The above example outlines how to do basic ICS on a static IP network. Once you have configured your Ubuntu computers for ICS and confirmed that everything works across your static network, there are a few advanced routing configurations which can make it much easier to set up the ICS client.

    Advanced configurations include DHCP server and DNS server. A DHCP server allows the client to get an IP address automatically without having to manually configure a static IP. A DNS server allows the client to resolve Internet host names without manually configuring DNS addresses.

    DHCP/DNS server

    This is deceptively easy, and will be acceptable for most situations. However, it will not allow the ICS client to see computers on different subnets.

    • Install software.
    • Stop the server. After dnsmasq has been installed, it is automatically started, so it will need to be stopped before changes can be made.
    • Make a backup of the well-commented configuration file (we won’t use any of this, but it’s handy to have a copy of for reference later).

    Edit /etc/dnsmasq.conf with your favorite text editor, and add the following two lines:

    Note: The «interface» should match the interface that your clients are connected to, and the «dhcp-range» should be within the gateway’s private IP subnet that you configured according with the «Gateway set up» directions above.

    • Start the DHCP/DNS server.

    Now, your clients should be able to pull an automatic ip address and resolve host names.

    Other approaches

    The following section includes a rough outline of some alternative methods for configuring an ICS gateway. They are incomplete and untested. They are included simply for the sake of information.

    Alternate server software (CLI)

    There are other ways to host ICS, but they are outside the scope of this article.

    Alternate NAT

    The ipmasq daemon does NAT routing so you don’t have to configure iptables. The following directions are incomplete and should not be considered a full description of what needs to be done to configure ipmasq.

    Configure ipmasq to allow dhcp requests. Otherwise, you need to stop ipmasq to make a connection. You need to copy a .rul from the documentation directory into the /etc config and edit the interface name. Then, reconfigure ipmasq to start after networking has been started.

    Dedicated DHCP server

    dhcp3 is an easy to configure and scalable true DHCP server that can be configured for many different aplications. dhcp3 configuration is more complex, but it can be useful in many situations:

    Dedicated DNS server

    BIND9 is a popular and well-supported local DNS server. It is very versatile and very powerful, but difficult to configure correctly:

    Alternate gateway software (GUI)

    Another approach is to set up Firestarter, to run connection sharing, to set up dhcp3-server, and to set its configuration to listen to the correct eth*. To change this later, run sudo dpkg-reconfigure dhcp3-server.

    Basically, you need to have Firestarter active/turned on/protecting, to have the connection shared.

    When you install dhcp3-server, it will place a sample config file in your /etc/dhcp3 folder, called dhcpd.conf. I suggest that you install dhcp3-server first and then Firestarter because if you are lucky, Firestarter will set up a new dhcp3 config file for you.

    At any time that changes are made to your dhcpd.conf file, restart the server by typing sudo /etc/init.d/dhcp3-server restart. Alternatively, every time you run the sudo dpkg-reconfigure dhcp3-server command, at the end, your server will restart.

    There are several issues that I had. First of all, the Firestarter firewall won’t even start if you don’t have it configured to listen to the right interface. You can change which one it listens to in Preferences —> Network Settings. The Local-network-connected device must be the same as you have dhcp3-server listening to. Of course, both checkboxes under that need to be checked. The Internet-connected network device will be the one that is configured for Internet. Now, I have two NICs, but I have PPPoE configured on eth0, and I have Internet connection sharing configured on the same one, because eth0 is also configured for a static 192.168 internal IP for my internal network.

    Simple iptables example

    In a simple example, wlan0 has the Internet connection, and eth0 is being used to share the connection. It could be connected directly with a single computer via a crossover cable or switch, or you could have a router with a cable from eth0 to the WAN port and a whole LAN setup behind this. Interestingly, the Internet connection could be ppp0, a 3G, or mobile Internet modem.

    #!/bin/sh
    #
    # internet connection sharing wlan0 is the gate way
    # eth0 is the lan port this might use a straight ethernet cable to a router wan port or a switch or a single PC
    # 192.168.2.2 is the port that is being used by the lan for access I changed it to 192.168.2.254 and set fixed addresses for the wan and router
    #
    # change wlan0 to ppp0 and you can use this for mobile broadband connection sharing
    #
    ip link set dev eth0 up
    ip addr add 192.168.2.1/24 dev eth0
    sysctl net.ipv4.ip_forward=1
    iptables -t nat -A POSTROUTING -o wlan0 -s 192.168.2.0/24 -j MASQUERADE
    iptables -t nat -A PREROUTING -i wlan0 -p tcp —dport 3074 -j DNAT —to-destination 192.168.2.2
    iptables -t nat -A PREROUTING -i wlan0 -p udp -m multiport —dports 88,3074 -j DNAT —to-destination 192.168.2.2
    iptables -A FORWARD -i wlan0 -d 192.168.2.2 -p tcp —dport 3074 -j ACCEPT
    iptables -A FORWARD -i wlan0 -d 192.168.2.2 -p udp -m multiport —dports 88,3074 -j ACCEPT

    You could use the above as a bash script changing things to suit your needs.

    • If things go wrong, the following script should save you when things get badly messed up.

    Источник

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