Настройка сети Raspberry Pi 3
Настройка сети Raspberry Pi 3
Основная операционная система предназначенная для Raspberry Pi – Raspbian – основана на Debian, поэтому и настройка сетевых интерфейсов здесь выполняется так же, как и в Debian. С проводным подключением всё достаточно просто. Вам достаточно подсоединить сетевой шнур к устройству, чтобы интернет начал работать. Немного сложнее настроить статический IP-адрес и беспроводное соединение с Wi-Fi.
Но, как бы там нибыло, без сети сейчас никуда. Поэтому в этой статье мы рассмотрим, как выполняется настройка сети Raspberry Pi 3 различными способами. Начнём с беспроводного подключения.
Static IP vs. Dynamic IP
Dynamic IP
Dynamic IP’s are good to use if you’re concerned about security. If a hacker gets access to your IP address, you’ll be less vulnerable to attack since your IP changes frequently. A dynamic IP can change every time you log in, or only at certain intervals. A program installed on your network router called the dynamic host configuration protocol (DHCP), automatically changes and assigns new dynamic IP addresses to computers on your network.
Static IP
A static IP (as you could probably tell by the name) is one that doesn’t change. This makes it more reliable when using services that depend on a stable internet connection, like online gaming, VOIP, or remote desktop applications. With a static IP, you’ll be able to use the same IP address every time you connect to your Pi.
Step 2: Gathering Intelligence
Before we change any settings on the pi, we need to collect some information regarding our network.
– In the command line type the following command and hit enter.
– From the info that comes up, note down the following things:
-> inet addr
-> Bcast
-> Mask
– When you have got all this information, you need even more information. Enter the following command and hit enter
– From the table that comes up note down the following:
-> Destination
-> Gateway
This is what I got:
- inet addr : 192.168.137.82
- Bcast : 192.168.137.255
- Mask : 255.255.255.0
- Destination : 192.168.137.0
- Gateway : 192.168.137.1
These numbers will most probabaly will be different for you so don’t copy mine by mistake.
After you have got all this, you can proceed to the next step.
Как узнать текущий адрес «Малины»?
Если для настройки выполняется подключение по SSH, то перед этим может потребоваться узнать, какой IP у «Малины» в текущий момент. Особенно полезной эта информация оказывается после перезагрузки роутера. Именно тогда многие новички задумываются о том, чтобы дать своему одноплатнику статичный адрес.
Узнать IP Raspberry Pi 3 возможно множеством разных способов. В Windows это делается посредством ввода в командную строку следующей команды: ifconfig eth0 (если используется WiFi, то нужно писать wlan0 вместо eth0).
Утилита выведет листинг, показывающий состояние всех присутствующих в сети устройств. Среди них будет и «Малина».
Другой вариант – зайти в панель управления роутера. Большинство маршрутизаторов демонстрирует соответствующую информацию на главной странице админки.
И третий способ – загрузить на телефон какое-нибудь приложение NetTools. После недлительного сканирования программа сообщит о подключенных к сети девайсах и представит информацию об их адресах.
Настройка статичного IP для «Малины» – не отличающая сложностью задача. Нужно следовать инструкции, у уже через 10 минут все будет сконфигурировано.
Алексей 2020-03-15 05:22:33
как быть, если в файле /etc/network/interfaces нет адресов
Raspberry Pi Static IP Setup
Prerequisites:
You must have a Raspberry Pi with Raspbian operating system flashed onto the SD card. If you don’t know how to flash Raspbian image to SD card, read the article Install Raspbian on Raspberry Pi. If you don’t have an external monitor and would like to setup Raspberry Pi with Raspbian operating system in headless mode, read the article Raspberry Pi Connect to Wifi Using wpa_supplicant. Once you have Raspbian operating system up and running on your Raspberry Pi, you can move on to the next section of this article below.
Network Configuration:
In this article, I will set 2 different static IP addresses on my Raspberry Pi 3 Model B. One for the ethernet network interface eth0 and one for the Wi-Fi network interface wlan0. My network configuration is given below. It will be different for you. So, make sure to replace them as required.
Ethernet network interface eth0 configuration:
IP Address: 192.168.0.21
Netmask: 255.255.255.0 or /24
Router/Gateway address: 192.168.0.1
DNS nameserver address: 192.168.0.1 and 8.8.8.8
Wi-Fi network interface wlan0 configuration:
IP Address: 192.168.0.31
Netmask: 255.255.255.0 or /24
Router/Gateway address: 192.168.0.1
DNS nameserver address: 192.168.0.1 and 8.8.8.8
Setting Up Static IP to Ethernet Network Interface:
To configure a static IP to the ethernet network interface eth0, you have to edit the configuration file /etc/dhcpcd.conf configuration file.
To edit the configuration file /etc/dhcpcd.conf with nano text editor, run the following command:
The dhcpcd.conf file should be opened with the nano text editor.
Now, go to the end of the configuration file and add the following lines.
The final configuration file should look as follows. Now, save the dhcpcd.conf configuration file by pressing + X followed by Y and .
Now, reboot your Raspberry Pi with the following command:
Once your Raspberry Pi boots, check the IP address of the ethernet network interface eth0 with the following command:
Your desired IP address should be assigned to the ethernet network interface eth0.
As you can see in the screenshot below, the static IP address 192.168.0.21 is assigned to the ethernet network interface eth0 of my Raspberry Pi 3 Model B as I wanted.
So, this is how you set a static IP address to the ethernet network interface eth0 of your Raspberry Pi running Raspbian operating system.
Setting Up Static IP to Wi-Fi Network Interface:
To configure a static IP to the Wi-Fi network interface wlan0, you have to edit the configuration file /etc/dhcpcd.conf configuration file.
To edit the configuration file /etc/dhcpcd.conf with nano text editor, run the following command:
The dhcpcd.conf file should be opened with the nano text editor.
Now, go to the end of the configuration file and add the following lines.
The final configuration file should look as follows. Now, save the dhcpcd.conf configuration file by pressing + X followed by Y and .
Now, reboot your Raspberry Pi with the following command:
Once your Raspberry Pi boots, check the IP address of the Wi-Fi network interface wlan0 with the following command:
Your desired IP address should be assigned to the Wi-Fi network interface wlan0.
As you can see in the screenshot below, the static IP address 192.168.0.31 is assigned to the Wi-Fi network interface wlan0 of my Raspberry Pi 3 Model B as I wanted.
So, this is how you set a static IP address to the Wi-Fi network interface wlan0 of your Raspberry Pi running Raspbian operating system.
Using an USB Wi-Fi dongle
Whereas the Raspberry Pi 3 has on-board Wi-Fi, earlier models (e.g. model 2) can use an USB Wi-Fi dongle to connect wirelessly.
Edimax has a nice range of USB Wi-Fi dongles, but any general Wi-Fi dongle can be used.
Either way, all the versions of Raspbian come pre-equipped to automatically detect and use the hardware. To ensure the best functionality, an update/upgrade will suffice in most cases:
After booting with the USB Wi-Fi dongle attached, its detection can be confirmed using the Linux kernel command, dmesg . The output of this command typically contains the messages produced by the device drivers:
The spacebar key can be used to scroll down one page at a time. Close to the end, something similar to the following lines will show:
The lines above indicates that a high-speed USB device was found. It also shows that it is a wireless LAN (802.11n WLAN) adapter. This means that the USB Wi-Fi dongle is identified and ready to use. Setting a static IP address for an USB Wi-Fi dongle is similar to doing it for on-board Wi-Fi.
- Включаем на Raspberry доступ по SSH
- В настройках роутера закрепляем за MAC-адресом Raspberry статический IP внутри сети (например, 192.168.1.123)
- Там же делаем 22 порт (SSH) расбы доступным “снаружи”
Включаем SSH
- Подключаем к расбе монитор и клаву
- Открываем терминал и запускаем утилиту настройки sudo raspi-config
- Находим Interfacing Options > SSH > включаем, Enter
Закрепляем за расбой IP внутри сети
Это нужно для того, чтобы роутер всегда выдавал нашей малинке один и тот же ИП внутри сети
- Входим в админку роутера, открыв в браузере 192.161.1.1 (адрес может отличаться. Найти можно, введя в консоль ipconfig. Ищите там похожие адреса). Роутер может запросить логин и пароль. Попробуйте найти наклейку на самом роутере или попробуйте admin admin
- Находим мак-адрес расбы ifconfig wlan0 | grep ether
- Находим раздел для резервации IP и прописываем там найденный мак. Если у вас получилось подключиться к роутеру по 192.161.1.1, то можете смело указывать рядом с маком 192.168.1.123. В другом случае может потребоваться изменение адреса, как требует DHCP (настраивается рядом, скорее всего)
- После перезагрузки роутера Raspberry должен выделиться новый внутренний адрес. Проверить можно введя на нем ifconfig wlan0 . Если этого не случилось, то поищите настройки, похожие на те, что на скриншоте ниже
Также убедитесь, что с этого момента вы можете подключиться к расбе через ssh pi@192.168.1.123 . Напишите в комментариях, если возникли проблемы
Пробрасываем 22 порт с расбы “наружу”
Сейчас Raspberry доступна только во внутренней сети. Тоесть, вы можете подключиться к ней с устройств, подключенных к тому же WiFi. Чтобы к ней можно было подключиться с “мира” мы должны рассказать роутеру, на какое устройство перенаправлять трафик по 22 порту.
Наша Raspberry с предыдущего пункта имеет адрес 192.168.1.123
- Находим настройки виртуальных серверов (virtual servers). Может иметь другое название, но должно быть связано с разделом переадресации (redirects)
- Добавляем новое правило. Порты некоторых сервисов: SSH 22, FTP 21, WEB 80 и 443 (для https://)
- Перезагружаем роутер и подключаемся к устройству уже через ssh pi@ip , где ip — ваш внешний IP адрес (можно узнать на 2ip.ru)
- Вы великолепны
Recent versions of Raspbian (which use dhcpcd ) allow ssh to work over a link-local address and avahi (which is a zeroconf implementation) enables programs to discover hosts running on a local network.
This means you can plug the Pi into a Computer (with an Ethernet cable) or a local network router and connect without knowing the IP address.
You can easily connect from Linux and OS X with ssh pi@hostname.local (the default hostname is raspberrypi ) This should work with popular GUI ssh programs. This is sometimes problematic with some versions of Windows and networks which use .local in a non-standard way. (See https://en.wikipedia.org/wiki/.local)
NOTE .local resolution does not always work e.g. in rsync . The following should resolve IP (and can be included in bash scripts)
RemotePi=$(getent hosts hostname.local | awk ‘< print $1 >‘)
If your system does not have getent to query the hosts e.g. macOS you can use the following:-
RemotePi=$(arp -n hostname.local | awk ‘
If you have multiple Pi you need to make sure each Pi has a unique hostname.
You can use a crossover cable, but you don’t need one (most modern interfaces automatically detect).
One drawback of direct connection is that the Pi will have no Internet access and the date will not be set. You can copy the date from the host by running ssh pi@hostname.local sudo date -s$(date -Ins) before connection.
You can do this by opening a terminal window and re-enter:
As shown in the figure above, you should see the static IP address now.
Great! You made it much easier now to access you Raspberry Pi from another computer now!
Remark: In the case you want to have a dynamic IP address again, you can just comment (add “#” at the beginning of the line) the changed lines of the configuration file we mention here above.
And if you are interested in learning to program electronic components on your Raspberry Pi, don’t hesitate to visit our shop. We have a nice kit which contains all the things you need tot start.
Raspberry PI 4B SSD upgrade kit
This upgrade kit allows you to easily integrate an SSD into your existing Raspberry Pi 4 setup. On top, the case .
Raspberry Pi 4B with 120 GB SSD starter kit
This high end kit includes everything you need to get maximum performance out of your Pi. An SSD instead of an .
Raspberry Pi 4 kit : case – power supply – fan – heatsinks
An ideal kit if you already have a Raspberry Pi 4 board and only need the basic elements. The enclosure with the .
Raspberry PI 4B case with fan
Get once for all rid of CPU performance losses your Pi is struggling with. This versatile 3D-printed Raspberry Pi 4 case .
Raspberry Pi 4B – Ultimate starter kit – 4GB
Start your next digital project with this small but amazing mini computer! The enclosure has been specially designed to guarantee maximum heat .
Raspberry Pi 4 kit : case – power supply – heatsinks
An ideal kit if you already have a Raspberry Pi 4 board and only need the basic elements. The enclosure has been .