Linux Device Drivers 2nd Edition, страница 100

PDF-файл Linux Device Drivers 2nd Edition, страница 100 Основы автоматизированного проектирования (ОАП) (17688): Книга - 3 семестрLinux Device Drivers 2nd Edition: Основы автоматизированного проектирования (ОАП) - PDF, страница 100 (17688) - СтудИзба2018-01-10СтудИзба

Описание файла

PDF-файл из архива "Linux Device Drivers 2nd Edition", который расположен в категории "". Всё это находится в предмете "основы автоматизированного проектирования (оап)" из 3 семестр, которые можно найти в файловом архиве МГТУ им. Н.Э.Баумана. Не смотря на прямую связь этого архива с МГТУ им. Н.Э.Баумана, его также можно найти и в других разделах. Архив можно найти в разделе "книги и методические указания", в предмете "основы автоматизированного производства (оап)" в общих файлах.

Просмотр PDF-файла онлайн

Текст 100 страницы из PDF

The same applies to the source address of received packets.To achieve this kind of “hidden loopback,” the snull interface toggles the least significant bit of the third octet of both the source and destination addresses; that is,it changes both the network number and the host number of class C IP numbers.The net effect is that packets sent to network A (connected to sn0, the first interface) appear on the sn1 interface as packets belonging to network B.To avoid dealing with too many numbers, let’s assign symbolic names to the IPnumbers involved:•snullnet0 is the class C network that is connected to the sn0 interface.Similarly, snullnet1 is the network connected to sn1.

The addresses ofthese networks should differ only in the least significant bit of the third octet.•local0 is the IP address assigned to the sn0 interface; it belongs to snullnet0. The address associated with sn1 is local1. local0 and local1must differ in the least significant bit of their third octet and in the fourthoctet.42722 June 2001 16:43http://openlib.org.uaChapter 14: Network Drivers•remote0 is a host in snullnet0, and its fourth octet is the same as that oflocal1. Any packet sent to remote0 will reach local1 after its class Caddress has been modified by the interface code. The host remote1 belongsto snullnet1, and its fourth octet is the same as that of local0.The operation of the snull interfaces is depicted in Figure 14-1, in which the hostname associated with each interface is printed near the interface name.remote0snullnet0localnetlolocalhostsn0local0eth0morganasn1local1snullnet1remote1Figur e 14-1.

How a host sees its interfacesHere are possible values for the network numbers. Once you put these lines in/etc/networks, you can call your networks by name. The values shown were chosen from the range of numbers reserved for private use.snullnet0snullnet1192.168.0.0192.168.1.0The following are possible host numbers to put into /etc/hosts:192.168.0.1192.168.0.2192.168.1.2192.168.1.1local0remote0local1remote1The important feature of these numbers is that the host portion of local0 is thesame as that of remote1, and the host portion of local1 is the same as that ofremote0.

You can use completely different numbers as long as this relationshipapplies.42822 June 2001 16:43http://openlib.org.uaHow snull Is DesignedBe careful, however, if your computer is already connected to a network. Thenumbers you choose might be real Internet or intranet numbers, and assigningthem to your interfaces will prevent communication with the real hosts. For example, although the numbers just shown are not routable Internet numbers, theycould already be used by your private network if it lives behind a firewall.Whatever numbers you choose, you can correctly set up the interfaces for operation by issuing the following commands:ifconfig sn0 local0ifconfig sn1 local1case "‘uname -r‘" in 2.0.*)route add -net snullnet0 dev sn0route add -net snullnet1 dev sn1esacThere is no need to invoke route with 2.2 and later kernels because the route isautomatically added.

Also, you may need to add the netmask 255.255.255.0parameter if the address range chosen is not a class C range.At this point, the “remote” end of the interface can be reached. The followingscreendump shows how a host reaches remote0 and remote1 through the snullinterface.morgana% ping -c 2 remote064 bytes from 192.168.0.99: icmp_seq=0 ttl=64 time=1.6 ms64 bytes from 192.168.0.99: icmp_seq=1 ttl=64 time=0.9 ms2 packets transmitted, 2 packets received, 0% packet lossmorgana% ping -c 2 remote164 bytes from 192.168.1.88: icmp_seq=0 ttl=64 time=1.8 ms64 bytes from 192.168.1.88: icmp_seq=1 ttl=64 time=0.9 ms2 packets transmitted, 2 packets received, 0% packet lossNote that you won’t be able to reach any other “host” belonging to the two networks because the packets are discarded by your computer after the address hasbeen modified and the packet has been received.

