Linux set static ip address

Linux Static IP Address Configuration

H ow do I configure the Internet Protocol version 4 (IPv4) properties of a network connection with a static IP address for servers running Linux operating systems? How do I configure static IP address under Debian Linux or Redhat / RHEL / Fedora / Redhat Enterprise Linux server?

You need to update and/or edit the network configuration files. This tutorial provides procedures to configure a static IP address on a computer running the following operating systems:

  1. RHEL / Red hat / Fedora / CentOS Linux eth0 config file – /etc/sysconfig/network-scripts/ifcfg-eth0
  2. RHEL / Red hat / Fedora / CentOS Linux eth1 config file – /etc/sysconfig/network-scripts/ifcfg-eth1
  3. Debian / Ubuntu Linux – /etc/network/interfaces

Sample Setup: Linux Static TCP/IP Settings

In this example you will use the following Internet Protocol Version 4 (TCP/IPv4) Properties including IP, default gateway, and preferred DNS servers:

  • IP address: 192.168.1.10
  • Netmask: 255.255.255.0
  • Hostname: server1.cyberciti.biz
  • Domain name: cyberciti.biz
  • Gateway IP: 192.168.1.254
  • DNS Server IP # 1: 192.168.1.254
  • DNS Server IP # 2: 8.8.8.8
  • DNS Server IP # 3: 202.54.2.5

RHEL / Red hat / Fedora / CentOS Linux Static IP Configuration

For static IP configuration you need to edit the following files using a text editor such as vi. Edit /etc/sysconfig/network as follows, enter:
# cat /etc/sysconfig/network
Sample static ip configuration:

Edit /etc/sysconfig/network-scripts/ifcfg-eth0, enter:
# cat /etc/sysconfig/network-scripts/ifcfg-eth0
Sample static ip configuration:

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Finally, you need to restart the networking service, enter:
# /etc/init.d/network restart
To verify new static ip configuration for eth0, enter:
# ifconfig eth0
# route -n
# ping 192.168.1.254
# ping google.com

Debian / Ubuntu Linux Static IP Configuration

Edit /etc/hostname, enter:
# cat /etc/hostname
Sample ip config:

Edit /etc/network/interfaces, enter:
# cat /etc/network/interfaces
Sample static ip config:

Finally, you need to restart the networking service under Debian / Ubuntu Linux, enter:
# /etc/init.d/networking restart
Type the following commands to verify your new setup, enter:
# ifconfig eth0
# route -n
# ping google.com

See also:

  • RHEL / Redhat / CentOS / Fedora Linux network configuration tutorial using GUI and config files.
  • Debian / Ubuntu Linux network configuration tutorial

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

Very helpful…thanks alot

YAY, easy as pie, thanks.

i am facing problem her in Ubuntu server i made static IP and it worked as ping from it and to it . after 5 min i can not ping to ubuntu but i used ifconfig i found my ip as it is and ping from ubunto to any pc is fine, i made ifdown then ifup it works again but after about time stopped ping from outside….

Sounds like you have another machine useing the ip address,

try doing ifdown and then ping from another machine to your ip address if you get reply, change your static ip to one that gets no respose do a ping first to check if the ip is in use, this way you can ensure you have a unique address, if using a dhcp make sure you add a reservation into it else it could happen again where the server is not getting a lease so the dhcp will assign on request to a machine, good idea is to set your dhcp range to something like xxx.xxx.xxx.100 – 200 and then you know you can freely use any ip up to xxx.xxx.xxx.99 and not have to add it in the reservations because the dhcp wont assign below 100

But if I have two NIC cards and I have to give different hostnames for evry ip.
Is this possible?

example
NIC 1 : 192.168.1.1
HOSTNAME : server1.abcd.com
NIC 2 : 192.168.2.1
HOSTNAME : server2.xyzf.com

So is this possible on one system??
In DNS server I have made this entry.
How can I resolve this ip/hostname from the machine itself.

I am new in this field. Please advise me.

( I guess I can do this entries in /etc/hosts. Is this right??)

in /etc/hosts
192.168.1.1 server1 server1.abcd.com
192.168.2.1 server2 server2.xyzf.com

Awesome, helped me out using Raspberry Pi Debian.

Thanks, I was able to resolve my ip addressing problem…now it’s not resolving dns and yes I added the dns ip’s to resolv.conf. What a nose bleed!
Is it just me or or is just beyond stupid Centos has problems connecting to the net out of the box. Reallllly?

I don’t want DHCP to push DNS info in my resolv.conf. How do I achieve that?

What I tried and didn’t help:-
1.Disable dns in /etc/nsswitch.conf
2.Disable dns in /etc/resolv.conf
3.Service network restart (obtain IP from DHCP)
4.Check resolv.conf to discover that dns ip is written in resolv.conf again!

PEERDNS=, where is one of the following:

yes — Modify /etc/resolv.conf with information from the server. If using DHCP, then yes is the default.

no — Do not modify /etc/resolv.conf.

Cyberciti, whenever I come here, I am done with my solution. Thank you so much.
Keep it up 🙂
-Vimal

