- Создание и настройка виртуальных сетевых интерфейсов в Linux
- 1. Введение
- 2. Временный виртуальный сетевой интерфейс
- 2.1. Отключение виртуального сетевого интерфейса
- 3. Присвоение виртуальному интерфейсу постоянного адреса
- 3.1. Debian / Ubuntu
- 3.1.1. Статический адрес
- 3.1.2. Dhcp
- 3.2. Redhat / Fedora / CentOS
- 3.2.1. Статический адрес
- 3.2.2. Dhcp
- 4. Заключение
- Virtual addressing in linux
- mtds / lvn.md
Создание и настройка виртуальных сетевых интерфейсов в Linux
1. Введение
Знаете ли вы, что можете присвоить более чем один IP-адрес физическому сетевому интерфейсу? Эта техника очень полезна, например при работе с Apache и виртуальными хостами, так как позволяет получить доступ к одному и тому же серверу Apache с двух разных IP-адресов.
2. Временный виртуальный сетевой интерфейс
Процесс создания виртуального сетевого интерфейса в Linux не занимает много времени. Он включает один запуск команды ifconfig.
Приведенная выше команда создает виртуальный сетевой интерфейс, базирующийся на оригинальном физическом сетевом интерфейсе eth0. Самое важное условие для создания виртуального сетевого интерфейса — должен существовать физический сетевой интерфейс, в нашем случае eth0. Ниже приведен полный пример:
Теперь мы можем настроить новый виртуальный интерфейс на базе eth0. После выполнения команды ifconfig новый виртуальный интерфейс готов к немедленному использованию.
2.1. Отключение виртуального сетевого интерфейса
Для отключения нашего, созданного ранее, временного сетевого интерфейса мы можем также использовать команду ifconfig с флагом down.
3. Присвоение виртуальному интерфейсу постоянного адреса
Описанные выше настройки не сохраняются после перезагрузки. Если вы хотите, чтобы виртуальный сетевой интерфейс работал постоянно, необходимо модифицировать конфигурационные файлы в соответствии с требованиями вашего дистрибутива Linux. Ниже описан этот процесс для самых распространенных дистрибутивов:
3.1. Debian / Ubuntu
3.1.1. Статический адрес
В Debian или Ubuntu вам необходимо отредактировать файл /etc/network/interfaces, добавив в него следующие строки:
3.1.2. Dhcp
Возможно также использовать витруальный сетевой интерфейс с DHCP. В этом случае вам необходимо добавить в /etc/network/interfaces следующую строку:
Для того, чтобы изменения вступили в силу, необходимо перезапустить сеть:
3.2. Redhat / Fedora / CentOS
3.2.1. Статический адрес
В Redhat, Fedora или CentOS Linux директория, отвечающая за присвоение постоянных IP-адресов — это /etc/sysconfig/network-scripts. В этой директории необходимо создать файл, соответствующий вашему новому виртуальному интерфейсу. В нашем случае этот файл будет называться ifcfg-eth0:0. Создайте этот новый файл и вставьте в него приведенные ниже строки. После перезагрузки адрес будет присвоен виртуальному интерфейсу на постоянной основе.
3.2.2. Dhcp
Когда закончите, перезапустите ваши интерфейсы:
4. Заключение
Раньше один физический сервер обслуживал один веб-сайт. Сегодня такой способ хостинга уже не является жизнеспособным, поэтому способность операционной системы создавать виртуальные сетевые интерфейсы действительно необходима.
Источник
Virtual addressing in linux
This is very Simple to create a virtual address rather than a existing Physical Network Interface.:
So let us consider the IP address assigned and the device name as ” eth0″:
now normally when the IP is not set it will be in DHCP automatically so we need to create a physical Network Interface as mentioned above.
Now let see how to add another IP address in the same physical address eth0:0
- You must be in root access to perform these operation.
Simple way to create an virtual ip address :
Command : ” ifconfig eth0:1 inet 192.168.1.136 netmask 255.255.255.0 “
First check whether your host system Network is in DHCP (automatic IP address ) or It is in static IP, you must manually enter the ip address ,subnet mask, default gateway.
Navigation to perfrom: —->System Tab in taskbar-Administrator tab- select “Network” . you will get a pop up window.
In that you will get a Network Configuration pop up window there u will be having device as eth0, in that you must specify the Static IP address ,subnet,default gateway…if it is not available then it will be in DHCP automatic IP mode so you must not leave it in Dynamic Host…
After setting ip address you must check the ip address in terminal window by entering the command –“ifconfig ” to check the ip address is been assigned accordingly…
when you perform this and save this network information will be stored in certain directory i.e in:
Lets start with creating a new virtual IP address in the same host:
- First you must copy the existing etho (ethernet ) content into a new virtual ip address what you are creating
Note: “The main concept here is you must have the “physical network Interface” (the device name above metioned in the window) it must be same as eth0 i.e when you start creating a virtual ip address the physical network Interface name(device name) must be same as etho and you must start with ( : ) and enter the number accordingly for example :eth0:1, eth0:2 etc…
- command to copy the the existing eth0 contents into new virtual ip address:
There are two ways to execute the copy command (you must be in super used i.e in root access) you can just copy by navigating through the directories :
Command: ” cp /etc/sysconfig/network-scripts/ifcfg-etho /etc/sysconfig/network-scripts/ifcfg-etho:1 “
Here the content of the “etho” will be copied to the newly created “eth0:1″…
other way is to changing the directory to the network-script i.e entering into it:
Command : cd /etc/sysconfig/network-scripts and press enter.
you will enter into the network-scripts directory:
the you list the contents by using ls command:
Here the content in the directory network – script is been listed there you can find ” ifcfg-eth0″ thats the physical network interface…..
so you need to copy the contents to the newly creating ethernet device (ip address)
Command: “ cp ifcfg-eth0 ifcfg-eth0:1 “
After executing the command the cursor goes down indicating its been copied and if you check again by ls command you can able to see ifcfg-eth0:1
- now the virtual ip is set and you need to change two options in it so you can change in two ways:
- Using vi editor
- Using nano
lest Use vi editor to change:
- Command here is : vi eth0:1
after this press enter button to enter in the vi editor:
Note: simple concept in vi editor is first command : “vi filename” and when you enter into the editor you can change the contents or edit by pressing the insert key i.e ” i ” button.. and when you finish it has standard exit procedure i.e we need to say and exit so you must press esc button and : (colon) wq ,,here w-write q-quit i.e save and quit….
Here you will be having the contents which were presented in the “eth0″ default physical network interface contents..
In this we must change two things :
- DEVICE= etho:1
- IPADDR=192.168.1.136
These two is mandatory to create a virtual ip address and the Device name …
After doing this exit the vi editor by standard procedure as mentioned above…
Now the virtual ip Address is set and stored in the corresponding directories with changes.
- The final step is to Restart the network service
After exiting the vi editor you will be back to the terminal and in there you must type the command
Command: ” service network restart “
Now the virtual Ip address is set and ready to use…
to check the ip address is set type in the command ifconfig .
Here the new virtual Ip address in the name of eth0:1 is created and the ip address is been changed to 192.168.1.136
now the host system has two ip address to use..
Источник
mtds / lvn.md
Virtual Networking on Linux
In the Linux Kernel, support for networking hardware and the methods to interact with these devices is standardized by the socket API:
In order to support new kind of computational workloads, different deployment scenarios and a better use of HW resources the Linux OS supports virtualization of different computing resources: CPU, memory, storage and networking. Virtual networking capabilities are indeed used as a basis for hosting VMs and containers.
A general overview of virtual networking components available in Linux is described in this article from the IBM developerworks web site.
Types of virtual Network Interfaces
- Bridge: A Linux bridge behaves like a network switch. It forwards packets between interfaces that are connected to it. It’s usually used for forwarding packets on routers, on gateways, or between VMs and network namespaces on a host. It also supports STP, VLAN filter, and multicast snooping.
- TUN: TUN (network Tunnel) devices work at the IP level or layer three level of the network stack and are usually point-to-point connections. A typical use for a TUN device is establishing VPN connections since it gives the VPN software a chance to encrypt the data before it gets put on the wire. Since a TUN device works at layer three it can only accept IP packets and in some cases only IPv4. If you need to run any other protocol over a TUN device you’re out of luck. Additionally because TUN devices work at layer three they can’t be used in bridges and don’t typically support broadcasting.
- TAP: TAP (terminal access point) devices, in contrast, work at the Ethernet level or layer two and therefore behave very much like a real network adaptor. Since they are running at layer two they can transport any layer three protocol and aren’t limited to point-to-point connections. TAP devices can be part of a bridge and are commonly used in virtualization systems to provide virtual network adaptors to multiple guest machines. Since TAP devices work at layer two they will forward broadcast traffic which normally makes them a poor choice for VPN connections as the VPN link is typically much narrower than a LAN network (and usually more expensive).
- VETH: Virtual Ethernet interfaces are essentially a virtual equivalent of a patch cable, what goes in one end comes out the other. When either device is down, the link state of the pair is down.
An example of creating a bridge:
Enslaving a network interface to a bridge:
An example of creating two virtual ethernet interfaces (ep1,ep2) and linking them together:
veth interfaces can also be linked to a bridge:
It is also possible to add IP addresses to the interfaces, for example:
All the network interfaces available will be shown with: ip address show
Many other types of virtual network interfaces are available, as described in this post from the RedHat developers blog.
Namespaces are a feature available on the Linux kernel which is used as a basis for many software technology like Linux Containers (LXC), Docker and software-defined network (SDN) solutions. It basically allows to define and use multiple virtual instances of the resources available on a host.
Linux namespaces include (additional references are available in the man page):
In particular, network namespaces allow individual containers to have exclusive access to virtual network resources, while each container can be assigned a separate network stack.
Network namespaces allows different processes to have different views of the network and different aspects of networking can be isolated between processes:
- Interfaces: different processes can connect to addresses on different interfaces.
- Routes: since processes can see different addresses from different namespaces, they also need different routes to connect to networks on those interfaces.
- Firewall rules: since these are dependant on the source or target interfaces, you may need different firewall rules in different network namespaces.
Handling of network namespaces are done with the ip command, which is part of the iproute2 package.
NOTE: all the commands in the following examples have to be executed directly by root or with root privileges (e.g. with sudo ).
Create, list and delete a network namespace:
ns1 is a network NS which is completely separated from the default one (which is always available after every Linux boot).
Distinct network namespaces can be connected together using veth interfaces:
Virtual ethernet interfaces can be assigned an IP address, inside a network class
Once the IPs are assigned, the veth interfaces have to be brought in UP state:
An example of running a ping command between the two different namespaces through the veth interfaces:
A network namespace can have its own network interface assigned to it, for example the loopback interface (which is by default always present on new network NS but in DOWN state):
It can also have a separated routing table (note that when the network namespace is initially set, the routing table is empty):
Once a network NS is created, it will shows up in multiple places:
A virtual network with network namespaces and a bridge
Considering the following properties:
- network NS can have their own network routes;
- virtual ethernet interfaces comes in pairs;
- it’s possible to assign a network interface to a different network NS;
it is then possible to build an example of multiple network NSs connected together through a Linux bridge and routing rules inside the same physical host. A bridge device give us the virtual equivalent of a network switch, allowing us to connect multiple interfaces (virtual or not), and have them communicate with each other.
The following is a conceptual schema:
- br-veth<1,2>: veth attached to the bridge
- veth<1,2>: veth part of their respective network NS
First, two network NS will be created:
Then two pairs of veth will be created:
Now two of the new veths will be attached to the network NS ( br-veth is just a convenient naming convention but it does not identify a veth connected to a bridge).
The two veth <1,2>will be shown only in their respective networks NS:
Note: the veth1 is marked as DOWN . The same goes for veth2 .
Assign the IP address 192.168.1.11 with netmask 255.255.255.0 to veth1:
An IP address (of the same network class) will be assigned also to veth2 :
Even when the two veth have assigned IP address they cannot communicate between each other: the reason is that there’s no configured interface on the default network namespace which can send the traffic to and from the two veth interfaces.
Adding a bridge it’s the only way to go further:
It can be verified that the bridge is available:
It’s now the time to connect the other two veth interfaces ( br-veth <1,2>) and attach them to the bridge:
In order to reach the veth interfaces through the routing table of the host itself, the bridge needs an IP address:
The brd string force to set the broadcast address (192.168.1.255), specifying the + symbol (255).
The routing table can be checked in this way:
From the global network NS it’s possible to reach both IP addresses (192.168.1.<11,12>) through a simple ping .
It’s also possible to reach ns2 from ns1, once the proper routing is defined:
And reaching ns2 can be tested in the following way:
If the setup will stop at this point, both the network NS will be basically isolated from the outside world: they can only ping each other (providing the internal route is configured) but cannot reach any other IP outside the 192.168.1.0/24 space.
In order to achieve this result we can use NAT (Network Address Translation) through iptables :
The previous command will specify that on the nat table we are appending ( -A ) a rule to the POSTROUTING chain for the source address specified ( -s ) and the action will be MASQUERADE .
Last but not least, the IP forwarding has to be enabled on the networking stack of the host:
A small test: send some packets to 8.8.8.8:
Источник