For example, a packet aimed at192.168.0.32 will leave through sn0 and reappear at sn1 with a destinationaddress of 192.168.1.32, which is not a local address for the host computer.The Physical Transport of PacketsAs far as data transport is concerned, the snull interfaces belong to the Ethernetclass.snull emulates Ethernet because the vast majority of existing networks—at leastthe segments that a workstation connects to—are based on Ethernet technology,be it 10baseT, 100baseT, or gigabit. Additionally, the kernel offers some42922 June 2001 16:43http://openlib.org.uaChapter 14: Network Driversgeneralized support for Ethernet devices, and there’s no reason not to use it.

Theadvantage of being an Ethernet device is so strong that even the plip interface (theinterface that uses the printer ports) declares itself as an Ethernet device.The last advantage of using the Ethernet setup for snull is that you can run tcpdump on the interface to see the packets go by. Watching the interfaces with tcpdump can be a useful way to see how the two interfaces work.

(Note that on 2.0kernels, tcpdump will not work properly unless snull’s interfaces show up asethx. Load the driver with the eth=1 option to use the regular Ethernet names,rather than the default snx names.)As was mentioned previously, snull only works with IP packets. This limitation isa result of the fact that snull snoops in the packets and even modifies them, inorder for the code to work.

The code modifies the source, destination, and checksum in the IP header of each packet without checking whether it actually conveysIP information. This quick-and-dirty data modification destroys non-IP packets. Ifyou want to deliver other protocols through snull, you must modify the module’ssource code.Connecting to the KernelWe’ll start looking at the structure of network drivers by dissecting the snullsource. Keeping the source code for several drivers handy might help you followthe discussion and to see how real-world Linux network drivers operate.

As aplace to start, we suggest loopback.c, plip.c, and 3c509.c, in order of increasingcomplexity. Keeping skeleton.c handy might help as well, although this sampledriver doesn’t actually run. All these files live in drivers/net, within the kernelsource tree.Module LoadingWhen a driver module is loaded into a running kernel, it requests resources andoffers facilities; there’s nothing new in that. And there’s also nothing new in theway resources are requested. The driver should probe for its device and its hardware location (I/O ports and IRQ line)—but without registering them—asdescribed in “Installing an Interrupt Handler” in Chapter 9.

The way a networkdriver is registered by its module initialization function is different from char andblock drivers. Since there is no equivalent of major and minor numbers for network interfaces, a network driver does not request such a number. Instead, thedriver inserts a data structure for each newly detected interface into a global list ofnetwork devices.Each interface is described by a struct net_device item.

The structures forsn0 and sn1, the two snull interfaces, are declared like this:43022 June 2001 16:43http://openlib.org.uaConnecting to the Kernelstruct net_device snull_devs[2] = {{ init: snull_init, }, /* init, nothing more */{ init: snull_init, }};The initialization shown seems quite simple—it sets only one field. In fact, thenet_device structure is huge, and we will be filling in other pieces of it later on.But it is not helpful to cover the entire structure at this point; instead, we willexplain each field as it is used. For the interested reader, the definition of thestructure may be found in <linux/netdevice.h>.The first struct net_device field we will look at is name, which holds theinterface name (the string identifying the interface).

The driver can hardwire aname for the interface or it can allow dynamic assignment, which works like this:if the name contains a %d format string, the first available name found by replacing that string with a small integer is used. Thus, eth%d is turned into the firstavailable ethn name; the first Ethernet interface is called eth0, and the othersfollow in numeric order. The snull interfaces are called sn0 and sn1 by default.However, if eth=1 is specified at load time (causing the integer variablesnull_eth to be set to 1), snull_init uses dynamic assignment, as follows:if (!snull_eth) { /* call them "sn0" and "sn1" */strcpy(snull_devs[0].name, "sn0");strcpy(snull_devs[1].name, "sn1");} else { /* use automatic assignment */strcpy(snull_devs[0].name, "eth%d");strcpy(snull_devs[1].name, "eth%d");}The other field we initialized is init, a function pointer.

Свежие статьи
Популярно сейчас
Зачем заказывать выполнение своего задания, если оно уже было выполнено много много раз? Его можно просто купить или даже скачать бесплатно на СтудИзбе. Найдите нужный учебный материал у нас!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
5259
Авторов
на СтудИзбе
421
Средний доход
с одного платного файла
Обучение Подробнее