on HREL/CentOS it didn’t work.

After restarting it connected, (pinged google ok) but pinging the IP I set returned unknown host

dont forget “auto eth0”

For set Centos Static IP Address Configuration need this configuration

DEVICE=eth0
BOOTPROTO=none
HWADDR=e0:66:90:03:98:5b
IPADDR=192.168.2.3
NETMASK=255.255.255.0
ONBOOT=yes
GATEWAY=192.168.2.1
TYPE=Ethernet
USERCTL=no
IPV6INIT=no
PEERDNS=yes

Hi i have this strange problem that on centOS running inside VirtualBox i set the IP Address and after sometime the configurations are lost and the interface has no IP Address. I have no clue why this is happeneing?

Can someone please help. Its like i setup everything restart, fine i have ip there but after like a min or 40+ seconds configurations are lost. i set again with ifconfig, they stay for sometime and then reset again, what should i do?

thanks a lot it’s perfect explain
I was suffering from IP problem between VMware and local computer there isn’t connection when I was using Putty to do connect to linux on VMware.

once again thanks million *_^

Good useful information. It was very helpful

thanks a lot dear please keep sharing this kind to knowledge to our all linux users.

Doesn’t look like it’ll work when you need something like this.

ip a a 127.0.0.1/8 dev lo
ip a a 8.8.8.8/32 dev lo

thanks its very help full site for user but one request for you Add search box in web page for finding more details which i want.

Источник

How to Set Static IP Address and Configure Network in Linux

If you are a Linux system administrator, time will come when you will need to configure networking on your system. Unlike desktop machines where you can use dynamic IP addresses, on a server infrastructure, you will need to setup a static IP address (at least in most cases).

This article is meant to show you how to configure static IP address on most frequently used Linux distributions.

For the purpose of this tutorial, we will use the following Internet Protocol version 4 (IPv4) details:

Configure Static IP Address in RHEL/CentOS/Fedora:

To configure static IP address in RHEL / CentOS / Fedora, you will need to edit:

Where in the above «ifcfg-eth0″ answers to your network interface eth0 . If your interface is named “ eth1» then the file that you will need to edit is «ifcfg-eth1» .

Let’s start with the first file:

Open that file and set:

Note: Make sure to open the file corresponding to your network interface. You can find your network interface name with ifconfig -a command.

In that file make the following changes:

You will only need to edit the settings for:

Other settings should have already been predefined.

Next edit resolve.conf file by opening it with a text editor such as nano or vi:

Once you have made your changes restart the networking with:

Set Static IP Address in Debian / Ubuntu

To setup static IP address in Debian/ Ubuntu, open the following file:

You may see a line looking like this:

Change it so it looks like this:

Save the file and then edit /etc/resolv.conf like this:

Restart the networking on your system with:

Your static IP address has been configured.

Conclusion:

You now know how to configure a static IP address on a Linux distro. If you have any questions or comments, please do not hesitate to submit them in the comment section below.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Источник

Как задать ip адрес в Linux

По умолчанию в большинстве дистрибутивов Linux, ip адрес устанавливается автоматически, по протоколу DHCP, независимо от того какой тип соединения используется, будь то проводной интернет или беспроводное подключение к точке доступа Wifi или даже USB модем. Но если необходимо вы можете задать ip адрес Linux вручную. Это может понадобиться если вы хотите использовать статический ip адрес чтобы сеть запускалась быстрее при старте системы.

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

Как узнать IP, шлюз и маску?

Вы не можете установить любой IP для своего компьютера. Есть определенный диапазон значений, которые можно использовать. Ваш новый ip адрес должен быть в той же сети, что IP адрес роутера, который представляет из себя шлюз в сеть. Также, если вы задаете IP вручную, то нужно указать и другие параметры, которые система раньше получала по DHCP. И перед тем как переходить к настройке давайте рассмотрим откуда взять эти данные.

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

  • 10.0.0.0 – 10.255.255.255
  • 172.16.0.0 – 172.31.255.255
  • 192.168.0.0 – 192.168.255.255

Они все зарезервированы для локальных сетей и их использование не должно вызвать конфликтов с общим интернетом, таким образом сначала надо узнать адрес шлюза. Но со шлюзом все немного сложнее. Это ваш маршрутизатор. Очень важно указать шлюз правильно, иначе компьютер не сможет получить доступ к сети. Посмотреть текущий адрес шлюза можно командой:

ip route show match 0/0

Здесь мы видим, что наш адрес шлюза — 192.168.0.1. Отсюда выплывает, что нам нужно выбирать наш ip именно из этого диапазона, можно менять только последнюю цифру и надо, чтобы в этой сети компьютеров с такими адресами больше не было, например, 192.168.0.64.

Маска подсети используется чтобы отделить локальную часть ip адреса, которая меняется, от статической. Сейчас в большинстве случаев применяется значение 255.255.255.0, которое означает изменение только последней цифры. Теперь, когда вы знаете откуда брать все значения, рассмотрим как установить ip адрес Linux.

Настройка ip адреса в Ubuntu

Настройкой сети в Ubuntu по умолчанию занимается специальная служба networking, конфигурация которой находятся в файле /etc/network/interfaces. Стандартные настройки с использованием динамического получения ip адреса по DHCP выглядят следующим образом:

В этом примере настраиваются два интерфейса, lo и eth0. Нас будет интересовать только строчка, касающаяся проводного соединения eth0, она тут одна:

iface eth0 inet dhcp

Отредактируйте конфигурацию как показано ниже, нужно закомментировать строчку получения ip по DHCP и добавить вместо нее настройку статического ip адреса, подсети, и шлюза:

sudo vi /etc/network/interfaces

auto lo
iface lo inet loopback
# iface enp24s0 inet dhcp
auto enp24s0
iface enp24s0 inet static
address 192.168.0.65
netmask 255.255.255.0
gateway 192.168.0.1
dns-nameservers 8.8.8.8,8.8.4.4

Более подробно настройка сети Ubuntu через терминал описана в отдельной статье. Настройте параметры в соответствии с вашими параметрами сети. Затем перезапустите сетевые службы чтобы изменения вступили в силу без перезагрузки компьютера:

sudo systemctl restart networking

Чтобы убедиться что все установлено правильно используйте утилиту ip.

ip addr list | grep enp24s0

Настройка IP адреса в CentOS

В системах, основанных на дистрибутиве RedHat, файлы настройки сети немного отличаются. Тут за начальную настройку сети отвечает фреймворк Wiched. Настройки получения IP адреса хранятся отдельно для каждого сетевого интерфейса в файлах /etc/sysconfig/network-scripts/ifcfg-имя_интерфейса, например, enp2s0. Настройки статического ip для сетевого адаптера с адресом enp2s0 будут выглядеть следующим образом:

sudo vi /etc/sysconfig/network-scripts/ifcfg-enp2s0

DEVICE=»enp2s0″
BOOTPROTO=»static»
NM_CONTROLLED=»yes»
ONBOOT=»yes»
TYPE=»Ethernet»
IPADDR=192.168.0.65
NETMASK=255.255.255.0
GATEWAY=192.168.0.1
DNS1=»8.8.8.8″

Чтобы изменения вступили в силу перезапускаем сеть:

sudo systemctl restart networking

Готово, настройка ip адреса linux с помощью стандартных средств системы завершена и вы можете дальше использовать свой компьютер.

Настройка статического IP адреса в nmcli

Сетевой конфигуратор NetworkManager сейчас используется практически повсеместно. Если нужно настроить IP в терминале вы можете использовать утилиту nmcli. Сначала смотрим доступные подключения. Для этого выполните:

Допустим, что необходимое вам подключение называется Проводное соединение 2. Тогда осталось установить IP адрес, шлюз и DNS сервер:

nmcli con mod «Проводное соединение 2» ipv4.addresses 192.168.1.64/24
nmcli con mod «Проводное соединение 2» ipv4.gateway 192.168.1.1
nmcli con mod «Проводное соединение 2» ipv4.dns «8.8.8.8»

Затем надо сообщить утилите, что IP адрес будет настраиваться вручную:

nmcli con mod «Проводное соединение 2» ipv4.method manual

В этом примере IP адрес задается немного по другому. Сначала идёт выбранный ip адрес, а затем маска в формате /24. Это аналог записи 255.255.255.0, только короче.

Настройка IP в графическом интерфейсе

Разберемся ещё как изменить IP адрес через графический интерфейс. Для этого кликните по значку сети в правом верхнем углу экрана, затем выберите любое сетевое подключение и кликните по пункту Параметры соединения:

В открывшемся окне параметров нажмите значок шестеренки напротив нужного соединения, например, Проводное:

Перейдите на вкладку IPv4 и напротив пункта Метод IPv4 выберите Вручную. Появится несколько полей, которые надо заполнить. Заполните IP адрес, маску и шлюз:

Затем чуть ниже пропишите DNS. Когда всё будет готово нажмите кнопку Применить.

Настройка IP адреса с помощью утилиты ip

Если вам не нужно настраивать статический ip при загрузке, а необходимо только один раз задать ip адрес linux через терминал, то можно использовать утилиту ip. Включите интерфейс, если он выключен:

sudo ip link set eth0 up

Сначала нужно изменить IP и маску сети:

sudo ip addr add 192.168.0.65/255.255.255.0 dev eth0

Затем добавить шлюз:

sudo ip route add default via 192.168.0.1

Готово, теперь ваша сеть должна работать. Только эти настройки будут работать до первой перезагрузки.

Выводы

Вот и все. В этой статье мы рассмотрели как выполняется настройка ip адреса linux. Все это может показаться сложным, но если хорошо разобраться, то смена ip linux уже не будет вызывать таких проблем. Если у вас остались вопросы, спрашивайте в комментариях!

На завершение, видео о том что значат цифры ip адреса и зачем они нужны:

Источник

Читайте также:  Check system time windows
Оцените статью