TCP-IP Essentials-A Lab-Based Approach
TCP-IP Essentials-A Lab-Based Approach
TCP/IP Essentials
The TCP/IP family of protocols have become the de facto standard in the world of
networking, are found in virtually all computer communication systems, and form the
basis of today’s Internet. TCP/IP Essentials is a hands-on guide to TCP/IP technologies,
and shows how the protocols operate in practice. The book contains a series of carefully
designed and extensively tested laboratory experiments that span the various elements of
protocol definition and behavior. Topics covered include bridges, routers, LANs, static
and dynamic routing, multicast and realtime service, and network management and
security. The experiments are described in a Linux environment, with parallel notes on
Solaris implementation. The book includes many exercises, and supplementary material
for instructors is available. The book is aimed at students of electrical and computer
engineering or computer science who are taking courses in networking. It is also an ideal
guide for engineers studying for networking certifications.
Shivendra S. Panwar
Department of Electrical and Computer Engineering,
Polytechnic University, Brooklyn, New York
Shiwen Mao
The Bradley Department of Electrical and Computer Engineering,
Virginia Polytechnic Institute and State University
Blacksburg, Virginia
Jeong-dong Ryoo
Electronics and Telecommunications Research Unit,
Daejeon, South Korea
Yihan Li
Department of Electrical and Computer Engineering,
Polytechnic University,
Brooklyn, New York
CAMBRIDGE UNIVERSITY PRESS
Cambridge, New York, Melbourne, Madrid, Cape Town, Singapore, São Paulo
Cambridge University Press has no responsibility for the persistence or accuracy of urls
for external or third-party internet websites referred to in this publication, and does not
guarantee that any content on such websites is, or will remain, accurate or appropriate.
To my wife, Shruti, my parents, and Choti.
Shivendra Panwar
To my wife, Kweesook, my children, James and Michelle, and my parents.
Jeong-dong Ryoo
To our son, Eric, and our parents.
Yihan Li and Shiwen Mao
Contents
0 TCP/IP overview 1
1.1 Objectives 26
1.2 Linux and TCP/IP implementations 26
1.3 Linux commands and tools 31
1.4 Diagnostic tools 35
vii
viii Contents
2.1 Objectives 43
2.2 Local area networks 43
2.3 Network interface 50
2.4 The Internet Control Message Protocol 52
2.5 The Sock traffic generator 54
2.6 Network interface exercises 54
2.7 ARP exercises 55
2.8 Exercises with ICMP and ping 58
2.9 Exercises with IP address and subnets mask 59
3.1 Objectives 61
3.2 Ethernet bridges 61
3.3 Configuring a bridge or router 66
3.4 Exercises on Cisco IOS 71
3.5 A simple bridge experiment 73
3.6 Spanning tree exercises 75
3.7 Exercise on the Cisco IOS web browser UI 76
4.1 Objectives 77
4.2 Static and dynamic routing 77
4.3 Manipulating routing tables 89
4.4 Traceroute 90
4.5 A simple router experiment 91
4.6 RIP exercises 93
4.7 Routing experiments with ICMP 95
ix Contents
Index 258
Preface
You can know the name of a bird in all the languages of the world, but when
you’re finished, you’ll know absolutely nothing whatever about the bird . . . So
let’s look at the bird and see what it’s doing – that’s what counts. I learned very
early the difference between knowing the name of something and knowing
something. Richard Feynman (1918–1988)
xiii
xiv Preface
students with the basic knowledge they need to perform the experiments
and derive insights from their observations during the course of the exper-
iments. Each lab experiment is designed to take no more than 3 hours to
complete.
The experiments were developed on the basis of a course taught at
the Polytechnic University over the course of over eight years. Initially,
we used SUN workstations with the Solaris operating system, but have
now switched to Linux machines. The primary operating system in this
book is Linux, but with Solaris commands provided when they differ
from Linux commands. Chapter 1 provides an introduction to Linux,
since many students may be unfamiliar with this operating system. It also
introduces key tools used in subsequent experiments such as tcpdump
and Ethereal. Chapter 2 introduces network interfaces, ping and IP ad-
dresses. Chapter 3 introduces bridges, also known as layer two switches,
bridge/router configuration, and the Cisco IOS. Chapter 4 focuses on rout-
ing, with RIP and OSPF as the routing protocols studied, along with the
useful traceroute utility. Chapter 5 introduces UDP and FTP. Chapter 6
follows up with TCP, including a study of its congestion control mecha-
nism. These six chapters are sufficient in many cases to introduce students
to the basics of TCP/IP. Nonetheless, the next three chapters are important
for students who wish to link the basic plumbing of TCP/IP with appli-
cations. Chapter 7 deals with IP multicast and realtime applications. The
web, DHCP, NTP and NAT are some key applications that are presented
in Chapter 8, as well as a brief introduction to socket programming. Net-
work management and security are arguably two of the most important
features that students need to know, at least at a basic level. Chapter 9
provides a brief introduction to this material, which can easily be the sub-
ject of a separate course. A list of key RFCs is provided at the end of the
book.
There are several alternative ways of teaching this material with this
book. A general knowledge of networking is assumed as a prerequisite for
this book. However, an introductory course in networking could be com-
bined with the first six experiments, back-loaded at the end of the course, to
illustrate the lowest four layers of the protocol stack. For computer scien-
tists, a top-down approach is sometimes the preferred approach in teaching
networking. In that case the lab experiments can be re-ordered to focus on
the higher layers.
xv Preface
Note to instructors
Additional course material, including lecture transparencies, sample lab
reports, homework assignments, examinations, and errata, are available at
the course website: www.cambridge.org/052160124X.
Acknowledgements
xvi
General conventions
options are in bold, while the parameters are in italics. For example, in
tcpdump -enx host ip addr1 and ip addr2,
the command tcpdump uses options -e, -n and -x. In the filter that fol-
lows, key words such as host, and, not, or etc., are also in bold. The
parameters are ip addr1 and ip addr2, which should be replaced with
the corresponding IP addresses during the exercise.
The following exemplary command,
/etc/init.d/snmpd start|stop,
uses two options. Either start or stop can be used, but not at the same
in the lab report. For example, for Exercise 1 in Chapter 1, students need
to answer the following question in Lab Report 1.
Lab report What is the default directory when you open a new command
guide can also be used with the Sun Solaris operating system. In the
following text, Linux-specific material, or general material that apply to
both operating systems are used, while the Solaris specific materials are
enclosed between horizontal lines.
xvii
Abbreviations
ACK Acknowledgement
AIMD Additive-Increase-Multiplicative-Decrease
API Application Programming Interface
ARP Address Resolution Protocol
ARPA Advanced Research Projects Agency
API Application Programming Interface
AS Autonomous System
ATM Asynchronous Transfer Mode
xviii
xix Abbreviations
! Internet Research Task Force (IRTF). The IRTF is responsible for fo-
protocol engineering and development.
ICANN has responsibility for Internet Protocol (IP) address space alloca-
tion, protocol identifier assignment, generic and country code Top-Level
Domain name system management, and root server system manage-
ment functions. These services were originally performed by the Internet
Assigned Numbers Authority (IANA) and other entities. ICANN now
Application layer
Transport layer
Network layer
! The transport layer provides data transport for the application layer,
the configuration of network interfaces.
! The network layer handles routing of packets across the networks, in-
simpler than TCP and does not guarantee reliability.
! Internet Control Message Protocol (ICMP). Used for error and control
which provides unreliable and connectionless service.
! The link layer handles all the hardware details to provide data transmis-
membership management.
sion for the network layer. Network layer protocols can be supported by
Application Layer
FTP BGP NFS BOOTP SNMP RTP
TCP UDP
Transport Layer
IP
Network Layer
Link Layer
ARP Ethernet, IEEE 802.3, IEEE 802.11 RARP
Token Ring, PPP, etc.
Host A Host B
Telnet Protocol
Telnet Telnet
TCP Protocol
TCP TCP
IP Protocol
IP IP
Figure 0.3. An illustration of the layers involved when two hosts communicate over the
same Ethernet segment or over an Ethernet hub.
Host A Host B
Telnet Protocol
Telnet Telnet
TCP Protocol
TCP TCP
IP Protocol
IP IP
Figure 0.4. An illustration of the layers involved when two hosts communicate through a
bridge.
Host A Host B
Telnet Protocol
Telnet Telnet
TCP Protocol
TCP TCP
IP IP
IP IP IP
LLC LLC
Ethernet Ethernet PPP PPP
Driver Driver Driver Driver
Figure 0.5. An illustration of the layers involved when two hosts communicate through a
router.
communicate with each other since the same link layer protocol is used.
Figure 0.4 shows how two different network segments using different link
layer technologies are interconnected using a bridge, which interfaces be-
tween the link layer protocols and performs frame forwarding. Figure 0.5
shows how two networks are interconnected by a router, which not only
performs the layer two functions as in Fig. 0.4, but also handles rout-
ing and packet forwarding, which are the major functions of the network
layer.
7 0.4 Encapsulation and multiplexing
User data
Applications
TCP segment IP
In a source host, the application data is sent down through the layers in
the protocol stack, where each layer adds a header (and maybe a trailer)
to the data received from its higher layer (called the protocol data unit
(PDU)). The header contains information used for the control functions
that are defined and implemented in this layer. This encapsulation process
is shown in Fig. 0.6. When the packet arrives at the destination, it is sent up
through the same protocol stack. At each layer, the corresponding header
and/or trailer are stripped and processed. Then, the recovered higher layer
data is delivered to the upper layer.
As explained in Section 0.2, one of the advantages of the layered structure
is the great flexibility it provides for network design and management. For
example, different higher layer protocols can use the service provided by
the same lower layer protocol, and the same higher layer protocol can
use the service provided by different lower layer protocols. In the first
8 TCP/IP overview
Protocol IP
ARP RARP
Ethernet
case, each packet sent down to the lower layer should have an identifier
indicating which higher layer module it belongs to. As is shown in Fig. 0.7,
multiplexing and demultiplexing is performed at different layers using the
information carried in the packet headers. For example, a communication
process running in a host is assigned a unique port number, which is carried
by all the packets generated by or destined to this process. Transport layer
protocols such as TCP or UDP determine whether a packet is destined for
this process by checking the port number field in the transport layer header.
In the IP case, each protocol using IP is assigned a unique protocol number,
which is carried in the Protocol IP header field in every packet generated
by the protocol. By examining the value of this field of an incoming IP
datagram, the type of payload can be determined. A field called Frame
Type in the Ethernet header is used for multiplexing and demultiplexing at
this level.
unnamed root
top-level arpa com edu gov int mil net org ae ... us ... zw
domains
Unite Zimbabwe
second- ny
in-addr cisco poly vt Arab
level
Emirates
domains
128 photon computing computing.vt.edu nyc
photon.poly.edu
238 mta.nyc.ny.us mta
100 100.66.238.128.in-addr.arpa
domain Description
top-level domains, .aero, .biz, .coop, .info, .museum, .name, and .pro, were
added to the Internet’s domain name system by ICANN in 2000.
Since the TCP/IP programs only recognize numbers, the domain name
system (DNS) is used to resolve, i.e., translate, a domain name to the
corresponding IP address. Then the resolved IP address, rather than the
domain name, is used in the TCP/IP kernel. DNS is a client/server type
of service. Since the entire database of domain names and IP addresses is
too large for any single server, it is implemented as distributed databases
maintained by a large number of DNS servers (usually host computers run-
ning the DNS server program). Thus each DNS server only maintains a
portion of the domain name database shown in Fig. 0.8. A host can query
the DNS servers for the IP address associated with a domain name, or for
the domain name associated with an IP address. If the DNS server being
queried does not have the target entry in its database, it may contact other
DNS servers for assistance. Or, it may returns a list of other DNS servers
that may contain the information. Thus the client can query these servers
iteratively.
It is inefficient to perform name resolution for the same domain name
every time its IP address is requested. Instead, DNS servers and clients
use name caching to reduce the number of such queries. A DNS server
or client maintains a cache for the names and corresponding IP addresses
which have been recently resolved. If the requested domain name is in the
cache, then there is no need to send a DNS query to resolve it. In addition,
each cached entry is associated with a Time-to-Live timer. The value of
this timer, which is usually set to the number of seconds in two days when
the entry is first cached, is determined by the server that returns the DNS
reply. The entry will be removed from the cache when the timer expires.
11 0.5 Naming and addressing
0.5.3 IP address
Each host interface in the Internet has a unique IP address. A host with
multiple interfaces and hence multiple IP addresses is called a multi-homed
host. An IP address is a 32-bit number written in the dotted-decimal nota-
tion, i.e., as four decimal numbers, one for each byte, separated by three
periods.
The global IP address space is divided into five classes, as shown in
Table 0.2. Each IP address has two parts, a network ID, which is common
for all the IP addresses in the same network, and a host ID, which is unique
among all hosts in the same network. Figure 0.9 shows the IP address
formats for the classes, where all class A IP addresses start with “0”, all
Class From To
A 0.0.0.0 127.255.255.255
B 128.0.0.0 191.255.255.255
C 192.0.0.0 223.255.255.255
D 224.0.0.0 239.255.255.255
E 240.0.0.0 255.255.255.255
12 TCP/IP overview
Subnet Mask: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0
= 0xFFFFFF00 = 255.255.255.0
Subnet Mask: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0
= 0xFFFFFFC0 = 255.255.255.192
Figure 0.10. An example of subnet masks for two different class B subnet design.
address. The first example uses a 24-bit subnet mask, resulting in a 8-bit
subnet ID and a 8-bit host ID. Therefore, there could be 28 = 256 subnets
and 28 − 2 = 254 hosts2 in each subnet with this subnetting scheme. In the
second example, a 26-bit subnet mask is used, resulting in a 10-bit subnet
ID and a 6-bit host ID. Therefore, there could be 210 = 1024 subnets and
26 − 2 hosts in each subnet with this subnetting scheme. Given a network
address, the administrator can flexibly trade off the number of bits needed
for the subnet ID and for the host ID, to find a subnetting arrangement best
suited for the administrative and operative requirements.
The network ID is often referred to as the network-prefix. When subnet-
ting is used, the combination of the network ID and subnet ID is called the
extended-network-prefix. In addition to using the IP address and network
mask pair, a slash-notation is often used by network engineers, where an IP
address is followed by a “/” and the number of 1’s in the subnet mask. For
example, the class B address arrangements in Fig. 0.10 can be expressed
as 128.238.66.101/24 and 128.238.66.101/26, respectively.
With the combination of an IP address and a port number, a process
running in a host is uniquely identified in the global Internet, since the IP
address is unique in the Internet and the port number is unique within the
host. The combination of an IP address and a port number is called a socket.
0.5.4 IP version 6
Since it was born, the Internet has been growing exponentially. Every new
host computer being connected needs a unique IP address. The recent trends
of pervasive computing that connects laptop computers, personal digital
assistants (PDA), and cell phones to the Internet, and home networking that
connects consumer electronic devices and home appliances to the Internet
require yet more IP addresses.
However, when the current version of IP (IPv4) was designed, it was
never imagined that the size of the Internet would be so huge. According
to [3], the 32-bit IPv4 addresses will be depleted between 2005 and 2015.
Some short-term solutions have been proposed to slow down the depletion
! A simpler header format. IPv6 uses a 40-byte fixed length header format.
tions. Some major enhancements are listed.
Some fields in the IPv4 header that are not frequently used are removed.
Options are now supported by extension headers that follow the 40-byte
for realtime services. With the flow label, intermediate routers can eas-
ily identify the flow to which a packet belongs, allowing for differenti-
ated service of packets from different flows. For example, IP datagrams
15 0.6 Multiple access
each other and be corrupted. Hosts should be able to check the availability of
the medium and to resolve a collision. In addition, since the total bandwidth
of the medium is limited, it is desirable to share it efficiently in terms of
the aggregate throughput of all the hosts. Furthermore, each host should
have a fair chance to access the medium and should not be allowed to take
it forever.
The sharing-rules are defined as medium access control (MAC) pro-
tocols. Two examples are: Carrier Sense Multiple Access/Collision
Detection (CSMA/CD, used in Ethernet), and Carrier Sense Multiple Ac-
cess/Collision Avoidance (CSMA/CA, used in wireless LANs). MAC pro-
tocols are implemented in the link layer. We will discuss CSMA/CD and
CSMA/CA in Chapter 2.
Figure 0.11. An illustration of flow control and congestion control in the Internet.
is discarded. IP, ICMP, IGMP, UDP and TCP use this algorithm to detect
errors in the headers.
Ethernet, on the other hand, uses the cyclic redundancy check (CRC)
technique to detect errors in the entire frame. With CRC, the entire frame
is treated as a single number, and is divided by a predefined constant, called
the CRC generator. The remainder of the division operation is appended to
the frame (as the trailer) and sent to the receiver. After receiving the frame,
the receiver performs the same division and compares the remainder with
the received one. If the two are identical, there is no error in the frame.
Otherwise, the frame is corrupted and should be discarded.
In addition to bit errors in a received packet, packets may be lost if there
is congestion in the network, or if an incorrect route is used. Sequence num-
bers can be used to detect this type of error. With this technique, the sender
and the receiver first negotiate an initial sequence number. Then the sender
assigns a unique sequence number to each packet sent, starting from the
initial sequence number and increased by one for each packet sent. The re-
ceiver can detect which packets are lost by ordering the received sequence
numbers and looking for gaps in them.
When a packet loss is detected, the receiver may notify the sender, and
request for a retransmission of the lost packet. In addition, the sender can
use other error control schemes, such as forward error correction (FEC), in
the application layer for better protection of the application data. We will
examine TCP error control in Chapter 6.
The basic control functions discussed in the previous sections are imple-
mented in different layers, while the information used by the control func-
tions are carried in the packet headers. In this section, we examine the
header formats of Ethernet, IP, UDP and TCP, which will be frequently
used in discussions and data analysis in the following chapters.
Differentiated
Version Hdr Len Total Length
Services
Identification Flags Fragment Offset
Time to Live Protocol Header Checksum
Source IP Address
Destination IP Address
Options (if any, <= 40 bytes)
Data
example, this field is set to 0x0800 for IP datagrams, 0x0806 for ARP
requests and replies, and 0x0835 for RARP requests and replies. The 4-
byte trailer is the CRC bits used for error control.
! Flags: 3 bits. Consists of a 3-bit field of which the lower two bits control
datagram.
destination of the data. The protocol field values for several higher
layer protocols are: 1 for ICMP, 2 for IGMP, 6 for TCP, and 17 for
Data (optional)
! Source Port Number: 16 bits. The port number of the source process.
! Destination Port Number: 16 bits. The port number of the process
! Sequence Number: 32 bits. Identifies the byte in the stream of data from
running in the destination host.
the sending TCP to the receiving TCP. It is the sequence number of the
! RST: If the fourth bit is set, it signals a request to reset the TCP con-
cation as soon as possible.
! SYN: The fifth bit of the flag field of the packet is set when initiating a
nection.
! TCP Checksum: 16 bits. Covers both the TCP header and TCP data.
can accept.
! Urgent Pointer: 16 bits. If the URG flag is set, the pointer points to the
last byte of the urgent message in the TCP payload. More specifically, the
last byte of the urgent message is identified by adding the urgent pointer
value to the sequence number in the TCP header.
23 0.11 An example: how TCP/IP protocols work together
In this section, we show how a packet is forwarded from the source to the
destination. As shown in Fig. 0.17, assume a user, named Bob, wants to
book an air ticket from the website: http://www.expedia.com. Here is
what happens in the system kernel and in the network.
First, Bob needs to know the domain name www.expedia.com, e.g.,
from a TV commercial or a web advertisement. If he happens to know the
IP address corresponding to this domain name, he can use the IP address
instead.
The remote computer with the domain name www.expedia.com is a web
server, which is always running and provides the web service. Bob can use
a web browser, which is a web client, to request and receive web service,
i.e., to browse a web page. The HyperText Transfer Protocol (HTTP) is
used by the web server and web browser. Most of the network services
are provided using such a client–server architecture. We will discuss the
client–server architecture in Chapter 5, and we will examine a web server
in Chapter 8.
Bob starts a web browser, e.g., Mozilla, in his computer. Then he types
http://www.expedia.com/index.html in the Location input area.
The prefix http indicates the application layer protocol for this transaction,
followed by the domain name of the web server, www.expedia.com, and
the target file, index.html, in the server.
Next, the web browser needs to translate the domain name to an IP
address, since domain names are not recognizable by the TCP/IP kernel.
This is done via a query–response process using a protocol called the
Domain Name System (DNS). The web browser invokes a function in the
TCP/IP kernel called gethostbyname(), to send a DNS query which in
24 TCP/IP overview
driver is responsible for delivering the Ethernet frame to the interface of the
next-hop router. Before sending the Ethernet frame out, the device driver
has to resolve the next-hop IP address, since it only recognizes Ethernet
MAC addresses. An ARP request is broadcast, querying the MAC address
associated with the target IP address. When the router interface receives
this ARP request, it responses with an ARP reply containing its MAC
address. Then, the frame is sent on the medium after the ARP reply is
received and the destination MAC address is learned. Note that whenever
the host sends a frame, it uses the CSMA/CD multiple access algorithm to
access the channel and may backoff if collision occurs. We will examine
the operation and configuration of an Ethernet interface in Chapter 2.
Bob’s local network consists of several LAN segments. Several IEEE
802.1d bridges, which are self-configuring and transparent, are used to
connect the LAN segments. The spanning tree algorithm is running in the
bridges to avoid loops in the local network. In this example, the Ethernet
frame is first transmitted on the host’s LAN segment, and then forwarded
to the router interface by an intermediate bridge. We will examine bridges
and the spanning tree protocol in Chapter 3.
Subsequently, the IP datagram is forwarded hop-by-hop by the interme-
diate routers along the route towards its destination. Some of the routers
may be connected by point-to-point long-haul connections running the
SDH/SONET protocol. Finally, the remote host’s MAC module receives
the Ethernet frame. The packet is delivered to the upper layers. At each
layer, the corresponding header is stripped and examined. The informa-
tion carried in the headers is used for such functions such as routing and
forwarding, error control, flow control, and congestion control. In addi-
tion, the information is also used to identify which higher layer module
the payload data belong to. When the Web server at the application layer
receives the HTTP request message, it assembles an HTTP response
message containing the requested file, and sends the response to the client.
The response message is forwarded back to Bob’s host, through a similar
procedure. Finally, Bob can see the homepage of www.expedia.com in his
web browser.
1 Linux and TCP/IP networking
The Linux philosophy is ‘Laugh in the face of danger’. Oops. Wrong One. ‘Do it
yourself’. Yes, that’s it. Linus Torvalds
1.1 Objectives
!
!
Getting acquainted with the lab environment.
!
Getting acquainted with the Linux operating system.
!
Preview of some TCP/IP diagnostic tools.
!
Capturing and analyzing the link layer, IP, and TCP headers.
!
Understanding the concept of encapsulation.
Understanding the concept of multiplexing using port numbers, the IP
Processes
System Calls
Socket Layer
Protocol Layer
TCP, UDP, IP, ICMP, IGMP
Interface Layer
Ethernet, PPP, IEEE 802.11, etc.
Media
1 The core of an operating system, implementing critical system functions, e.g., managing memory
and file systems, loading and executing other programs, and scheduling processes.
28 Linux and TCP/IP networking
···
ftp stream tcp nowait root /usr/sbin/tcpd in.ftpd ftpd
telnet stream tcp nowait root /usr/sbin/tcpd in.telnetd
···
#finger stream tcp nowait root /usr/sbin/tcpd in.fingerd
···
# default: off
# description: An echo server. This is the tcp \
# version.
service echo
{
disable = no
type = INTERNAL
id = echo-stream
socket type = stream
protocol = tcp
user = root
wait = no
}
Solaris uses the following network configuration files stored in the /etc
directory.
nodename Host name of the machine.
hostname.interface Interface IP address or the interface name.
! chmod who op-code permission file or directory name: Changes the file
cp file name directory name: Copies a file into directory name.
access permissions.
who: u user, g group, o other users, a all;
op-code: + add permission, − remove permission;
Most of the above commands accept input from the system’s standard
input device (e.g., the keyboard) and send an output to the system’s standard
output device (e.g., the screen). Sometimes it is convenient to direct the
output to another process as input for further processing, or to a file for
storage. The redirect operator “>” directs the output to a file, as:
command > file name.
With the pipe operator “|”, two commands can be concatenated as:
command1 | command2,
where the output of command1 is redirected as the input of command2.
To delete text, place the cursor over the target position, and type the
following commands.
To search for a special string, e.g. foo, in the text file, type /foo in the
command mode. The cursor will jump to the nearest matching position in
the file. To repeat the last search, type n in the command mode.
To save the file and quit vi, press Esc (even if in the command mode, it
doesn’t hurt), and type :wq. To quit vi without saving changes to the file,
use the command :q!
In Solaris, a user may use xwd and an additional tool called xpr to dump
a window. The pipe operator is used to conveniently redirect the output of
xwd as the input of xpr, as:
xwd | xpr -device ps -output file name
After the shape of the mouse pointer changes, click the mouse in the target
window. The keyboard bell rings once at the beginning of the dump and
twice when the dump is completed. The dumped file may be examined with
Image tools found in the Programs menu.
3 Different keyboards may have different names for this key. For example, Prnt Scrn or PrtSc.
4 /dev/fd0 is the device name of the floppy driver. The device names and their corresponding mount
points are defined in the /etc/fstab file. For example, the CDROM has a device name /dev/cdrom
and is mounted to the /mnt/cdrom directory.
35 1.4 Diagnostic tools
In Solaris, the CDROM and floppy drives are controlled by the volume man-
ager, which is a daemon process named vold. When a floppy disk is inserted
in the drive, vold does not automatically recognize it (However, it recog-
nizes a CD automatically). The user should type the volcheck command,
which mounts the floppy disk under the /floppy/floppy0 directory. To
eject the floppy disk, use the eject command. To format a MD-DOS disk,
use fdformat -v -U -d.
1.4.1 Tcpdump
Tcpdump is a network traffic sniffer built on the packet capture library
libpcap.5 While started, it captures and displays packets on the LAN
segment. By analyzing the traffic flows and the packet header fields, a
5 A public domain packet capture library written by the Network Research Group (NRG) of the
Information and Computing Sciences Division (ICSD) of the Lawrence Berkeley National Laboratory
(LBNL) in Berkeley, California.
36 Linux and TCP/IP networking
great deal of information can be gained about the behavior of the protocols
and their operation within the network. Problems in the network can also be
identified. A packet filter can be defined in the command line with different
options to obtain a desired output.
A typical output of tcpdump running on a 128.238.66.0 subnet is shown
in Fig. 1.2. The first line of the output gives a summary of the link/IP/TCP
headers, while the following data block contains the raw bits of the IP
datagram.
1.4.2 Ethereal
Ethereal is a network protocol analyzer built on the packet capture library
pcap. In addition to capturing network packets as in Tcpdump, Ethereal
provides a user friendly graphical interface, and supports additional ap-
plication layer protocols. Ethereal can also import pre-captured data files
from other network monitoring tools, such as Tcpdump and Sniffer.
In the following experiments, we use Ethereal to analyze a packet trace
captured by Tcpdump, since generally Ethereal does not allow a normal
user to capture packets (see Section A.5).
We start with a simple single segment network, where all eight comput-
ers are connected in one Ethernet segment (see Fig. 1.3). The host IP
37 1.5 Exercises with Linux commands
128.238.66.0 subnet
addresses are given in Table 1.2. Note that the slash-notation is used, where
“128.238.66.100/24” means an IP address of “128.238.66.100” with a sub-
netmask of “255.255.255.0”.
Exercise 1 Login to the system. The login ID is guest, and the login password is guest1. Get
acquainted with the Gnome environment, the Linux commands, text editors, and the
man pages.
Exercise 2 After logging in, open a command window if one is not opened automatically, by
clicking the right mouse-key on the background and choosing the New Terminal
item in the menu.
38 Linux and TCP/IP networking
LAB REPORT What is the default directory when you open a new command window?
What is your working directory?
Exercise 3 Run ps -e to list the processes running in your host. After starting a new process by
running telnet in another command window, execute ps -e again in a third window
to see if there is any change in its output.
Find the process id of the telnet process you started, by:
ps -e | grep telnet.
Then use kill process id of telnet to terminate the telnet process.
LAB REPORT Is the Internet service daemon, xinetd, started in your system? Is inetd
started in your system? Why?
Exercise 4 Display the file /etc/services on your screen, using:
more /etc/services.
Then in another console, use the redirect operator to redirect the more output to
a file using more /etc/services > ser more. Compare the file ser more with the
original more output in the other command window.
Copy /etc/services file to a local file named ser cp in your working directory,
using cp /etc/services ser cp. Compare files ser more and ser cp, using cmp
ser more ser cp. Are these two files identical?
Concatenate these two files using cat ser more ser cp > ser cat.
Display the file sizes using ls -l ser*. Save the output. What are the sizes of files
ser more, ser cp, and ser cat?
39 1.6 Exercises with diagnostic tools
LAB REPORT Submit the ls output you saved in this exercise and answer the above
questions.
Study the different options associated with each command. Throughout this lab you
will use these commands rather extensively.
LAB REPORT Explain the above commands briefly. Two or three sentences per com-
mand would be adequate.
Exercise 6 In this exercise, we will use tcpdump to capture a packet containing the link, IP,
and TCP headers and use ethereal to analyze this packet.
First, run tcpdump -enx -w exe6.out. You will not see any tcpdump output, since
the -w option is used to write the output to the exe6.out file.
Then, you may want to run telnet remote host 6 to generate some TCP traffic.
After you login the remote machine, terminate the telnet session and terminate the
tcpdump program.
Next, you will use ethereal to open the packet trace captured by tcpdump and
analyze the captured packets. To do this, run ethereal -r exe6.out &. The ethereal
Graphical User Interface (GUI) will pop up and the packets captured by tcpdump
will be displayed.
For your report, you need to save any one of the packets that contain the link, IP,
and TCP headers. Carry out the following instructions.
1. Click on a TCP packet from the list of captured packets in the ethereal window.
Then go to the Edit menu and choose Mark Frame.
2. Go to the File menu and choose Print. In the Ethereal:Print dialog that
pops up, check File, Plain Text, Expand all levels, Print detail,
6 We use remote host to denote the IP address of a remote host, i.e., a machine other than the one you
are using.
40 Linux and TCP/IP networking
and Suppress unmarked frames. Then, enter the output text file name, e.g.,
headers.txt, and click the OK button. The marked packet is now dumped into the
text file, with a detailed list of the name and value of every field in all the three
headers.
LAB REPORT Draw the format of the packet you saved, including the link, IP, and
TCP headers (See Figs 0.12, 0.13, and 0.16 in Chapter 0 of this guide), and
identify the value of each field in these headers. Express the values in the
decimal format.
LAB REPORT What is the value of the protocol field in the IP header of the packet
you saved? What is the use of the protocol field?
Exercise 7 In a manner similar to the previous exercise, we will run tcpdump to capture an
ARP request and an ARP reply,7 and then use ethereal to analyze the frames.
Run tcpdump -enx -w exe7.out to capture all the packets on the LAN segment.
If there is no arp requests and replies in the network, generate some using arping
remote machine.
When Solaris 8.0 is used, you can generate an ARP request and an ARP
reply by running telnet to a remote machine. Note this remote machine
should be a different machine from the one you used in Exercise 6.
After you see several ARP replies in the arping output, terminate the arping and the
tcpdump program. Open the tcpdump trace using ethereal -r exe7.out &. Print one
ARP request and one ARP reply using ethereal.
LAB REPORT What is the value of the frame type field in an Ethernet frame car-
rying an ARP request and in an Ethernet frame carrying an ARP reply,
respectively?
What is the value of the frame type field in an Ethernet frame carrying
an IP datagram captured in the previous exercise?
What is the use of the frame type field?
Exercise 8 Using the tcpdump utility, capture any packet on the LAN and see the output format
for different command-line options. Study the various expressions for selecting
which packets to be dumped.
7 We will examine the Address Resolution Protocol (ARP) in the next Chapter. For this exercise, the
purpose is to examine the use of the frame type field in an Ethernet frame.
41 1.7 Exercises on port numbers
For this experiment, use the man page for tcpdump to find out the options and
expressions that can be used.
If there is no traffic on the network, you may generate traffic with some applications
(e.g. telnet, ping, etc.).
LAB REPORT Explain briefly the purposes of the following tcpdump expressions.
tcpdump udp port 520
tcpdump -x -s 120 ip proto 89
tcpdump -x -s 70 host ip addr1 and (ip addr2 or ip addr3)
tcpdump -x -s 70 host ip addr1 and not ip addr2
Exercise 9 Start tcpdump in a command window to capture packets between your machine
and a remote host using:
tcpdump -n -nn host your host and remote host 8 .
Execute a TCP utility, telnet for example, in another command window.
When you see a TCP packet in the tcpdump output, terminate tcpdump and save its
output.
LAB REPORT What are the port numbers used by the remote and the local computer?
Which machine’s port number matches the port number listed for telnet in
the /etc/services file?
Exercise 10 Start tcpdump in one command window using:
tcpdump -n -nn host your host and remote host.
Then, telnet to the remote host from a second command window by typing tel-
net remote host. Again issue the same telnet remote host command from a third
command window. Now you are opening two telnet sessions to the same remote
host simultaneously, from two different command windows.
Check the port numbers being used on both sides of the two connections from the
output in the tcpdump window. Save a TCP packet from each of the connections.
LAB REPORT When you have two telnet sessions with your machine, what port number
is used on the remote machine?
Are both sessions connected to the same port number on the remote ma-
chine?
8 For some older versions of tcpdump, the -n -nn options is combined into one single -n option.
42 Linux and TCP/IP networking
What port numbers are used in your machine for the first and second telnet,
respectively?
LAB REPORT What is the range of Internet-wide well-known port numbers? What
is the range of well-known port numbers for Unix/Linux specific service?
What is the range for a client port number? Compare your answer to the
well-known port numbers defined in the /etc/services file. Are they
consistent?
LAB REPORT Explain briefly what a socket is.
2 A single segment network
Metcalfe’s Law: “The value of a network grows as the square of the number of its
users.” Robert Metcalfe
2.1 Objectives
!
!
Network interfaces and interface configuration.
!
Network load and statistics.
!
The Address Resolution Protocol and its operations.
!
ICMP messages and Ping.
!
Concept of subnetting.
Duplicate IP addresses and incorrect subnet masks.
43
44 A single segment network
0021 IP Datagram
or other network layer protocol data, over a serial link. Currently, most
dial-up Internet access services are provided using PPP.
PPP consists of two types of protocols. The Link Control Protocol (LCP)
of PPP is responsible for establishing, configuring, and negotiating the data-
link connection, while for each network layer protocol supported by PPP,
there is a Network Control Protocol (NCP). For example, the IP Control
Protocol (IPCP) is used for transmitting IP datagrams over a PPP link.
Once the link is successfully established, the network layer data, i.e., IP
datagrams, are encapsulate in PPP frames and transmitted over the serial
link.
The PPP frame format is shown in Fig. 2.1. The two Flag fields mark
the beginning and end points of a PPP frame. The Protocol field is used
to multiplex different protocol data in the same PPP frame format. Since
there are only two end hosts in a PPP LAN, neither an addressing scheme
nor medium access control are needed.
send, it first senses the channel to see if there is any transmission going on.
If the channel is busy, the host will wait until the channel becomes idle.
Otherwise, the host begins transmission if the channel is idle. Assume the
maximum end-to-end propagation delay is a seconds. After the first bit is
transmitted, the host keeps on sensing the channel for 2a seconds. If there
is no collision detected during this period, the entire frame is assumed to
be transmitted successfully. This is because it takes at most a seconds for
all the hosts to hear this transmission, and another a seconds to hear any
possible collision with another transmission. When a collision is detected,
all hosts involved in the collision stop transmitting data and start to backoff,
i.e., wait a random amount of time before attempting to transmit again. The
random time is determined by the exponential backoff algorithm given in
Table 2.1.
In addition to attaching all hosts to a common cable or a hub, an Ethernet
LAN can be built using Ethernet switches with a star topology. Ethernet
switches, also called switched hubs, are MAC layer devices that switch
frames between different ports. An Ethernet switch offers guaranteed band-
width for the LAN segments connected to each port and separates a LAN
into collision domains. If each Ethernet switch port is connected to a single
host only, CSMA/CD operation is not required. However, in order for the
switch to deal with traffic congestion, the switch may generates a false
collision signal (backpressure) to make the transmitting host back off.
(a) (b)
Figure 2.2. Different operation modes of IEEE 802.11 WLANs. (a) The infrastructure
mode. (b) The ad-hoc mode.
An IEEE 802.11 WLAN can be configured to work in two modes: the in-
frastructure mode and the ad-hoc mode. In the infrastructure mode shown
in Fig. 2.2(a), fixed access points are used. These access points are con-
nected to the wireline network. Each access point communicates with hosts
within its transmission range and serves as a gateway for the hosts. When an
active mobile host moves from one access point to another, handoff tech-
niques can be applied to switch the connection from the original access
point to the new access point without an interruption. In addition, multiple
access points can be configured to work together to provide extended cov-
erage. In the ad hoc mode shown in Fig. 2.2(b), there is no need for access
points. Host computers can communicate with each other as long as they
are in each other’s transmission range.
In WLANs, CSMA/CD is inadequate because collision detection cannot
be performed effectively in a wireless channel. Rather, CSMA/CA is used
for medium access control. In CSMA/CA, a host first senses the medium
when it has a frame to send. If the medium remains free for a certain period
of time (called the Distributed Coordination Function (DCF) Inter-Frame
Space (DIFS)), the host begins transmitting data. When the transmission
is over, it waits for an acknowledgement from the receiving host. If no ac-
knowledgement received, it assumes that a collision occurred and prepares
to retransmit. On the other hand, if the medium is busy, the host waits for
the end of the current frame transmission plus a DIFS, and then begins
a backoff procedure like in the case of CSMA/CD protocol. Backoff is
performed as follows. The host first chooses a random number within a
certain range as a backoff time, and then listens to the wireless channel to
determine if it is free or busy. The backoff time is decremented by one if
the medium is free in a time slot. However, the host stops decrementing the
backoff time if the medium is busy during a time slot, and resumes decre-
menting it only when the medium becomes free again. When the backoff
time becomes 0 and the channel is idle, the host attemps a transmission.
47 2.2 Local area networks
(a) (b)
Collision
Host B Host B
R: transmission R: transmission
range range
Host A Host A
Figure 2.3. The hidden terminal and exposed terminal problems of IEEE 802.11
WLANs. (a) The hidden terminal problem. (b) The exposed terminal problem.
2 2 1 1 2 6 4 6 4 bytes
corresponding MAC address found in the cache is used and no ARP request
and reply will be sent.
Figure 2.4 shows the format of an ARP message, which is 28 bytes long.
An ARP request or reply is encapsulated in an Ethernet frame, with the
Protocol Type field set to 0x0806. An 18-byte padding is needed since
the minimum length of an Ethernet frame is 64 bytes.
In Fig. 2.4, the first four fields define the types of the addresses to
be resolved. Hardware Type specifies the type of physical address used,
and Protocol Type specifies the type of the network protocol address.
The next two fields give the length of these two types of addresses. The
Operation field specifies whether it is an ARP request (with a value of 1),
ARP reply (2), RARP request (3), or RARP reply (4). The following four
fields are the MAC and IP addresses of the sender and the targeted receiver,
respectively.
PPP networks do not use ARP. In this case, hosts must know the IP
address at the end of the PPP link. Usually DHCP is used over a PPP link
where the IP address of one end host is assigned automatically by the other
end host.
Subnet 1 Subnet 2
Proxy-ARP
enabled
(1): Host_A broadcasts an ARP request for Host_B (4): Host_A inserts a new entry in its ARP cache:
(2): Router Port 0 replies for Host_B {(Host_B’s IP) at (Router Port 0’s MAC)}
(3): Host_A sends the frame to Router Port 0 (5): Router forwards the frame to port 1
(6): Router port 1 sends the frame to Host_B
IP Output IP Input
Yes No
MAC known? No
loopback Yes
driver
multiplex ARP demultiplex
Ethernet frame ARP packet Ethernet frame
Ethernet
datagram that can be encapsulated in a link layer frame, which is called the
maximum transmission unit (MTU). Examples of MTUs are: 1500 bytes
for Ethernet and 4352 bytes for FDDI. If an IP datagram to be sent is
longer than the MTU of the interface, the IP datagram will be fragmented
and carried in several data link layer frames. We will further discuss MTU
and IP fragmentation in Chapter 5.
! netstat -a: Shows the state of all sockets, routing table entries, and inter-
will be used frequently in the following experiments.
1 It is recommended that the interface be disabled first, before changing its settings.
2 Different systems may give different names for the interfaces, e.g., le0 for Sun Sparc 4 with SunOS
5.5.1 and hme0 for Sun Ultra 5 with Solaris 8. You can find the name by typing netstat -i or ifconfig
-a.
53 2.4 The Internet Control Message Protocol
0 78 15 16 31
type(3) code(0–15) checksum
unused (must be 0)
0 78 15 16 31
optional data
Sock is a test program that can be run either as a client or as a server, using
UDP or TCP. It also provides a means to set various socket options. Sock
operates in one of the following four modes [5].
1. Interactive client: connects to a server, and copies the standard input,
i.e., keys a user typed, to the server and copies everything received from
the server to the standard output, i.e., the screen.
2. Interactive server: waits for a connection request from a Sock client,
and then copies the standard input to the client and copies everything
received from the client to the standard output.
3. Source client: sends packets to a specified server.
4. Sink server: receives packets from a client and discards the received
data.
LAB REPORT How many interfaces does the host have? List all the interfaces found,
give their names, and explain their functions briefly.
LAB REPORT What are the MTUs of the interfaces on your host?
LAB REPORT Is network subnetted? What is the reasoning for your answer? What the
experimental are the reasons for subnetting?
55 2.7 ARP exercises
Exercise 2 While tcpdump host your host is running in one command window, run ping
127.0.0.1 from another command window.
LAB REPORT From the ping output, is the 127.0.0.1 interface on? Can you see any
ICMP message sent from your host in the tcpdump output? Why?
Exercise 3 By using netstat -in command, collect the statistics from all the hosts on the
network. Since we use the same login name and password, we can telnet to other
workstations and run netstat -in there.3
Save the netstat -in outputs.
If you don’t see a significant amount of output packets in the netstat output, the
machine was probably restarted recently. You may do this experiment later, or use
the following sock command to generate some network traffic:
sock -u -i -n200 remote host echo.
LAB REPORT Calculate the average collision rate over all the hosts for the set of
statistics you collected in this exercise.
In the following experiment, we shall examine the host ARP table and the
ARP operation, including two interesting cases: proxy ARP and gratuitous
ARP. You may need to ask the lab instructor for the MAC addresses of the
host and router interfaces, and record these MAC addresses in Table A.1
and Table A.2 in the appendix. You need these MAC addresses for the
exercises and lab report.
Exercise 4 Use arp -a to see the entire ARP table. Observe that all the IP addresses displayed
are on the same subnet.
If you find that all the remote hosts are in your host’s ARP table, you need to delete
a remote host (not your workstation) from the table, using,
arp -d remote host.4
Save the ARP table for your lab report.
While tcpdump -enx -w exe2.out is running, ping a remote host that has no entry
in your host ARP table. Then terminate the tcpdump program.
3 After you are done with a remote host, you should exit the telnet session before you telnet to
another remote host. Recursive telnet will generate unnecessary data in the tcpdump output and
cause confusion.
4 If you deleted your workstation’s IP address from the ARP table by mistake, you must add the entry
back in the table. See the arp manual page to add. Note that, in order for your workstation to reply
to the ARP requests, the ARP entry of your workstation must have the P flag in the ARP table.
56 A single segment network
LAB REPORT From the saved tcpdump output, explain how ARP operates. Draw the
format of a captured, ARP request and reply including each field and the
value.
! At the MAC layer, what is the destination Ethernet address of the frame
Exercise 5 While tcpdump host your host is running to capture traffic from your machine,
execute telnet 128.238.66.200. Note there is no host with this IP address in the
current configuration of the lab network.
Save the tcpdump output of the first few packets for the lab report.
After getting the necessary output, terminate the telnet session.
LAB REPORT From the saved tcpdump output, describe how the ARP timeout and
retransmission were performed. How many attemps were made to resolve
a non-existing IP address?
Exercise 6 The network topology for this proxy ARP exercise is shown in Fig. 2.9. We will
divide the group into two subnets interconnected by a router. The IP addresses
and network masks for the hosts are also given in Fig. 2.9. Change the IP address and
network mask of your host accordingly (see Section 2.3.2). The IP addresses and
network masks of the Router4 interfaces are the same as their default settings.
Note that the network mask of the hosts in the 128.238.65.0 network is 255.255.0.0.
Next we will enable the proxy ARP function on the ethernet1 interface of Router4.
1. telnet to Router4 from shakti: telnet 128.238.64.4. The login password is
el537.5
5 Check with your lab instructor for the password of the router your are using, which may be different
from el537.
57 2.7 ARP exercises
128.238.64.0 subnet
ether0 64.4/24
Router 4
2. Log in to the router, type enable to enter the Privileged EXEC mode.6 The password
is again el537.
3. Enter the Global Configuration mode by typing config term.
4. Then type the following lines:
interface ethernet 17
ip proxy-arp
Ctrl-Z
5. Type exit to terminate the telnet session.
Now Router4’s ethernet1 interface can perform proxy ARP for the hosts in the
128.238.64.0 subnet.
Run tcpdump -enx on all the hosts.
Then let the hosts in the 128.238.65.0 subnet send UDP datagrams to the hosts in
the 128.238.64.0 subnet. For example, on guchi type:
sock -i -u -n1 -w1000 Host in 64.0 subnet echo.
When you are done with all the hosts in the 128.238.64.0 subnet, save the tcpdump
output for the lab report.
Run arp -a to display the new ARP table in your host. Save the ARP table for your
lab report.
After the lab instructor restores the network into a single subnet (see Fig. 1.3),
change the IP address and network mask of your host’s interface back to their
default values as in Fig. 1.3.
Exchange your data saved in this exercise with a student working in the other
subnet.
Exercise 7 This exercise will be performed by all the students together. While tcpdump -ex
-w exe7.out is running on all the hosts, reboot host guchi.
After guchi is started, terminate tcpdump and run ethereal -r exe7.out & to load
the tcpdump trace. Print the the gratuitous ARP request for your lab report.
LAB REPORT List the sender IP address, target IP address, sender MAC address, and
target MAC address of the gratuitous ARP you saved.
Exercise 8 Use ping -sv remote host to test whether the remote host is reachable, while
running: tcpdump -enx host your host and remote host.
Save the tcpdump and ping output for the future study on ping.
Exercise 9 While running tcpdump -x -s 70 host your host and remote host,
execute the following sock command to send a UDP datagram to the remote host:
sock -i -u -n1 -w1000 remote host 88888.
Save the tcpdump output for the lab report.
LAB REPORT Study the saved ICMP port unreachable error message (see Fig. 2.7).
Why are the first 8 bytes of the original IP datagram payload included in
the ICMP message?
Exercise 10 While tcpdump is running to capture the ICMP messages, ping a host with IP
address 128.238.60.100. Save the ping output.
59 2.9 Exercises with IP address and subnet mask
LAB REPORT Can you see any traffic sent on the network? Why? Explain what hap-
pened from the ping output.
LAB REPORT List the different ICMP messages you captured in Exercises 8, 9, and
10 (if any). Give the values of the type and code fields.
In this section, we will observe what happens when the same IP address is
assigned to two different hosts. We will also set an incorrect subnet mask
for hosts and see what are the consequences. For the next two exercises,
we split the current single segment network into two segments, Group A
and Group B as shown in Table 2.3, so that they will not interfere with each
other.
LAB REPORT Explain what happened in the first case and why. Answer the questions
for the second and third cases.
Exercise 12 Change the host IP addresses and the subnet masks as shown in Table 2.4.
Since we still have two separate segments, Groups A and B can do the exercise
independently. Note that two hosts in each group (shakti and apah in Group A,
or yachi and guchi in Group B) are assigned an incorrect subnet mask.
Capture the packets with tcpdump -e for the following cases.
1. When shakti (yachi) pings one of the hosts that have the correct subnet mask.
2. When apah (guchi) pings one of the hosts that have the correct subnet mask.
Now, copy the output displayed from the ping window in apah (guchi). Share
the saved output message with other students.
3. When a host with the correct subnet mask pings shakti (yachi).
4. When a host with the correct subnet mask pings apah (guchi).
To avoid confusion, only one machine in each group should generate traffic in each
case. Clearly, this exercise has to be performed as a team.
LAB REPORT Explain what happened in each case according to the tcpdump outputs
saved. Explain why apah (or guchi in Group B) could not be reached from
other hosts, whereas shakti (or yachi in Group B), which has the same
incorrect subnet mask, could communicate with the other hosts.
3 Bridges, LANs and the Cisco IOS
Algorhyme
I think that I shall never see
A graph more lovely than a tree.
A tree whose crucial property
Is loop-free connectivity.
A tree that must be sure to span
So packets can reach every LAN.
First, the root must be selected.
By ID, it is elected.
Least-cost paths from root are traced.
In the tree, these paths are placed.
A mesh is made by folks like me,
Then bridges find a spanning tree. Radia Perlman
3.1 Objectives
!
!
The Cisco Internet Operating System software.
!
Configuring a Cisco router.
!
Transparent bridge configuration and operation.
The spanning tree algorithm.
Figure 3.1. The bridge learns the source address from an incoming frame.
LAN A
1 1
Bridge2 Bridge1
2 2
Host1 to HostX
LAN B
Figure 3.2. When there is a loop in the bridged network, the address learning scheme will
not work.
found, the bridge forwards this frame to the network segment indicated by
the entry. Otherwise, flooding is used where the received frame is copied
to all the active ports except the incoming port.
Bridge1 Bridge1
1 2 1 2
LAN A LAN A LAN B
LAN B
1
1 1
Bridge2 1 2
Bridge2 Bridge3
2 2 Bridge3 X
2 3
3
LAN C LAN D
LAN C
LAN D 1
Bridge4
2
1
2 LAN E
LAN E Bridge4
Figure 3.3. An example bridged network with a loop and the corresponding tree with the
loop removed.
broadcast storm. A severe broadcast storm can block other network traffic,
resulting in a network meltdown.
The solution to this problem is to remove loops in bridged networks. A
bridged network can be viewed as a graph, where the bridges are nodes and
the network segments are edges. A tree is a graph with no loops. If we can
build a tree from this graph by disabling some of the bridge ports, loops
will be removed. This is shown in Fig. 3.3, where the loop in the network
is removed by disabling port 2 of Bridge3. It can be seen that from any
host in the tree network to any other host, there is only a single path. The
problem discussed in the previous example is solved.
The spanning tree algorithm defined in the IEEE 802.1d standard is used
in bridged networks to build trees dynamically. It works as follows.
1. Each bridge is assigned a unique identifier, and each port of a bridge is
assigned an identifier unique to that bridge. Typically, the identifier of
a bridge is a priority concatenated with one of the bridge ports’ MAC
address, and the identifier of a port is a priority concatenated with a port
index local to the bridge. Each bridge port has a corresponding path
cost, which indicates the cost to transfer a frame to an attached network
segment through that port.
2. Select the root bridge, which is the one with the lowest-value bridge
identifier. The ID of the root is called the root ID.
3. Each bridge selects its root port. The root port of a bridge is the port
from which the root bridge can be reached with the least aggregate path
cost (called the root path cost).
65 3.2 Ethernet bridges
2 1 1 1 8 4 8 2 2 2 2 2
4. Determine the designated bridges and the designated ports. Each net-
work segment is associated with a designated bridge, which provides the
shortest path to the root bridge and is the only bridge allowed to forward
frames to and from the root. The port connecting a designated bridge to
the network segment is a designated port. If more than one bridge pro-
vides the same root path cost, the bridge with the lowest-valued bridge
identifier is selected as the designated bridge.
5. Only the root ports and designated ports of the bridges are allowed to
forward frames. All other bridge ports are blocked.
6. The above steps are repeated whenever the network topology changes.
In the tree shown in Fig. 3.3, Bridge1 is the root bridge since it has the
smallest bridge identifier. Bridge4’s root port is port 1, with a root path
cost of 2 hops. LAN D’s designated bridge is Bridge3, and its designated
port is Bridge3’s port 3.
To implement the spanning tree algorithm in a distributed manner,
bridges exchange configuration information using a message called bridge
protocol data units (BPDUs). The format of a BPDU message is given in
! Flags: The least significant bit, called the Topology Change (TC) bit, is
fields are always set to 0.
! Root ID: Identifies the root bridge by listing its 2-byte priority followed
used.
by a 6-byte Ethernet address. The priority value can be set in the Global
Network Applications
Cisco IOS
Network Platform
Figure 3.5. Cisco IOS enables network applications on the network platforms.
! Port ID: Each bridge port has a unique 2-byte identifier. The first byte
is the priority, which is configurable, while the second byte is a number
! Message Age:1 Specifies the amount of time since the root originally
assigned to the port.
lated if a bridge does not hear BPDUs from the root bridge. The default
! Hello Time:1 Provides the time period between two BPDUs from the
value is 15 seconds.
! Forward Delay:1 provides the amount of time that bridges should wait
root bridge. The default value is 1 second.
1 in 1/256ths of a second.
67 3.3 Configuring a bridge or router
In our lab, the Cisco IOS software is running in the four routers. In the
following exercises, we will learn how to use the Cisco IOS to configure a
bridge or a router. More specifically, we will configure the interfaces, enable
or disable different functions, choose what protocol (e.g., the spanning
tree algorithm, RIP or OSPF) to use, and display the state of the bridge/
router.
login
mode : User EXEC
prompt : Router> logout
reload , then
mode : Privileged EXEC press Ctrl–C mode : ROM Monitor
prompt : Router# during the first prompt : > or boot> or rommon>
60 seconds of
system start up
configure terminal end or Ctrl–Z
In the following experiments, we will use commands in the first four con-
figuration modes. Figure 3.6 further illustrates configuration modes, their
prompts, and commands used to navigate through them.
To get help, typing ? displays all the commands available in the mode
you are in. Typing ? after a partial command string lists commands in the
current mode that begin with that string. Typing ? after a full command
lists the available syntax for that command.
IP address doesn’t match the subnet of a router, you first need to set your
workstation IP address to match the subnet of the router that you want to
configure. Then you can telnet to the router interface and change the IP
address of each interface as required. If you change the router interface
to another subnet, the telnet session will be frozen since now the router
interface is in a different subnet from your host. In this case, kill the window
and change the IP address of your workstation again to match that of the
router interface. Again, telnet to the new IP address of the router interface
(which you just set), and then do the remaining configuration.2
The following is an example of router configuration from a remote host.
1. Connect the host and a router interface using a hub. Also change the
host’s IP and/or netmask to match the subnet of the router interface if
necessary.
2. Telnet to the router interface, enter the virtual terminal password, which
is el537. Now you are in the User EXEC mode with prompt:
Router>
3. You may enter the Privileged EXEC mode by typing:
Router> enable
After entering the enable password (el537), you will see the Privileged
EXEC prompt:
Router#
You may type write terminal to display the current configuration in the
Privileged EXEC mode.
4. To begin a new configuration, use the following command in the Privi-
leged EXEC prompt:
Router# configure terminal
Then the router displays an explanation of the editing functions. Now
you are in the Global Configuration mode.
In this mode, you can make various configurations, e.g., assigning IP
addresses to the interfaces, specifying which protocols to run, etc. Since
it is impossible to describe all the configuration commands here, we will
introduce configuration commands whenever they are needed.
5. To end the configuration mode, type Ctrl-z. Then, you will get back to
the Privileged EXEC mode. You can examine the new configuration by
typing write terminal again.
2 By defining a virtual interface called loopback, we can change the IP address of any router interface
without an interrupt of the telnet session. However, for the sake of experiments, we do not introduce
the loopback feature in this lab.
70 Bridges, LANs and the Cisco IOS
6. Enter the disable command to return to the User EXEC mode. Type exit
to end the connection to the router.
Here, we intentionally omit the command for saving the configuration
changes to NVRAM (Nonvolatile RAM). For more information about the
configuration commands, see [6] and [7].
no ip routing
interface ethernet 0
ip address 128.238.61.1 255.255.255.0
bridge-group 1
interface ethernet 1
ip address 128.238.61.2 255.255.255.0
bridge-group 1
bridge 1 protocol ieee
The students in the lab should divide themselves into four groups for the
first four exercises. Each group uses two workstations, a bridge, and two
hubs, which are required to be connected as shown in Fig. 3.7, Table 3.2
and Table 3.3.
eth0 eth1
HOST A HOST B
eth0 eth1
BRIDGE
HOST_A HOST_B
After running tcpdump -enx on both workstations, turn on the router. Capture the
gratuitous ARP sent by the router.
Change the IP address of your workstation to be in the same subnet as the router.
You can choose any valid host id for your host.
ping the router interface to test the connection to the router.
LAB REPORT Submit the gratuitous ARP sent by the router. What is the default IP
address of the router interface?
Exercise 2 Telnet to your router. When prompted for a login password, type el537. You
should now be in the User EXEC mode.
Type help to learn how to use the online help.
73 3.5 A simple bridge experiment
Study Fig. 3.6. Navigate through the User EXEC, Privileged EXEC, Global Configu-
ration, and Interface Configuration modes. In each mode, type ? to display a list of
available commands and study these commands.
Type show version in the User EXEC mode to display the Cisco IOS banner. Identify
which Cisco IOS Release is running in the router. Save the Cisco IOS banner for
your lab report.
LAB REPORT Submit the Cisco IOS banner you saved. Identify the release of the
Cisco IOS software in the router.
Figure 3.7 shows a simple case of the use of bridges, which consists of
two network segments connected by a bridge. With this simple topology,
we can easily capture initial BPDUs before each bridge is engaged in the
spanning tree calculation.
Configure transparent bridging as in Fig. 3.7, Table 3.2 and Table 3.3.
Note that the default configuration of the hosts and the bridges are differ-
ent from those in the tables. You need to change the IP addresses of the
bridge interfaces,3 as well as set the bridge group and enable the spanning
tree algorithm (see the previouse section on bridge configuration). Do the
following experiments.
Exercise 3 Configure the IP addresses of your workstation and the bridge interfaces as shown
in Fig. 3.7, Table 3.2 and Table 3.3. To avoid confusion, each bridge should be
configured by only one person.
Run tcpdump -en ip proto 1 on your machine, and your partner’s machine.
Send ping messages to your partner’s machine: ping -sv remote machine.
After receiving the tenth echo reply, quit the ping process, and save the tcpdump
outputs from both machines.
During this exercise, don’t run ping programs at the same time. For clean results,
do your experiments in turn.
LAB REPORT What are the IP and MAC addresses of a packet that went from your
machine to the bridge? What are the IP and MAC addresses of a packet
that went from the router to your partner’s machine?
3 As soon as you change the IP address of the bridge interface your host is connected to, the telnet
connection will be lost. You need to again change the IP address of your workstation to be in the
same subnet as the bridge interface. See Section 3.3.3.
74 Bridges, LANs and the Cisco IOS
Answer the same questions, but for the echo reply that was returned from
your partner’s machine.
LAB REPORT Using the tcpdump outputs from both machines, calculate the average
delay that a packet experienced in the bridge. Note that the system times
of the two machines might be different. Show all the steps and submit the
tcpdump outputs with your report.
LAB REPORT How frequently (in seconds) does a bridge sends its BPDUs?
vayu shakti
61.101/24 61.100/24
128.238.61.0 subnet
61.104/24 61.105/24
yachi fenchi
LAB REPORT Submit the eight different BPDUs you saved. Identify the values of root
ID, root path cost, bridge ID, and port ID for each BPDU4 .
In this section, we will use Fig. 3.8 as our network topology. You need
to change the IP addresses of the bridge interfaces, as well as that of your
workstation. Refer to Section 3.3.4 on how to configure a transparent bridge.
Also see Section 3.3.3 on how to handle a frozen telnet session after you
change the bridge IP address.
Upon being started, a transparent bridge learns the network topology by
analyzing source addresses of incoming frames from all attached networks.
The next exercise shows the process by which a transparent bridge builds
its filtering database.
Exercise 5 After configuring the network in Fig. 3.8, login to the bridge.
Get to the Privileged EXEC mode. Type show bridge to see the entries in the bridge
forwarding database.
Whenever you ping or telnet from your workstation to a host that is not in the table,
observe how the filtering database in the bridge is expanded.
You may use the clear bridge group command to remove any learned entries from
the filtering database, if you see a full filtering database or if you want to repeat the
above exercise.
LAB REPORT From the output of show bridge, identify which bridge ports are blocked,
and which ports are in the forwarding state for each bridge.
Exercise 6 Using tcpdump -ex ether multicast, capture the BPDU packet flowing on your
network segment.
Telnet to the hosts in the other three LAN segments and execute the above tcpdump
command in the telnet window to collect BPDUs sent there.
Login to each bridge to collect the show bridge outputs.
LAB REPORT Submit the four different BPDUs you saved. Identify the values of root
ID, root path cost, bridge ID, and port ID for each BPDU.
LAB REPORT Based upon the initial BPDUs saved in Exercise 4, draw the spanning
tree seen by the BPDUs. Identify the root ports and the root path cost (in hop
4 You may ask the lab instructor for the physical addresses of network interfaces, and record them in
Table A.1 and Table A.2. You need the MAC addresses to help analyze the BPDUs.
76 Bridges, LANs and the Cisco IOS
counts) for each bridge. Identify the designated bridge and the designated
port for each LAN segment. Identify the state of each bridge port (blocking
or forwarding).
Don’t just assume that Bridge1 has the highest priority for the root bridge.
Draw the spanning tree based upon your data (eight initial BPDUs).
Write the final BPDUs you collected using the three-tuple format: {root
ID, root path cost, bridge ID}.
Once you have the spanning tree, justify it using the four final BPDUs
collected in this exercise and/or the output of the show bridge command.
Exercise 7 This exercise is performed by all the students together. First, send ping messages
from apah to yachi, while tcpdump is running. Let the two programs run during
this exercise.
Then, disconnect the cable from the ethernet0 port of Bridge2 from the hub,
and type the time command on apah or yachi to get the current time.
Observe the ping and tcpdump windows. When the connection is reestablished,
type the time command again. How long does it take the spanning tree algorithm to
react to the change in the topology?
Once you can successfully reach other hosts, get to the bridges to run show bridge
to collect the port states. Also collect BPDUs from all the LAN segments as you did
in the previous exercise.
After every student has collected the required data, connect the cable to the original
position. Again, measure the time it takes for the bridges to adapt to the new change.
LAB REPORT Draw the new tree formed after the cable was disconnected, based on
the BPDUs you collected in this exercise. Specify the state of each bridge
port.
Exercise 8 You can also configure a router using the web browser UI. To enable the web server,
login to the router and execute ip http server in the Global Configuration mode.
Next, start a web browser (e.g., Mozilla in Linux, or Hotjava in Solaris) in your
host, and enter the IP address of the router interface. When prompted, enter el537
for password, and leave the User Name field blank. Then you can browse the router
configuration web pages and configure the router there.
4 Static and dynamic routing
4.1 Objectives
!
!
Comparison of router and bridge.
!
IP forwarding.
!
Use of ICMP messages in routing.
!
The Routing Information Protocol (RIP).
!
The Open Shortest Path First (OSPF) protocol.
Static routing by manually building the routing tables in the routers and
address. A host address has a nonzero host ID, while a network address
! Flags. There are five flags which can be used for a given route.
! U. The route is up.
! G. The route is to a router (gateway).
! H. The route is to a host.
! D. The route was created by a redirect (see Section 4.2.3).
! M. The route was modified by a redirect.
! The host’s network interface that the datagram should be delivered to,
e.g., the host’s Ethernet interface eth0.
When a router receives a datagram, it extracts the destination IP address
and computes the network prefix. Then the forwarding decision is made
according to the result of routing table lookup, as follows.
1. If the network prefix matches any directly connected network address,
the datagram is delivered directly to the destination over that network.
2. Else if the table contains a host-specific route for that address, the data-
gram is sent to the next hop router specified in that table.
3. Else if the table contains a network-specific route for the destination
host’s subnet, the router forwards the datagram to the router of that
network.
79 4.2 Static and dynamic routing
4. Else if there is a default router entry in the routing table, the datagram
is sent to the default router.
5. If not even a default router is found, a routing error is generated and the
datagram is dropped.
As shown above, host entries have priority over network entries, which
have priority over default entries. This sequence of lookups is called the
longest-prefix-matching rule and is commonly used in routing table lookup.
Table 4.1 gives an example routing table from a Linux machine, where
the first entry is for the host’s own subnet, the second entry is for the
loopback interface, and the third entry is the default route with a default
router 128.238.42.1 and a G flag. Both the first and the third entry use the
local Ethernet interface eth0, while the loopback entry uses the loopback
interface lo. When the host has a packet to sent to a destination in the
128.238.4.0 subnet, both the first and the third entry match the destination
address. However, due to the longest-prefix-matching rule, the first route is
used. If the host has a packet to a destination of 128.238.66.100, the default
route will be used.
Considering the fact that table lookup is performed for each IP datagram
in each router along its path, and the tremendous volume of IP datagrams
in today’s Internet, a smaller routing table, which shortens the lookup time,
is always preferred. Most routing tables do not contain host-specific entries
but only network-specific entries, which keeps the table small. For hosts
that can access only one router, using a default route for all the networks
that are not directly connected is more efficient.
0 78 15 16 31
type(5) code(0-3) checksum
correct gateway IP address
looks up the routing table and decides that Router B is the next-hop router.
However, it detects that the datagram is being sent out on the same interface
it was received on. Then, Router A sends an ICMP redirect message to
Host X, saying that subsequent datagrams to Host Y should be routed to
Router B. After receiving the ICMP redirect message, Host X inserts a
more efficient routing entry for Host Y using Router B as the next-hop
router, with a D flag.
ICMP redirect is enabled by default in the routers in our lab. To enable this
feature if it is disabled, use the following command in the router Interface
Configuration mode:
Router(config-if)# ip redirects.
0 78 15 16 31
type(9) code(0) checksum
no. of addr. addr. length(2) lifetime
router address [1]
preference level [1]
router address [2]
preference level [2]
......
0 7 8 15 16 31
command(1-6) version(1) set to zero
address family (2) set to zero
4-byte IP address
set to zero 20 bytes
set to zero
metric (1-16)
0 7 8 15 16 31
command(1-6) version(2) routing domain
address family (2) route tag
4-byte IP address
4-byte subnet mask 20 bytes
4-byte next-hop IP address
metric (1-16)
4. The route-flush timer. Amount of time that must pass before the route
is removed from the routing table. The interval should be longer than
the larger of the invalid and hold-down values. The default value is 240
seconds.
RIP messages are encapsulated in UDP datagrams, using the well-known
port number 520. Figure 4.4 shows the format of a RIP message, and Fig. 4.5
shows the format of a RIP-2 message. The fields of a RIP message are listed
! Metric: Indicates how many hops have been traversed from the source
to the destination.
85 4.2 Static and dynamic routing
LAN A LAN B
Router A Router B
The RIP-2 message takes advantage of the unused fields in RIP, and
provides additional information such as subnet support and a simple au-
! Routing Domain: The identifier of the routing daemon that sends this
thentication scheme. These fields are listed here.
! Subnet Mask: The subnet mask associated with the IP address adver-
AS Boundary Router
Backbone
Area
Border Backbone
Router Router
Area 1
Area 3
Area 2
Internal Routers
Figure 4.7. An AS with a backbone and three areas.
0 7 8 15 16 31
version type (1-5) packet length
router ID
area ID
checksum authentication type
authentication
authentication
be adjacent when their link state databases are synchronized. Each router
periodically sends LSAs to provide information on the link states, so that
failed routers can be detected quickly. By using the information in LSAs,
a router builds a topological database containing an overall picture of the
area, and calculates a shortest-path tree with itself as root, which then yields
a routing table.
Rather than using TCP or UDP, OSPF uses IP directly. In the IP header,
OSPF has its own value for the protocol field (89, see Fig. 0.7). Each
OSPF packet has a 24-byte header, as shown in Fig. 4.8. The fields in an
OSPF header. The maximum length is 216 − 1 = 65535 bytes since this
gateway addr ess] [metric M] [netmask mask] dev inter f ace name:
! route add [net] dest addr gateway addr metric: Inserts a new route
In Solaris 8.0, the route commands are:
! route delete [net] dest addr gateway addr : Deletes an existing route
to the routing table.
entry.
ates a route to the destination subnet with IP prefix prefix and subnet mask
mask, via next hop. The admin distance argument is optional. If you want
a static route to be overridden by dynamic routing information, specify
admin distance greater than the default administrative distance of the
routing protocol. As an example, a RIP-derived route has the default
4.4 Traceroute
Router1 Router2
Source Destination
(1) ICMP Time Exceeded
the datagram decrements the TTL, discards the datagram, and returns an
ICMP time exceeded message to the sender. The datagram carrying this
ICMP message also contains the router’s IP address as the source address.
Thus the first router in the path is identified. Next, Traceroute sends a
datagram with a TTL of 2, and the address of the second router is identified
in a similar way. This continues until the destination host is reached. The
destination host will not discard the datagram even though the TTL field is
1 (because the packet has reached its destination). To find out whether the
destination host is reached, Traceroute chooses a large UDP destination
port number (greater than 30,000), which is unlikely to be in use by any
process at the destination host. Then the destination will return an ICMP
port unreachable message to the source. In summary, the ICMP time
exceeded messages identify the intermediate routers, and the ICMP port
unreachable message identifies the end host.
As in the previous lab, we will divide the students into four groups, each
with two workstations, a router, and two hubs, which are to be connected
as shown in Fig. 4.10. The IP addresses of the routers and hosts are given
in Table 4.2 and Table 4.3, respectively.
Exercise 1 Configure the IP addresses of your workstations and the router as shown in
Fig. 4.10, Table 4.2 and Table 4.3.
Initially your host’s routing table has no entry for the subnet on the other side of
the router. In order to be connected, you need to add a routing entry for the other
subnet in the routing table of your workstation (see section 4.3.1).
92 Static and dynamic routing
eth0 eth1
HOST A HOST B
eth0 eth1
ROUTER
HOST_A HOST_B
Run tcpdump -en on your machine, and tcpdump -en on your partner’s machine in
the other subnet simultaneously:
tcpdump -en host remote host and your machine.
Send ping messages continuously to your partner’s machine:
ping -sv remote host.
After receiving the tenth echo reply, quit ping and save the tcpdump outputs from
both machines. Also, copy the ping output.
During this exercise, don’t run the ping program at the same time. For clean results,
do your experiments in turn.
LAB REPORT When a packet was sent to a workstation in the other subnet, explain
how the source and destination Ethernet addresses were changed.
What are the source and destination addresses in the IP and Ethernet headers
of a packet that went from your machine to the router?
93 4.6 RIP exercises
What are the source and destination addresses in the IP and Ethernet headers
of a packet that went from the router to your partner’s machine?
Answer the above two questions, but now for the echo reply that was
returned from your partner’s machine.
LAB REPORT Use the tcpdump outputs from both machines to calculate the average
delay that a packet experienced in the router. Note that the system times
of the two machines might be different. Show all the steps and submit the
tcpdump outputs with your report.
Compare this value with the previous value in the case of the bridge. Which,
a router or a bridge, is faster? Why?
In this section, we will examine the operation of RIP. To enable the RIP
routing process in a router, use the following commands in the Global
Configuration mode.
Router(config)# router rip
Router(config)# network network number,
where network number could be 128.238.0.0. To remove the network,
use:
Router(config)# no network network number
To shutdown the RIP process, use:
Router(config)# no router rip
Consider Fig. 4.11 as our network topology for this section. Since the IP
address of ethernet1 in router4 is the only interface which is different
from the initial configuration in Appendix B, we will reboot all the four
routers to restore their default configurations, and change the IP address on
the ethernet1 in router4 only. Since our workstations started routed at
boot-up time, no further action is needed to run RIP on the workstations.2
Exercise 2 Connect the routers and hosts and change the IP addresses of the workstations
and router4 as shown in Fig. 4.11. Also, make sure that your workstation has no
other routing entries than your own subnet and your loopback interface. For how to
remove an entry from the host routing table, see Section 4.3.
Run the RIP process in each router. To avoid confusion, each router should be
configured by only one person.
2 The lab instructor should make sure that the IP-Forwarding function is enabled in each host (see
Appendix A.6).
94 Static and dynamic routing
vayu shakti
61.101/24 61.100/24
128.238.61.0 subnet
128.238.63.0 subnet
63.100/24 63.101/24
yachi fenchi
After starting RIP in all the routers, test connections to other hosts by pinging them.
Once you can successfully reach all the hosts, run the following command to capture
the RIP messages sent on your subnet:
tcpdump -x -s 100 -c 4 -w exe2.out udp port 520.
Save the routing table in your workstation. Note the number of hops needed to reach
destinations other than in your own subnet.
Run ethereal -r exe2.out & to load the packet trace recorded by the above tcpdump
command. Mark and print two different RIP messages captured in your subnet (see
Exercise 6 of Chapter 1). Exchange the printed RIP messages with students in other
groups. You need eight different RIP messages for your lab report.
LAB REPORT Explain why you can only get two different RIP messages in your subnet.
Was a RIP packet forwarded by the routers? Why?
LAB REPORT Draw the format of one of the saved RIP response packets from your sub-
net, including the IP and UDP headers and the RIP message (see Figs 0.13,
0.14, and 4.4). Identify each field, and express their values in decimal
format.
95 4.7 Routing experiments with ICMP
For the other seven RIP response packets collected, explain the contents of
the RIP messages only, excluding IP and UDP headers.
LAB REPORT Draw the distance tables and the routing tables in the routers based on
Fig. 4.11, assuming that number of hops is used as the metric.
Verify the routing tables using the RIP messages you captured.
Exercise 3 In this exercise we will examine how RIP responds to link failures. Send ping
message continuously from apah to yachi and start tcpdump on apah. Let the
two programs run during this exercise.
Disconnect the cable from the ethernet0 port of router2 from the hub in the
128.238.62.0 subnet, and type the time command to get the current time.
Observe the ping and tcpdump windows. When the connection is re-established,
type the time command again. See how much time RIP takes to alter the routing
table in your workstation to the new topology.
Once you can successfully reach other hosts, connect the cable to the original
position. Again, measure the time that RIP takes to change your routing table.
LAB REPORT Compare this time with the previous value in the spanning tree
experiment.
Explain why it takes this time for RIP to react to the route change. Refer
to Section 4.2.4 for RIP operation and default timer values.
Exercise 4 Eliminate the routing entries for subnets other than your own and the loopback
interface. Save the routing table for your lab report.
Create a default routing entry using one of the routers directly connected to your
workstation.
While tcpdump -enx -s 100 ip proto 1 is running, send ping messages to a host that
is three hops away through the default router.
After capturing an ICMP redirect message, save the tcpdump output, the ping output,
and your workstation’s routing table. You may need to ping the same host several
times in order to get your routing table updated.
eth1
Router 3 66.103/24 66.102/24 66.101/24 66.100/24
66.3/24
apah agni vayu shakti
eth1
Router 4
66.4/24
128.238.66.0 subnet
Compare the original routing table with the new routing table. Explain the
meaning of the flags of the new entry.
Exercise 5 This exercise3 is on ICMP router discovery. All students should do this exercise
together, using a single segment network.
Connect the routers and hosts and change the host IP addresses as shown in
Fig. 4.12.
Telnet to the routers, change the IP address of the ethernet1 interfaces as shown
in Fig. 4.12. Enable ICMP router discovery on these two interfaces by the following
Interface Configuration command:
Router(config-if)# ip irdp.
Run tcpdump -enx ip proto 1 on all the hosts except shakti.
The lab instructor should now reboot shakti.
Save the captured route discovery requests and replies for the lab report.
Telnet to shakti and save its routing table for the lab report.
LAB REPORT What is the destination IP address of the ICMP router solicitation
message? Who sends the ICMP router advertisement message?
What are the type and code of the ICMP messages captured?
What are the advertised router IP addresses and their preference levels?
How many default router entries are there in shakti’s routing table?
Why?
3 This exercise is for Solaris only, since Red Hat Linux does not support ICMP router discovery.
97 4.8 OSPF exercise
In order to enable OSPF in the routers, you need to create an OSPF routing
process first. Then, define the range of IP addresses to be associated with
the routing process and assign area IDs for these IP addresses, using the
following commands:
Router(config)# router ospf process id
Router(config)# network address wildcard mask area area id.
Process id is a numeric value local to the router. It does not have to match
process ids on other routers. Address is the network address of the interface
on which the OSPF process runs (128.238.0.0 in our case). Wildcard mask
helps reduce the number of configuration commands. 0 is a match and 1 is a
“don’t care” bit (0.0.255.255 in our case). Area id is the number of the area
that the interfaces belong to (see Fig. 4.7). It can be any integer between 0
and 232 − 1 or can have an IP address form. Note that 0 is reserved for the
backbone.
The above commands are required to configure OSPF, while other tasks
(configuring interface parameters, configuring area parameters, etc.) are
optional. For more information on other configuration tasks, refer to the
router manual.
Consider Fig. 4.13 for our OSPF experiment. The lab instructor should
reboot the routers to restore their default configurations.
Figure 4.13. Network configuration for the OSPF exercise, the static routing exercise,
and the traceroute exercise.
98 Static and dynamic routing
Exercise 6 After connecting the cables properly, change the host IP addresses as given in
Fig. 4.13. You need to remove the default route added in Exercise 4 from the host
routing table. Note that the router interfaces are set as Fig. 4.13 by default.
Run the following command to capture any OSPF packets:
tcpdump -x -s 120 ip proto 89
Login to a directly connected router and start the OSPF process. Set the argument
area id to 1 for all the routers.
The workstations in our lab run routed (which uses RIP). The routing daemon
supporting OSPF, gated, is not installed. In order to reach the routers and hosts in
the other subnets, you need to add a default router in your host’s routing table.
Examine the routing table in each router (see Section 4.3). When the routing table
gets an entry for the network that is not directly connected, kill the tcpdump process
and save the tcpdump output.
Collect the tcpdump outputs from other subnets. Study the various types of OSPF
packets from the tcpdump outputs.
You can display OSPF information in a router using the following commands in the
Privileged EXEC mode.
show ip ospf
show ip ospf database [router|network|summary| \
asb-summary|external|database-summary]
show ip ospf interface ethernet [0|1]
show ip ospf neighbor
show ip ospf virtual-links
LAB REPORT Draw the common header of a saved OSPF message, giving the decimal
values of the header fields (see Fig. 4.8).
Submit the routing tables you collected from the routers.
Exercise 7 After checking the wiring, as shown in Fig. 4.13, reboot the routers to restore their
initial settings. Check the IP addresses of the workstations as shown in Fig. 4.13.
Remove all the routing entries other than your own subnet and the loopback interface
from your host routing table. Save the output of netstat -rn before building your
workstation’s routing table.
99 4.10 Traceroute experiment
Examine Fig. 4.13 and build your host’s static routing table manually.
Telnet to a router that is directly connected to your workstation, and save its routing
table before building any route. Save the routing table of the other router if you have
one more router connected directly. You may not be able to telnet to a router that
is not directly connected. In this case, copy the initial routing table of these routers
from students in other subnets later.
Now configure the routing table in each router. See Section 4.3 for commands
and syntax on manipulating router routing tables. Note that each router should be
configured by one person only.
Use ping to test the connections. When you can reach all other subnets successfully,4
save the routing tables in your workstation and all the routers for the lab report.
In this exercise, we use the same network and configuration of the previous
exercises, and use traceroute to find a multi-hop path.
Exercise 8 Execute tcpdump -enx -s 100 host your host and remote host on your host, where
remote host is a workstation at least two hops away.
Then, execute traceroute remote host to find the route from your host to the remote
host.
Save the output of both traceroute and tcpdump.
4 Even when the routing table in your workstation and all the routers are configured perfectly, you may
not be able to ping a remote host, if the routing table in the remote host is incorrect. When you can
get ping reply messages from all the interfaces of the routers successfully, your work is done for this
exercise.
5 UDP and its applications
The principle, called the end-to-end argument, suggests that functions placed at
low levels of a system may be redundant or of little value when compared with
the cost of providing them at that low level.
J. H. Saltzer, D. P. Reed and D. D. Clark
5.1 Objectives
! Study sock as a traffic generator, in terms of its features and command
! IP fragmentation.
! MTU and path MTU discovery.
! UDP applications, using the Trivial File Transfer Protocol as an example.
! Compare UDP with TCP, using TFTP and the File Transfer Protocol.
Compared with the other transport protocol, TCP, UDP is simpler in the
sense that it does not guarantee successful and in-order delivery of the data-
grams. UDP is used by many network services, such as DNS, TFTP (which
we will examine in this chapter), NFS, RPC, BOOTP/DHCP, and SNMP.
UDP is also suitable for realtime services, such as video streaming and
VoIP, which are delay sensitive and loss tolerant. Besides unicast service,
UDP also provides multicast service. We will examine UDP multicast and
realtime transport in Chapter 7.
5.3.1 IP fragmentation
In Chapter 2 we saw that an important parameter associated with each
network interface is the MTU. An interesting question with MTU is what
happens if an IP datagram is longer than the MTU of the interface. In
this case, the IP layer splits the datagram into several fragments, each
with a length less than or equal to the MTU. This process is called IP
fragmentation.
The following IP header fields (see Fig. 0.13) are related to IP fragmen-
! Total Length: After fragmentation, this changes to the size of the frag-
tation.
! Flags: The “more fragments” flag indicates if the current fragment is the
original Identification.
last one or not, while the “don’t fragment” flag can be set by the source
! Fragment Offset: contains the offset (in 8-byte units) of the current
to disallow fragmentation in intermediate routers.
0 78 15 16 31
type (3) code (4) checksum
unused (set to 0) MTU of the next–hop network
IP header (including options) + first
8 bytes of the original IP datagram data
the source. This feature is used in path MTU discovery to find the smallest
MTU along a path.
5.4.2 TFTP
TFTP is a simple file transfer protocol using UDP. Since UDP is connec-
tionless and unreliable, TFTP uses a stop-and-wait flow control algorithm,
where each data packet is acknowledged by an ACK packet before the
next data packet is sent. In addition, a lost packet causes timeout and re-
transmission. TFTP is primarily designed for diskless systems to download
configuration files from a remote server during bootstrapping.
Figure 5.2 shows the architecture of a TFTP session. A common feature
for all the application layer protocols is the user interface (UI) module.
A UI directly interacts with a user, by translating user inputs (such as
keyboard entries and mouse clicks) into protocol primitives and displaying
the results of the operations. The TFTP protocol interpreter accesses the
local file system and communicates with its counterpart at the other end of
the session. The TFTP server uses UDP port 69 for TFTP control messages.
A different ephemeral port number is used by the server for data transfer.
Figure 5.3 shows the packet format of TFTP messages. The opcode field
is used to multiplex different TFTP messages. A typical TFTP session,
where a client downloads a file from the server, is as follows.
5.4.3 FTP
FTP is a file transfer protocol using TCP. Figure 5.4 shows the FTP archi-
tecture, where two TCP connections are used: a control connection (TCP
port 21) for FTP commands and replies, and a data connection (TCP port
20) for file transfer.
To set up an FTP session, the client sends SYN request to the server
TCP port 21 to establish the control connection. TCP connections will
be discussed in the next chapter. Tables 5.1 and 5.2 give the FTP com-
mands and typical server replies that can be sent on the control connection.
User inputs (e.g., get foo.txt) are translated to the primitives (e.g., RETR
foo.txt) shown in Table 5.1 by the UI, and sent on the control connection.
In addition, server responses, shown in Table 5.2, are received from the
control connection and are translated to more friendly messages by the UI
105 5.4 Client–server applications
Command Description
Reply Description
Client Server
FTP User
Interface
FTP user Protocol TCP port A TCP port 21 FTP server Protocol
Interpreter Interpreter
FTP user data transfer TCP port B TCP port 20 FTP server data transfer
function function
and displayed on the client screen. A data connection is created each time
a file is transferred. To open a data connection, the client first chooses an
ephemeral port number and then sends the port number to the server using
the PORT command, as shown in Table 5.1, via the control connection. Then
the server issues an active open to that port on the client host. File transfer
begins after the data connection is set up.
Many FTP servers support Anonymous FTP, which allows everyone
to log in and perform file uploads and downloads. Public domain free
information is sometimes provided using this technique. The login name
of Anonymous FTP is anonymous, and the password is your own email
address.
Most FTP implementations can be run in the debug mode, which is a
convenient way to study the operations of FTP. To run ftp in the debug
mode, use:
ftp -d ftp server IP.
! sock -s 5555
! sock -i -n3 -w2048 host 5555
Exercise 3 While running tcpdump src host your host, execute the following command with
different values of size (i.e., the size of the datagram).
sock -u -i -n1 -wsize remote host echo
The -u option is used to send UDP datagrams rather than TCP segments.
Increase size (i.e. the size of the datagram) until fragmentation occurs.
Use netstat -in to find out the MTU of the Ethernet interface.
107 5.7 Path MTU discovery exercise
LAB REPORT What is the maximum value of size for which the UDP datagram can be
sent without IP fragmentation? Justify your answer with the netstat output.
Exercise 4 Capture the data packets generated by the following command using tcpdump src
host your host.
sock -u -i -n1 -w10000 remote host echo
Save the tcpdump output for the lab report.
LAB REPORT Explain the tcpdump output in terms of the IP header fields that are
used in fragmentation.
When IP fragmentation occurs, only the first fragment has the UDP header.
How do you verify this fact from the tcpdump output?
Exercise 5 While running tcpdump src host your host, execute the following command with
different values of size,
sock -u -i -n1 -wsize remote host echo
in order to find out the maximum size of a UDP datagram that the system can send
or receive, even when fragmentation is allowed.
LAB REPORT What is the maximum size of user data in a UDP datagram that the
system can send or receive, even when fragmentation is allowed?
63.101/24 65.100/24
fenchi kenchi
Figure 5.5. The network setup for Exercise 6.
Observe the DF bit of the first datagram and that of the following datagrams. Save
the tcpdump output for your lab report.
Exchange tcpdump outputs with a student in the other subnet.
LAB REPORT Explain the operation of path MTU discovery based on the tcpdump
outputs saved.
Which ICMP message is used in path MTU discovery? Give the decimal
value of each field of the captured ICMP message.
What is the MTU of the destination network of the UDP datagram? Verify
your answer using both the ICMP message and the IP fragmentation trace
saved.
We will study the performance of FTP and TFTP for file transfer between
two machines. By transferring the same file using these two protocols, we
can compare the operations and performances of UDP and TCP.
Two files (large.dum and small.dum) with random contents are stored
in the /home/LAB directory and in the /tftpboot directory of each
workstation in the lab. We will use the get command to retrieve files
109 5.8 Exercises with FTP and TFTP
from a remote host. When FTP is used, you need to change directory
to /home/LAB/ by cd /home/LAB before retrieving the file. If you don’t
know how to use tftp, refer to its manual page.
Exercise 7 In order to compare the transfer rates of FTP and TFTP, we will retrieve a large
file from a remote server using FTP and TFTP, respectively. First run the following
tcpdump command:
tcpdump host your host and remote host > output1
Here we use the redirect operator, >, to save the tcpdump output into a text file
called output1.
Then get the /home/LAB/large.dum file from remote host using ftp.
Also, from the ftp window, record the transfer rate (time) displayed.
Restart the above tcpdump command, with the last argument changed to output2.
Now use tftp to get the /tftpboot/large.dum file.
Save output1 and output2 for the lab report.
LAB REPORT Examining the saved tcpdump output file, output1. Identify the start-
ing and ending time of actual data transfer. Don’t include the time spent
establishing the TCP connection. Calculate the time spent for data transfer.
Compare the time with the value displayed in ftp window. Are they consis-
tent? If there exists any significant difference, what might be the reason?
Now, from the saved output2, carefully determine the starting and ending
time of data transfer for the tftp program.
Compare the time with the value displayed in tftp window. Are they con-
sistent? If there exists any significant difference, what might be the reason?
By comparing the actual data transfer times of ftp and tftp, which of these
two is faster, and why?
Exercise 8 Capture the packets that are exchanged during a tftp session for the
/tftpboot/small.dum file between your host and a remote host, by
tcpdump -x host your host and remote host > output3
Observe the protocol in action. Analyze various types of TFTP messages used by
examining the content of output3. Save output3 for the lab report.
LAB REPORT List all the different types of packets exchanged during the tftp session.
Compare them with the TFTP message format in Fig. 5.3.
Why does the server’s port number change?
110 UDP and its applications
LAB REPORT In most cases, tftp service is restricted.1 Why is tftp service not generally
available to users?
LAB REPORT In Exercise 5, we found the maximum size of a UDP datagram in your
machine. With tftp, which uses UDP, we transferred a file larger than the
maximum UDP datagram size. How do you explain this?
Exercise 9 Repeat the above experiment, but use ftp and change the output file name
to output4. Capture a trace of the packets exchanged when downloading the
/home/LAB/small.dum file using ftp.
Save your tcpdump output. Examine the port numbers used.
LAB REPORT How many well-known port numbers were used? Which machine used
the well-known port numbers? What were the other machine’s port num-
bers?
LAB REPORT As can be seen from the tcpdump output, FTP involves two different
connections, ftp-control and ftp-data. Why are two different connec-
tions used, instead of one connection?
Exercise 10 Run ftp in the debug mode using: ftp -d remote host.
After logging into the remote host, type dir /home/LAB/small.dum in the ftp window.
Then type quit to terminate the ftp session, and save the ftp window output.
LAB REPORT Submit what you saved in this exercise, explaining each line of the
output.
Explain how the PORT command works.
Which connection, the control connection or the data connection, did the
server send the reponse (the LIST output) on?
1 This is not the case in our lab, where we deliberately enabled the TFTP service and use it as a tool
to study the UDP protocol.
6 TCP study
6.1 Objectives
!
!
TCP connection establishment and termination.
!
TCP timers.
!
TCP timeout and retransmission.
!
TCP interactive data flow, using telnet as an example.
!
TCP bulk data flow, using sock as a traffic generator.
!
Further comparison of TCP and UDP.
!
Tuning the TCP/IP kernel.
Study TCP flow control, congestion control, and error control using DBS
and NIST Net.
TCP is the transport layer protocol in the TCP/IP protocol family that pro-
vides a connection-oriented, reliable service to applications. TCP achieves
! Flow control: TCP uses sliding window flow control to prevent the re-
mechanism to guarantee that application data is received reliably.
111
112 TCP study
! Congestion control: TCP uses slow start, congestion avoidance, and fast
retransmit/fast recovery to adapt to congestion in the routers and achieve
high throughput.
The TCP header, shown in Fig. 0.16, consists of fields for the implementa-
tion of the above functions. Because of its complexity, TCP only supports
unicast, while UDP, which is much simpler, supports both unicast and mul-
ticast. TCP is widely used in internet applications, e.g., the Web (HTTP),
email (SMTP), file transfer (FTP), remote access (telnet), etc.
In the TCP header, the source and destination port numbers identify the
sending and receiving application processes, respectively. The combination
of an IP address and a port number is called a socket. A TCP connection is
uniquely identified by the two end sockets.
(a) (b)
client server client server
(1) FIN (seqNo x,
= ackNo=y)
(1) SYN (seqNo=n, ms
s=z, win=w)
ackNo=x+1
(2) to client
ents from server
more data segm
ss k, win=h)
,ackNo=n+1, m =
SYN (seqNo=m more acks from
client to server
(2)
ckNo=x+1)
(3) FIN (seqNo=z,a
(3) (4)
ackNo=m+1
ackNo=z+1
Figure 6.1. The time-line illustration of TCP connection management. (a) Three-way
handshake connection establishment; (b) Four-way handshake connection termination.
If an unrecoverable error is detected, either end can close the TCP con-
nection by sending a RST segment, where the Reset flag is set.
when this timer expires, the segment will be retransmitted. We will dis-
! Delayed ACK Timer. Used for delayed ACK in TCP interactive data
cuss this timer in more detail in the next section.
! TCP Persist Timer. Used in TCP flow control in the case of a fast
flow, which we will discuss in Section 6.4.2.
transmitter and a slow receiver. When the advertised window size from
the receiver is zero, the sender will probe the receiver for its window size
when the TCP Persist Timer times out. This timer uses the normal TCP
Exponential Backoff algorithm, but with values bounded between 5 and
! TCP Keepalive Timer. When a TCP connection has been idle for a long
60 seconds.
time, a Keepalive timer reminds a station to check if the other end is still
termination. It is the period of time that a TCP connection keeps alive after
the last ACK packet of the four-way handshake is sent [see Fig.6.1(b)].
This gives TCP a chance to retransmit the final ACK.2 It also prevents the
delayed segments of a previous TCP connection from being interpreted
as segments of a new TCP connection using the same local and remote
sockets.
segments). The receiver TCP module uses a receiving buffer to store and re-
order received TCP segments. A byte stream is restored from the receiving
buffer and sent to the application process.
Error detection
In order to detect lost TCP segments, each data byte is assigned a unique se-
quence number. TCP uses positive acknowledgements to inform the sender
of the last correctly received byte. Error detection is performed in each
layer of the TCP/IP stack (by means of header checksums), and errored
packets are dropped. If a TCP segment is dropped because TCP checksum
detects an error, an acknowledgement will be sent to the sender for the first
byte in this segment (also called the sequence number of this segment), thus
effectively only acknowledging the previous bytes with smaller sequence
numbers. Note that TCP does not have a negative acknowledgement feature.
Furthermore, a gap in the received sequence numbers indicates a transmis-
sion loss or wrong order, and an acknowledgement for the first byte in the
gap may be sent to the sender. This is illustrated in Fig. 6.2. When segment
7 is received, the receiver returns an acknowledgement for segment 8 to
the sender. When segment 9 is lost, any received segment with a sequence
number larger than 9 (segments 10, 11, and 12 in the example) triggers a
time
Figure 6.2. A received segment triggers the receiver to send an acknowledgement for the
next segment.
116 TCP study
0 1 2 3 4 5 6 7 8 9 10 11 12 time
X
the real time out value
The timer starts here timer goes off
with timeout value=6seconds at the 12th tick
the base timer. For the ith measured RTT value Mi , RTO is updated as
follows (RFC 2988):
RT Tis = (1 − α) × RT Ti−1
s
+ α × Mi , (6.1)
d d s
RT Ti = (1 − β) × RT Ti−1 + β × |Mi − RT Ti−1 |, (6.2)
s d
RT Oi = RT Ti + max{G, 4 × RT Ti }, (6.3)
where α = 1/8 and β = 1/4. If the computed RTO is less than 1 second,
then it should be rounded up to 1 second, and a maximum value limit may
be placed on RTO provided that the maximum value is at least 60 seconds.
The TCP timers are discrete. In some systems, a base timer that goes off
every, e.g., 500 ms, is used for RTT measurements. If there are t base timer
ticks during a RTT measurement, the measured RTT is M = t × 500 ms.
Furthermore, all RTO timeouts occur at the base timer ticks. Figure 6.3
shows a timeout example when RT O = 6 seconds, and the timer goes off
at the 12th base timer tick after the timer is started. Clearly the actual time
out period is between 5.5 and 6 seconds. Different systems have different
clock granularities. Experience has shown that finer clock granularities
(e.g., G ≤ 100 ms) perform better than more coarse granularities [8].
70
60
RTO (seconds) 50
40
30
20
10
0
0 2 4 6 8 10 12
Number of retransmissions
Delayed acknowledgement
TCP uses a delayed acknowledgement timer that goes off every K ms (e.g.,
50 ms). After receiving a data segment, TCP delays sending the ACK until
the next tick of the delayed acknowledgement timer, hoping that new data
to be sent in the reverse direction will arrive from the application during
119 6.4 Managing the TCP data flow
this period. If there is new data to send during this period, the ACK can
be piggybacked with the data segment. Otherwise, an ACK segment (with
no data payload) is sent. Depending on when the data segment is received,
when there is new data arriving from the application layer, and when the
delayed acknowledgement timer goes off, an ACK may be delayed from 0
ms up to K ms.
Wl advertised window Wm Wr
1 2 3 4 5 6 7 8 9 10 11
sent but can be
sent and acked not acked sent cannot be sent as yet
(a)
1 2 3 4 5 6 7 8 9 10 11
(b)
Figure 6.5. A TCP sliding window flow control example. (a) The sliding window
maintained by the sender. (b) The updated sliding window when an acknowledgement,
[ackno = 5, awnd = 6] is received.
(called the Advertised Window, or awnd), and the sender is not allowed to
send more data than the advertised window.
Figure 6.5(a) illustrates the sliding window flow control algorithm. The
application data is a stream of bytes, where each byte has a unique sequence
number. In Fig. 6.5, each block represents a TCP segment with MSS bytes,
and the number can be regarded as the sequence number of the TCP seg-
ments in units of MSS bytes. In TCP, the receiver notifies the sender (1) the
next segment it expects to receive and (2) the amount of data it can receive
without causing a buffer overflow (denoted as [ackno = x, awnd = y]),
using the Acknowledgement Number and the Window Size fields in the
TCP header. Figure 6.5(a) is the sliding window maintained at the sender.
In this example, segments 1 through 3 have been sent and acknowledged.
Since the advertised window is five segments and the sender already has
three outstanding segments (segments 4, 5, and 6), at most two more seg-
ments can be sent before a new acknowledgement is received.
The sliding window, shown as a box in Fig. 6.5, moves to the right as
new segments are sent, or new acknowledgements and window advertise-
ments are received. More specifically, if a new segment is acknowledged,
Wl , the left edge of the window, will move to the right (window closes).
Wm moves to the right when new segments are sent. If a larger window
is advertised by the receiver or when new segments are acknowledged,
the right edge of the sliding window, Wr , will move to the right (window
opens). However, if a smaller window is advertised, Wr will move to the
left (window shrinks). Figure 6.5(b) illustrates the updated sliding window
when an acknowledgement, [ackno = 5, awnd = 6], is received.
With this technique, the sender rate is effectively determined by (1)
the advertised window, and (2) how quickly a segment is acknowledged.
Thus a slow receiver can advertise a small window or delay the sending of
121 6.4 Managing the TCP data flow
1e+05
cwnd
1e+05 ssthresh
1e+05
8e+04
Bytes
6e+04
4e+04
2e+04
0e+00
0 100 200 300 400 500 600 700 800 900 1000
Time (RTT)
Figure 6.6. The evolution of cwnd and ssthr esh for a TCP connection, including slow
start, congestion avoidance, fast retransmit, and fast recovery.
gap. Further arriving segments, other than the segment corresponding to the
gap, trigger duplicate acknowledgements (see Figure 6.2). After receiving
three duplicate acknowledgements, the sender assumes that the segment
is lost and retransmit the segment immediately without waiting for the
retransmission timer to expire. This algorithm is called the fast retransmit
algorithm. After the retransmission, congestion avoidance, rather than slow
start, is performed, with an initial cwnd equal to ssthr esh plus one segment
size.4 This is called the fast recovery algorithm. With these two algorithms,
cwnd and ssthr esh are updated as shown in Table 6.2. In the example
shown in Fig. 6.6, TCP fast retransmit and fast recovery occur at time
instances around 610, 740, and 950.
default values. For the parameters with binary values, a “0” means the func-
tion is disabled, while a “1” means the function is enabled. Some frequently
! sysctl -p file name: to load the sysctl setting from a configuration file. If
Solaris 8.0 provides a program, ndd, for tuning the TCP/IP kernel, including
the IP, ICMP, ARP, UDP and TCP modules. To display a list of parameters
editable in a module, use the following command:
ndd module \?,
where module could be /dev/ip, /dev/icmp, /dev/arp, /dev/udp, or
/dev/tcp. To display the current value of a parameter, use:
ndd -get module parameter.
To modify the value of a parameter in a module, use:
ndd -set module parameter.
Controller (3)
(3) ... ...
(3)
(3) (2)
(1)
(1)
TCP connection 1
TCP connection 2
timestamp src IP.src port > dest IP.dest port: flags seq no ack window urgent options
Exercise 1 While tcpdump -S host your host and remote host is running, execute: telnet
remote host time.
Save the tcpdump output.
LAB REPORT Explain TCP connection establishment and termination using the
tcpdump output.
LAB REPORT What were the announced MSS values for the two hosts?
127 6.8 Exercise on TCP interactive data flow
LAB REPORT Explain what happened in both the UDP and TCP cases. When a client
requests a nonexisting server, how do UDP and TCP handle this request,
respectively?
Exercise 3 While tcpdump is capturing the traffic between your machine and a remote machine,
issue the command: telnet remote host.
After logging in to the host, type date and press the Enter key.
Now, in order to generate data faster than the round-trip time of a single byte to be
sent and echoed, type any sequence of keys in the telnet window very rapidly.
Save the tcpdump output for your lab report. To avoid getting unwanted lines from
tcpdump, you and the student who is using the remote machine should do this
experiment in turn.
LAB REPORT Answer the following questions, based upon the tcpdump output saved
in the above exercise.
(1) What is a delayed acknowledgement? What is it used for?
(2) Can you see any delayed acknowledgements in your tcpdump output?
If yes, explain the reason. Mark some of the lines with delayed ac-
knowledgements, and submit the tcpdump output with your report.
Explain how the delayed ACK timer operates from your tcpdump
output.
If you don’t see any delayed acknowledgements, explain the reason
why none was observed.
128 TCP study
Exercise 4 While tcpdump is running and capturing the packets between your machine and
a remote machine, on the remote machine, which acts as the server, execute:
sock -i -s 7777.
Then, on your machine, which acts as the client, execute:
sock -i -n16 remote host 7777.
Do the same experiment three times. Save all the tcpdump outputs for your lab
report.
LAB REPORT Using one of three tcpdump outputs, explain the operation of TCP in
terms of data segments and their acknowledgements. Does the number of
data segments differ from that of their acknowledgements?
Compare all the tcpdump outputs you saved. Discuss any differences
among them, in terms of data segments and their acknowledgements.
LAB REPORT From the tcpdump output, how many different TCP flags can you see?
Enumerate the flags and explain their meanings.
How many different TCP options can you see? Explain their meanings.
Exercise 5 Execute sysctl -A | grep keepalive to display the default values of the TCP kernel
parameters that are related to the TCP keepalive timer.
What is the default value of the TCP keepalive timer? What is the maximum number
of TCP keepalive probes a host can send?
In Solaris, execute ndd -get /dev/tcp tcp keepalive interval to display the
default value of the TCP keepalive timer.
129 6.11 Other exercises
Exercise 7 While tcpdump src host your host is running, execute the following command,
which is similar to the command we used to find out the maximum size of a UDP
datagram in Chapter 5,
sock -i -n1 -wn host echo
Let n be larger than the maximum UDP datagram size we found in Exercise 5 of
Chapter 5. As an example, you may use n = 70,080.
When Solaris is used, use ndd to examine the TCP/IP configuration pa-
rameters. See Section 6.5 or the manual page of ndd for the syntax and
parameters.
130 TCP study
In this exercise, students are divided into two groups as shown in Table 6.3.
The four hosts in each group are connected by a hub. All the hosts have the
default IP addresses and subnet masks as shown in Table 1.2.
Before these exercises, the lab instructor should start ntpd to synchronize
the hosts. First, modify the /etc/ntp.conf file in all the hosts as follows:
(1) comment the “restrict default ignore” line, and (2) for host1, host2, and
host3 in Group A, insert a new line “server 128.238.66.103”; for host1,
host2, and host3 in Group B, insert a new line “server 128.238.66.107”. For
example, the /etc/ntp.conf file in host1, host2, and host3 look should
like the following:
···
# restrict default ignore
···
server 128.238.66.103 # for Group A
# server 128.238.66.107 # for Group B
···
Second, start the ntpd daemon by running /etc/init.d/ntpd start. Then all
the hosts in Group A (Group B) will be synchronized with apah (kenchi).
Note that it may take a while (several minutes) for the hosts to be synchro-
nized, since by default an NTP client polls a server every 60 seconds.
Exercise 9 In the following, we will use DBS to study the performance of TCP under differ-
ent background traffic. The DBS command files used in this exercise are given in
Appendix C.1.
The TCP1.cmd file in Section C.1.1 of Appendix C1 is used to set up a TCP connection
between host1 and host2, where host2 sends a stream of packets to host1. Edit
the TCP1.cmd file, replace the values for the hostname variable to the IP addresses
131 6.12 Exercises with DBS and NIST Net
of the corresponding hosts in your group as shown in Table 6.3. For example, in
group A, host1 is shakti and host2 is vayu. So the TCP1.cmd for Group A should
be changed as shown below:
···
sender {
hostname = 128.238.66.101
···
receiver {
hostname = 128.238.66.100
···
In all the following experiments, we will use host4 as the DBS controller. Start
tcpdump host host1 IP and host2 IP on all the hosts. Then start dbsd on all other
hosts except host4 (apah in Group A and kenchi in Group B). Next, execute dbsc
TCP1.cmd on host4.
Observe the data transmissions between host1 and host2 from the tcpdump
output.
When the data transmission is over, execute the following two commands on host4
to plot the received sequence numbers and throughput of the TCP connection:
dbs view -f TCP1.cmd -sq sr -p -ps -color > ex9sqa.ps,
dbs view -f TCP1.cmd -th r -p -ps -color > ex9tha.ps.
Save these two Postscript files for the lab report. You can use the GIMP graphical
tool in Red Hat Linux to convert the Postscript files to other formats. The second
dbs view command also gives the average throughput of the TCP connection. Save
this number for the lab report.
Next, edit the TCPUDP.cmd file given in Section C.1.2 of Appendix C. Replace
the hostname fields with the corresponding IP addresses for the senders and
the receivers according to Table 6.3. Then, repeat the above exercise, but use the
TCPUDP.cmd file. This file consists of commands to start a TCP connection with
the same parameters as the previous exercise, and a UDP flow emulating an MPEG
video download. Oberve the impact on TCP performance of the UDP flow.
When the data transmission is over, execute the following two commands to plot
the received sequence numbers and throughput of the TCP connection:
dbs view -f TCPUDP.cmd -sq sr -p -ps -color > ex9sqb.ps,
dbs view -f TCPUDP.cmd -th r -p -ps -color > ex9thb.ps.
Save these two Postscript files, as well as the average throughputs of the TCP
connection and the UDP flow.
132 TCP study
host1 IP host2 IP 20 ms
host3 IP host2 IP 500 ms
LAB REPORT Compare the throughput of the TCP connections in the above two exper-
iments. In which case does the TCP connection have higher throughput?
Justify you answer with the throughput plots and the sequence number
plots.
Exercise 10 5 In one command window, execute tcpdump ip host host1 IP and host2 IP to
capture the TCP packets between host1 and host2. In another command window,
run tcpdump ip host host3 IP and host2 IP to capture the TCP packets between
host3 and host2.
On host1, execute Load.Nistnet to load the NIST Net emulator module into the Linux
kernel.
Execute xnistnet on host1 (shakti in Group A and yachi in Group B). Enter the
values in the NIST Net GUI as given in Table 6.4. Then click the Update button
to enforce a 20 ms delay on the TCP connection between host1 and host2, and a
500 ms delay on the TCP connection between host2 and host3.
Start the DBS daemon on host1, host2, and host3, by running dbsd -d.
Edit the TCP2.cmd file given in Section C.1.3 of Appendix C on host4. Set the
hostname values in the command file to the corresponding IP addresses according
to Table 6.3. Execute the DBS controller on host4, by dbsc TCP2.cmd.
Observe the data transmissions shown in the tcpdump outputs. When data trans-
missions are over, save the tcpdump outputs and use the following command to
plot the received sequence numbers and throughputs of the two TCP connections:
dbs view -f TCP2.cmd -sq sr -p -ps -color > ex10sq.ps,
dbs view -f TCP2.cmd -th r -p -ps -color > ex10th.ps,
Save the plots and the mean throughputs of the two TCP connections from the
dbs view outputs.
LAB REPORT From the received sequence number plot, can you tell which TCP
connection has higher throughput? Why? Justify your answer using the
tcpdump outputs and the dbs view plots.
5 This exercise is for Linux only, since NIST Net does not run on Solaris.
133 6.12 Exercises with DBS and NIST Net
Exercise 11 6 Restart the xnistnet program on host1. Set Source to host2’s IP address
and Dest to host1’s IP address. Set Delay for this connection to be 500 ms, and
Delsigma to 300 ms. This enforces a mean delay of 500 ms and a delay deviation
of 300 ms for the IP datagrams between host1 and host2.
Execute tcpdump ip host host1 IP and host2 IP on all the hosts.
Start a sock server on host1 by running sock -i -s 7777. Start a sock client on
host2 by running sock -i -n50 host1 IP 7777 to pump TCP packets to host1.
When the data transfer is over, examine the tcpdump outputs to see if a retransmis-
sion or fast retransmission occured. If you cannot see one, you may try running the
sock program again.
LAB REPORT Submit the section of a tcpdump output saved that has out of order TCP
segments arriving at the receiver.
Exercise 12 7 This exercise is similar to the previous one, except that Delay is set to 100 ms,
Delsigma is set to 0 ms, and Drop is set to 5%.
Run the sock server and client. When the data transfer is over, examine the tcpdump
output. Can you see any packet loss and retransmission? Justify your answer using
the tcpdump output.
Try different values for the Drop field, or different combinations of Delay,
DelSigma, and Drop.
6 This exercise is for Linux only, since NIST Net does not support Solaris.
7 This exercise is for Linux only, since NIST Net does not support Solaris.
7 Multicast and realtime service
We are now in a transition phase, just a few years shy of when IP will be the
universal platform for multimedia services. H. Schulzrinne
7.1 Objectives
!
!
Multicast addressing.
!
Multicast group management.
!
Multicast routing: configuring a multicast router.
!
Realtime video streaming using the Java Media Framework.
!
Protocols supporting realtime streaming: RTP/RTCP and RTSP.
Analyzing captured RTP/RTCP packets using Ethereal.
7.2 IP multicast
(a) (b)
Network B Network B
A C A C
D D
Figure 7.1. Comparison of IP unicast and multicast. (a) A unicast example, where node A
sends three copies of the same packet to nodes B, C, and D. (b) A multicast example,
where node A sends a packet to the multicast group, which consists of nodes B, C,
and D.
1 RFC 1112 indicates that the sender, e.g. node A, does not have to be in the multicast group.
136 Multicast and realtime service
1. Multicast addressing. How to define a common group address for all the
nodes in the group to use, and how to map a multicast group address to
a MAC address.
2. Multicast group management. The multicast group is dynamic, meaning
that users may join and leave the group during the multicast session.
A multicasting router needs to keep track of the memberships of the
multicast groups, and a participant may want to know who else is in the
group.
3. Multicast routing. A multicast tree should be found and maintained
from a participating node to all other nodes in the group, and the tree
should be updated when either the network topology changes or the
group membership changes.
We will examine these three key components of IP multicasting in the
following sections.
Multicast bit
Figure 7.2. The multicast bit in an Ethernet address (the eighth bit).
11 1 0 5 bits 23 bits
only the last 23 bits of the Class D IP address is mapped into the multicast
MAC address. As a result, 25 = 32 Class D IP addresses will be mapped
to the same Ethernet multicast address. Thus the device driver or the IP
module should perform the packet filtering function to drop the multicast
IP datagrams destined to a group it does not belong to.
At the receiver, the upper layer protocol should be able to ask the IP
module to join or leave a multicast group. The IP module maintains a list
of group memberships. This list is updated when an upper layer process
joins a new group or leaves a group. Similarly, the network interface should
be able to join or leave a multicast group. When the network interface joins a
new group, its reception filters are modified to enable reception of multicast
Ethernet frames belonging to the group. A router interface should then be
able to receive all the multicast IP datagrams.
1 4 5 8 9 16 17 32
Version Type Unused Checksum
32–bit Class D IP Address
1 8 9 16 17 32
Type Max Resp Time Checksum
32-bit Class D IP Address
! The packet comes from the shortest route from R back to S. This scheme
S if, and only if the following conditions apply.
! R forwards the packet only to the child links for S. A child link of R for S
is called Reverse Path Forwarding.
is defined as the link that has R as parent on the shortest path tree where
S is the root. The child links are found by multicast routing updates.
Thus, a multicast datagram is effectively flooded to the entire network using
the shortest path tree with S as the root. In addition, DVMRP assigns various
values to the TTL field of multicast datagrams to control the scope of the
broadcast. Furthermore, each link can be assigned with a TTL threshold in
addition to the routing cost. A router will not forward a multicast/broadcast
datagram if its TTL is less than the threshold.
When the packet arrives at a router with no record of membership in that
group, the router will send a prune message, or a non-membership report,
upstream of the tree, so that the branch will be deleted from the multicast
tree. On the other hand, when a new member in a pruned subnet joins the
group, the new membership will be detected by the router using IGMP.
Next, the router will send a message to the core to undo the prune. This
technique is called grafting.
As in RIP, DVMRP is based on the distance vector routing algorithm.
Therefore, it has the same limitations as RIP, e.g., it also has the count-to-
infinity problem. DVMRP uses multiple multicast trees, each with a source
as its root. The multicast routing daemon for DVRMP is mrouted.
Receiver 1
source 3
Core
Receiver 1
source 1 source 2
It has been used for testing of new protocols or tools (e.g., the vic teleconfer-
encing tool in 1994), live multicasting of academic conferences (e.g., ACM
SIGCOMM), the NASA space shuttle missions, and even a Rolling Stones
concert.
MBone is an overlay network with a double-layer structure. The lower
layer consists of a large number of local networks that can directly support
IP multicast, called multicast islands. The upper layer consists of a mesh
of point-to-point links, or tunnels, connecting the islands. The mrouted
multicast routing daemon is running at the end points of the tunnels using
the DVMRP protocol. Multicast IP datagrams are sent and forwarded within
the islands. However, when a multicast IP datagram is sent through a tunnel,
it is encapsulated in a unicast IP datagram. When the unicast IP datagram
reaches the other end of the tunnel, the unicast IP header is stripped and the
recovered multicast IP datagram is forwarded. Note that such a dual-layer
structure is also suggested and used in IPv6 deployment.
frames
source
Network
Network X
Receiver
t
Playout Buffer
Display
t
F1 F2 F3 F4 F5 F6 F7 F8 F9 F10 F11 F12
Figure 7.8. A video streaming example: the playout buffer is used to absorb jitter.
video frames are sent periodically at the source, the received video frame
pattern is distorted. Usually the receiver uses a playout buffer to absorb
the variation in the packet interarrival times (called jitter). Each frame is
delayed in the playout buffer for a certain amount of time and is extracted
from the buffer at the same rate at which they are transmitted at the source.
An overdue frame, which arrives later than its scheduled time for extraction
from the buffer (or the time it is supposed to be displayed), is useless and
discarded. The difference between the arrival time of the first frame and the
time it is displayed is called playout delay. With a larger playout delay, a
frame is due at a later time, and thus a larger jitter is tolerable and fewer
frames will be overdue. But this improvement in loss rate is at the cost of
a larger delay experienced by the viewer.
In addition to the jitter control discussed above, there are many other
requirements for effective realtime multimedia streaming. These require-
ments can be roughly categorized into two types: end-to-end transport
control and network support. End-to-end transport control is implemented
at the source and receiver, assuming a stateless core network, while network
support is implemented inside the network. Several important end-to-end
a means for the receiver to detect if the arriving packets are out of order.
One way to do this is to assign a unique identifier, called the sequence
number, to each packet. The sequence number is increased by one for each
packet transmitted. By examining the sequence numbers of the arriving
147 7.3 Realtime multimedia streaming
frame to the receiver, so that the receiver can replay the frames at the
right pace. Timestamps can also be used by a receiver to compute jitter
data types, coding schemes, and formats, the sender should inform the
receiver about the payload type, so that the receiver can interpret the
! Error concealment. When packets are lost, the receiver may perform
reQuest (ARQ).
error concealment to reduce the impact of the lost packets. For exam-
ple, when a frame is lost, the player may repeat the previous frame, or
such as loss rate, jitter, received frame quality, and send them back to the
sender. With such information, the sender may adjust its parameters or
! Rate control. A multimedia session may have a high data rate (e.g.,
operation modes to adapt to congestion or packet losses in the network.
high quality video streaming). Usually UDP is used for multimedia data
transfer. The high-rate UDP data flows may cause congestion in the net-
work, making other adaptive TCP flows suffer from low throughput (see
Exercise 9 in Chapter 6). The sender needs to be adaptive to network con-
gestion. When there is congestion, the sender may reduce its sending rate,
e.g., by reducing the frame rate or changing the encoding parameters.
In addition to the end-to-end transport controls, realtime multimedia
streaming also requires support from the packet-switched IP network. Ex-
amples of such supports are: (1) reservation of bandwidth along the network
path for a multimedia session; (2) scheduling packets at the core routers
to guarantee their QoS requirements; (3) sophisticated routing algorithms
to find a route that satisfies the QoS requirements of a multimedia session
(e.g., enough bandwidth or a low loss probability); and (4) shaping and
policing the multimedia data flow to make it conform to an agreed-upon
traffic specification.
148 Multicast and realtime service
Applications
RTP/RTCP/RTSP/SIP
! Version (V): 2 bits. This field shows the RTP version, which is cur-
the RTP header format. The fields are listed here.
! Padding (P): 1 bit. If this bit is set to 1, the RTP payload is padded
rently 2.
to align to the 32-bit word boundary. The last byte of the payload is the
number of padding bytes.
149 7.3 Realtime multimedia streaming
! CSRC Count (CC): 4 bits. This field indicates the number of contributing
following the RTP header.
This bit can be used to mark a significant event, e.g., the boundary of a
! Payload Type (PT): 7 bits. This field identifies the format of the RTP
video frame, in the payload.
! Timestamp: 32 bits. This field identifies the sampling instant of the first
detection and resequencing.
each with 32 bits. The list of identifiers of the sources whose data is
carried (multiplexed) in the payload.
RTCP uses several types of packets, e.g., Sender Report (SR) and Re-
ceiver Report (RR) for QoS reports, Source Description (SDES) to de-
scribe a source, goodbye (BYE) packet for leaving the group, and other
application-specific packets (APP). A RTCP packet may be the concatena-
tion of several such packets. The format of a RTCP SR packet is shown in
Fig. 7.11. A RTCP RR packet has the same format as a RTCP SR, but with
the PT field set to 201 and without the Sender Info block. The following
list gives the definitions of the header fields.
SSRC of Sender
Profile–specific Extensions
! NTP Timestamp: 64 bits. This field carries the wallclock time (absolute
! Sender’s Octet Count: 32 bits. The total number of RTP bytes sent
sent by this sender.
! Fraction Lost: 8 bits. This field is the fraction of RTP data packet lost
by this sender.
number of RTP data packet lost from the source since the beginning of
! Delay since Last SR (DLSR): 32 bits. This field is the delay, ex-
from the source.
Network
For all the exercises in this section, the network topology is given in Fig. 1.3,
where all the hosts are connected to a single network segment using their
default IP addresses, i.e., from 128.238.66.100 to 128.238.66.107.
Exercise 1 Execute netstat -rn to display the routing table of your host. If there is no entry for
the 224.0.0.0 subnet, you need to provide a default route for multicast traffic, by:
route add -net 224.0.0.0 netmask 240.0.0.0 dev eth0 3
Save the new routing table.
LAB REPORT How many multicast groups did the interface belong to? What were the
groups? Explain the meaning of the group IDs.
3 This command can be appended to the /etc/rc.local file, so that it will be executed automatically
when the system bootstraps. Each time when the network interface is brought down and up again by
the ifconfig command, you may need to run the route command to re-insert the multicast routing
entry.
153 7.4 Simple multicast exercises
Exercise 3 Execute ping 224.0.0.1. Examine the ping output to see which hosts reply.
Ping a broadcast address using ping -b 128.238.66.255. Examine the ping output
to see which hosts reply.
LAB REPORT Which hosts replied when the multicast address was pinged? Which
hosts replied when the broadcast address was pinged?
In each case, was there a reply from your host?
Exercise 4 Execute tcpdump -n -nn -e and tcpdump ether multicast -n -nn -e to capture
an Ethernet unicast frame, an Ethernet multicast frame, and an Ethernet broadcast
frame.
To generate an Ethernet unicast frame, run sock -i -u -n1 r emote host echo.
Execute sock -i -u -n1 230.11.111.10 2000 to generate an Ethernet multicast frame.
Generate another Ethernet multicast frame, but with a different group address of
232.139.111.10.
To generate an Ethernet broadcast frame, you may ping a remote host that has no
entry in the ARP table of you host. Recall that the ARP request is broadcast.
Save the frames captured for the lab report.
LAB REPORT Compare the source and destination MAC addresses of the frames you
captured.
Use one of the multicast frames captured to explain how a multicast group
address is mapped to a multicast MAC address. For the two multicast frames
captured, do they have the same destination MAC address? Why?
Exercise 5 Start the multicast client netspy on all the hosts, by executing
netspy 224.111.111.111 1500.
Then, start the multicast sender netspyd on shakti, by executing
netspyd 224.111.111.111 1500 1.
Execute tcpdump ip multicast on every host to capture multicast IP datagrams.
Login to shakti from a remote machine, e.g., kenchi, using telnet or ssh.
Save the captured multicast datagram sent by netspyd and exit the telnet (or ssh)
session.
154 Multicast and realtime service
LAB REPORT From the tcpdump output, how many messages are sent by netspyd
when a new user logged in to shakti? From the netspy outputs on all the
hosts, how many copies of the message are received in total?
Did shakti, where the multicast sender, netspyd, was running, receive
the multicast datagram? Why? If yes, through which interface did shakti
receive this datagram?
Exercise 6 Keep the netspy and the tcpdump programs running. Execute ping 224.111.111.111
from kenchi. Examine the tcpdump and ping outputs to see which hosts replied.
To avoid confusion, students should do this exercise by turns.
Terminate the netspy programs on several hosts, e.g., shakti, vayu, and fenchi.
Execute the ping command again. Also, examine the tcpdump and the ping outputs
to see which hosts replied.
In the following exercises, students are divided into two groups, Group A
and Group B, each with four hosts and one router. The network topology of
each group is given in Fig. 7.13, and the corresponding host IP addresses
and router IP addresses are given in Table 7.2 and Table 7.3, respectively.
GROUP A GROUP B
eth0 eth1
ROUTER
Figure 7.13. The network topology for the exercises in Section 7.5.
155 7.5 IGMP exercises
Exercise 7 Connect the hosts and the route in your group as shown in Fig. 7.13. Set the IP
address of your host as given in Table 7.2. Note that the IP addresses of the router
interfaces are the same as their default IP addresses.
Login to the router and run ip multicast-routing to enable multicast routing in the
Global Configuration mode. Then, enable the PIM protocol on each interface, by
running ip pim dense-mode in the Interface Configuration mode.4 Now the router
is enabled to do multicast routing using PIM.
Login to the router, execute show ip igmp interface and show ip igmp group in
the Privileged EXEC mode. Examine the multicast group memberships currently
recorded in the router and the configurations of the router interfaces.
LAB REPORT Can you ping a host on the other side of the router? Will the router
forward a multicast IP datagram to the other side? Justify your answers.
Exercise 9 Execute tcpdump ip multicast -w ex9a.out in one console to capture IGMP mes-
sages. At the same time, execute tcpdump ip multicast in another console to mon-
itor the capture process. When you see three or more IGMP queries in the second
tcpdump output, terminate both tcpdump programs.
Start ethereal by using ethereal -r ex9a.out to analyze the IGMP messages you
captured. Print and save two different IGMP messages.
Repeat the above experiment, but change the output file to ex9b.out. Terminate
netspy on host2 and host4. Terminate the tcpdump programs and analyze the IGMP
leave message you captured.
LAB REPORT What is the value of the Time-to-Live (TTL) field for the IGMP mes-
sages? Why do we not set the TTL to a larger number?
What is the default frequency at which the router sends IGMP queries?
Exercise 10 Login to the router. See if you can make a router interface (e.g., Ethernet0) join
a multicast group of 224.0.0.2, using
ip igmp join-group 224.0.0.2.
For the rest of the exercises in this chapter, the network topology is given
in Fig. 7.14. The exercises will be jointly performed by all the students.
The IP addresses of the hosts and router interfaces are given in Fig. 7.14.
Exercise 11 Connect the hosts and routers as illustrated in Fig. 7.14. Configure the IP addresses
of the hosts and router interfaces as given in the figure. Note that most of the router
interfaces use their default IP addresses, only the Ethernet0 interface of Router4
needs to be changed to 128.238.63.4.
eth0 eth1
62.100/24 router2 63.100/24 63.101/24
agni 62.2/24 63.2/24 apah yachi
Enable PIM multicast routing in all the routers (see Exercise 7).
Run tcpdump ip multicast on all the hosts.
Execute netspy 224.111.111.111 1500 on shakti, agni, apah, fenchi, and
kenchi. Execute netspyd 224.111.111.111 1500 16 on yachi. To generate mul-
ticast traffic, you can login (by telnet or ssh) to or logout of yachi. Each time
when the login user set of yachi changes, netspyd on yachi will send a multicast
datagram to group 224.111.111.111, to report the change in its login users.
Can you see the netspy messages on the 128.238.65.0 (or the 128.238.61.0) subnet
in the tcpdump output?
Terminate the netspy program on kenchi (or shakti). Can you see the netspy
messages on the 128.238.65.0 (or the 128.238.61.0) subnet?5
Save one of the PIM routing packets. You may use ethereal to analyze it.6 What is
the destination IP address used in this PIM routing packet?
Exercise 12 In this exercise, try the mstat Cisco IOS command to find the multicast tree from
a source. The mstat command is executable in the Privileged EXEC mode. You can
always type “?” to get help on the syntax of the command.
Exercise 13 Keep netspy running on all the hosts. Ping the multicast group address from
yachi, using
ping 224.111.111.111 -t n.
The parameter n is the TTL to be set to the multicast datagrams sent by ping. Try
different values of n, e.g., 1, 2, 3, and 16. See how far a multicast datagram can
travel with different TTL values.
Now, login to Router2, in the Interface Configuration mode, set the TTL threshold
of the Ethernet0 interface to 32, using:
ip multicast ttl-threshold 32.7
Run the ping command with n = 16 again. Can you see the multicast datagrams in
the 128.238.61.0 and 128.238.62.0 subnet? Try n = 33. Answer the same question.
5 If IGMPv1 is used, a participant does not send a leave message when it leaves the group. In this
case, the membership record in the router expires in 120 seconds. During this interval, the router still
forwards multicast datagram through the port.
6 As usual, first capture the packet using tcpdump -w out put f ile, then open the output file using
ethereal.
7 The syntax of this command may be different for different versions of Cisco IOS. You may use “?”
to get help.
158 Multicast and realtime service
In the following exercise, we use jmstudio for video streaming. The routers
and hosts have the same configurations as in Fig. 7.14.
Exercise 14 Start jmstudio on all the hosts, by using jmstudio &.
On shakti, go to the jmstudio menu: File/Transmit .... In the “RTP Transmit”
dialog, chose file /home/guest/video/Hurr-Lili-Trailer.mpeg. Then click
the “next” button. In the next window, click the “next” button again. In the following
window, specify the multicast group address to be 224.123.111.101, with port
number 22224 and TTL 33. Then click the “Finish” button. Now the jmstudio on
shakti is transmitting the video clip using RTP/RTSP/UDP/IP to the multicast group
224.123.111.101 on port 22224.
On all other hosts, go to the jmstudio menu: File/Open RTP Session .... In the
following “Open RTP Session” dialog, specify the same group address, port number
and TTL as that used in shakti. Now you should see the received video is displayed
on the screen.
Execute tcpdump ip multicast -w ex14.out in one console to capture the multicast
datagrams. In another console, execute tcpdump ip multicast to monitor the capture
process. When you see some RTCP packets in the second tcpdump output, terminate
both tcpdump programs.
Use ethereal to load the ex14.out file. Analyze the header format of a RTP data
packet and a RTCP Sender (or Receiver) Report packet.
8 The Web, DHCP, NTP and NAT
8.1 Objectives
!
!
The HyperText Transfer Protocol and the Apache web server.
!
The Common Gateway Interface.
!
The Dynamic Host Configuration Protocol.
!
The Network Time Protocol.
!
The Network Address Translator and the Port Address Translator.
An introduction to socket programming.
1XX Informational 100: The server has received the first part of the request.
2XX Success 200: The request is successful and the response is returned in
the following message body.
3XX Redirection 300: Multiple choices.
4XX Client error 404: The requested file is not found.
5XX Server error 500: Internal server error.
! For an HTTP response, the requested file or other data follows the blank
line.
HTTP uses TCP for file transfers. Before an HTTP request, the client
first establishes a TCP connection to the server. After the HTTP response
is sent, the server may terminate the TCP connection. Many HTML files
have embedded objects, e.g., pictures, audio/video, or Java applets. When
an HTML file is received, the web browser parses the file to identify the
embedded objects, and then sends an HTTP request to the server for each
embedded object. For example, for an HTML file with two pictures, the
client sends three HTTP requests, with the first one for the original file and
the other two for the pictures. With HTTP/1.0, the client establishes a TCP
connection for each request. The TCP connection is terminated by the server
when transmission of the requested file (an HTML file or an embedded
object) is over. This may be inefficient when the HTML file has many
embedded objects, since TCP connection establishments and terminations
waste both network and server resources and introduce additional delays.
In HTTP/1.1, persistent connections are supported, where all the embedded
objects are sent through the TCP connection established for the first request.
In the example in Table 8.1, the persistent connection feature is enabled
162 The Web, DHCP, NTP and NAT
1 This means when a file is downloaded, it is likely to be downloaded again in the near future, by the
same or a different user.
163 8.2 The HyperText Transfer Protocol
3 An older protocol for this purpose is BOOTP, with which DHCP is backward compatible.
165 8.3 The Dynamic Host Configuration Protocol
t
Server 1
for the clients, i.e., a client can be assigned with the same set of parameters
whenever it bootstraps, or is moved to another subnet. The DHCP server
keeps a key-value entry for each client that should be configured statically
(e.g., an email or web server) and uses the entries to match queries from the
clients. The entry could be a combination of a subnet address and the MAC
address (or the domain name) of a client. DHCP can also assign configu-
ration parameters dynamically. In this case, the DHCP server maintains a
pool of parameters (e.g., a range of IP addresses) and assigns an unused set
of parameters to a querying client. A DHCP client leases an IP address for
a period of time. When the lease expires, the client may renew the lease,
or the IP address is put back to the pool for future assignments.
Figure 8.1 illustrates the operations of DHCP, where two DHCP servers
are used. These are the operations.
1. A client first broadcasts a DHCPDISCOVERY message on its local
physical network during bootstrapping. The message may be forwarded
by relay agents to servers in other physical networks.
2. Each server may respond with a DHCPOFFER message with an available
network address in the Your IP Address field.
3. The client may receive one or more DHCPOFFER messages. Then,
it chooses one server from all the responding servers based on the
configuration parameters offered, and broadcasts a DHCPREQUEST
message with the Server Identifier option to indicate the selected
server.
4. When the DHCPREQUEST message is received, only the chosen server
responds with a DHCPACK message carrying a full set of configuration
parameters to the client.
When the client receives this message, it checks the parameters and
configures its TCP/IP modules using the parameters. The message also
specifies the duration of the lease. When the lease expires, the client
may ask the server to renew it. If the server does not hear from the client
166 The Web, DHCP, NTP and NAT
0 8 9 15 16 23 24 31
Opcode Hardware Type Hw Add. Len. Hop Count
Transaction ID
Number of Seconds Flags
Client IP Address
Your IP Address
Server IP Address
Relay Agent IP Address
Client Hardware Address (16 bytes)
Server Hostname (64 bytes)
Boot Filename (128 bytes)
Options (variable)
beyond the expiry of the lease period, it will put the assigned address
back in the pool and may assign this address to other hosts.
5. The client may send a DHCPRELEASE message to the server to relin-
quish the lease on a network address.
Figure 8.2 shows the format of a DHCP message. The fields are listed
here.
1. Opcode: 1 means a boot request, and 2 means a boot reply. Every DHCP
message sent from a client has the boot request code (1). The boot reply
code (2) is written in every DHCP message sent from a server.
2. Hardware Address Type: The values of this field are defined in the
“Assigned Numbers” RFC. For an Ethernet MAC address, the value is 1.
3. Hardware Address Length: The length of the hardware address.
4. Hop Count: This is optionally used by relay agents when a host boots
via a relay agent. A relay agent is a host or router that forwards DHCP
messages between DHCP clients and servers.
5. Transaction ID: This is a randomly generated number used to
associate a query and response between a client and a server.
6. Number of Seconds: This is the number of seconds elapsed since
the client began the address acquisition or renewal process.
7. Flags: The leftmost bit is the Broadcast flag, while the remaining 15
bits are reserved for future use and must be set to zero. The Broadcast
flag is used in case that a client cannot receive a unicast IP datagram
before its interface is configured.
167 8.3 The Dynamic Host Configuration Protocol
1 default-lease-time 600;
2 max-lease-time 7200;
3 option subnet-mask 255.255.255.0;
4 option broadcast-address 128.238.66.255;
5 option routers 128.238.66.1;
6 #option domain-name-servers 128.238.2.38, 128.238.3.21;
7 #option domain-name “poly.edu”;
8
9 subnet 128.238.66.0 netmask 255.255.255.0 {
10 range 128.238.66.111 128.238.66.112;
11 }
12
13 host apah {
14 hardware ethernet 08:00:20:79:e9:9f;
15 fixed-address 128.238.66.110;
16 }
Stratum 1
Stratum 2 ...
... ...
Figure 8.3. The hierarchical strata structure of NTP time service.
170 The Web, DHCP, NTP and NAT
NTP daemon.
ntpd uses the /etc/ntp.conf configuration file and can be started as
an NTP server or an NTP client. Some frequently used entries in the
! peer host IP|host domain name: Specifies an NTP peer. ntpd can
to synchronize to.
operate in the peer mode, where multiple peers communicate with each
other to determine which one has the most accurate clock and synchronize
to this server.
NTP also uses several other configuration files in the /etc/ntp directory.
For example, the /etc/ntp/ntp.drift file contains the latest estimation
of the clock frequency error, called drift. ntpd keeps on monitoring the
171 8.4 The Network Time Protocol
frequency error and records the measured error in this file at hourly in-
tervals. ntpd also supports authentication using the /etc/ntp/keys file,
which stores keys and key IDs. The client and the server must have the
same key and key ID in their /etc/ntp/keys files in order to commu-
nicate with each other. These configuration files must be specified in the
/etc/ntp.conf file.
! rdate [options] remote host: Gets time from the network. The options
follow.
-P : Prints the returned time.
-s: Sets the current system time to the returned time.
-u: Uses UDP rather than TCP in the transport layer.
rdate uses the RFC 868 time server,4 with UDP and TCP port 37.
! ntptrace host: Traces time information back to the high stratum servers
! ntpdate [options] ntp server: Synchronizes the local clock with the re-
in the synchronization tree.
! ntpq: Queries the state of the NTP daemon on a local or remote host.
mote server once.
A Cisco router can also be configured to use NTP. For example, the
Global Configuration command ntp server NTP server IP specifies an
NTP server with which the router will synchronize to. The Global Config-
uration command ntp access-group controls access to NTP service on the
system.
4 The time and time-udp services should be enabled in the Linux machine in order to respond to a
rdate query, by chkconfig time on and chkconfig time-udp on, respectively.
In Solaris, the lines corresponding to time and time-udp services in the /etc/inetd.conf file
should be uncommented.
172 The Web, DHCP, NTP and NAT
The Internet
...
10.0.0.2 10.0.0.3 10.0.0.10
Figure 8.4. A NAT example.
association is released and the public address 128.238.4.12 is put back into
the pool for future use.
In the example, a pool of public IP addresses is dynamically shared by
all the internal hosts. NAT also supports static translation, where a private
address is persistently mapped to a public address. Static mapping is useful
for internal servers (e.g., an email server or a web server).
If there are many internal hosts in the private network sharing a small
number of public IP addresses, connections will be blocked when no free
public IP address is available. Port Address Translation (PAT) can be used
in this case to reduce the blocking rate. PAT extends the notion of translation
one step further by also translating transport identifiers, i.e., TCP and UDP
port numbers and ICMP query identifiers. With PAT, multiple internal hosts
can share a single public IP address, while different transport identifiers
are used to distinguish them. A NAT/PAT router translates both the source
IP address and the source port number of an outbound packet. Then the
router records the association of the private IP address and the public IP
address, as well as the internal source port number and the external source
port number. PAT is ideal for small offices or home networks that need to
have full Internet access at a low cost.
In addition to IP address reuse, there are several other advantages of using
NAT. With NAT, the structure of the private network is hidden. Moreover,
NAT can also be used with a firewall to filter undesired traffic, resulting
in better security. When the private network switches to a different ISP,
174 The Web, DHCP, NTP and NAT
only the public IP addresses (which were assigned by the original ISP)
need to be changed. The internal settings of the private network can remain
unchanged. This is useful for large private networks where the configuration
task would be time-consuming and error prone.
The disadvantage of using NAT/PAT is that the stub router may be con-
gested and become the performance bottleneck, since in addition to IP
address and port translations, the router has to recalculate the header check-
sums. Furthermore, ICMP error messages need to be handled carefully and
the ICMP payload may also have to be translated. NAT does not directly
support applications with interdependent control and data connections, e.g.,
H.323, RTP/RTCP, and FTP. Special application gateways are required to
support such applications.
Most of the applications discussed so far are implemented using the socket
Application Programming Interface (API). In this section, we will give a
brief overview of socket programming basics. For a more complete treat-
ment, see Stevens [12].
As shown in Fig. 8.5, the TCP/IP protocols are implemented in the
system kernel. User applications can use the TCP/IP service through the
socket API. In such applications, each participating process should create
a socket, containing the IP address of the host where the process is running
Network Layer: IP
Figure 8.5. The socket API provides an interface for the user processes to access the
TCP/IP services in the system kernel.
176 The Web, DHCP, NTP and NAT
and a unique port number. Then, the application process can use the socket
functions for sending or receiving data. There are three types of sockets for
applications to use. If reliable transport service is required, TCP sockets can
be used to create a TCP connection between the communicating parties.
Otherwise, UDP sockets can be used to provide datagram service. In addi-
tion, applications can also bypass the transport layer protocols by invoking
raw sockets to use the IP datagram service directly.
The client–server architecture is used in socket programming. A server
socket listens at a port, receives client requests, and provides the requested
service, while a client socket connects to the server socket to get the desired
service. In the lab exercise, we will write server and client programs using
TCP and UDP sockets. Some frequently used socket functions are listed
! socket(). Creates a new socket. You can specify which type of socket to
below.
create, e.g., for TCP sockets use type SOCK STREAM, while for UDP
! listen(). Makes the TCP server socket wait for incoming requests from
bind() bind()
bind() (optional) bind() (optional)
request
listen() connect()
grant
accept()
data data
send(), recv() send(), recv() send(), recv() send(), recv()
function, waiting for requests from TCP clients. A TCP client, on the other
hand, calls the connect() function to send a TCP connection request (a
SYN segment) to the TCP server. When the server receives the request,
it calls the accept() funtion to create a new socket locally, which serves
as the end point of the TCP connection on the server side. In other words,
the TCP server socket serves as a front-end, receiving incoming client
requests and creating the corresponding local sockets. Then, data can be
transmitted between the newly created socket on the server side and the
TCP client socket on the client side. If datagram sockets are used, there is
no need to set up or terminate the connection since UDP is connectionless.
Thus, after creating the sockets and calling bind(), the UDP client and
UDP server can directly exchange data by calling the send() or recv()
functions. When data transmission is over, both the server and the client
can call the close() function to terminate the connection (in the stream
socket case) and release the resources (e.g., port numbers and memory, in
both the stream and datagram socket cases).
The best way to learn programming, perhaps, is to read the source code
and try it out. Four examples of socket programs, namely UDPserver.c,
UDPclient.c, TCPserver.c, and TCPclient.c, are given in Ap-
pendix C.4. Moreover, the netspy and netspyd programs used in Chapter 7
are multicast socket programs and the source code is given in Appendix C.2.
To compile a socket program, e.g., TCPclient.c, use:
gcc -o TCPclient TCPclient.c -lnsl
178 The Web, DHCP, NTP and NAT
For the exercises in this section, the network topology is given in Fig. 1.3,
where all the hosts are connected to a single network segment using their
default IP addresses, i.e., from 128.238.66.100 to 128.238.66.107.
Exercise 1 Study the Apache server configuration file (see Section 8.2.3). Examine the various
configuration directives used and the corresponding settings.
Start the Apache server on your host. In order to check if the server is working
properly, you may start a Mozilla web browser to download the test page at
http://localhost/.
Then, execute pgrep httpd to list the process IDs of the httpd processes started.
Save the output and the configuration file for the lab report.
LAB REPORT How many httpd processes were started? Which one was the master
server, and which ones were the child servers? Justify your answer using
the httpd.conf file.
What is the purpose of initiating multiple httpd processes?
Exercise 2 Execute tcpdump host your host and remote host -w ex3.out to capture packets
between your host and a remote host.
Login to the remote host’s web server: telnet remote host 80.
In the login console, type the following HTTP request line by line:
Note that you need to type the Return key to input the last line, which is blank.
When the telnet process is terminated, save the output for your lab report.
Terminate tcpdump. Use ethereal to load the ex3.out file and analyze the captured
HTTP packets. Print and save the HTTP request and response.
179 8.7 HTTP exercises
Save the HTTP response’s data part into a file, named ex3.html. Use Mozilla to
view the file.
LAB REPORT Submit the HTTP request and response, including the start-lines and all
the headers.
Exercise 3 By default, Apache server supports persistent connections. Before this exercise,
the lab instructor should check the KeepAlive directive in the server configuration
file to make sure it is turned on, as KeepAlive on.
Execute tcpdump host your host and remote host -w ex4a.out to capture packets
between your host and a remote host.
Start Mozilla on your host. Go to menu Edit/Preferences /Advanced/HTTP
Networking, and uncheck the Enable Keep-Alive checkbox to disable persis-
tent connections.
Enter the URL http://remote host/try1.html, to download the HTML file con-
sisting a line of text, an embedded picture, and a hyperlink.
Use ethereal to load the ex4a.out file, and print the HTTP requests and responses
for the lab report.
Restart the tcpdump program, but dump the output to a ex4b.out file.
Go to Mozilla menu Edit/Preferences/Advanced/HTTP Networking, and en-
able persistent connections by checking Enable Keep-Alive.
Use Mozilla to reload the try1.html file.
Use ethereal to load the ex4b.out file, and print the HTTP requests and responses
for the lab report.
LAB REPORT When you browsed the try1.html file for the first time, how many
HTTP requests were sent? Which files were requested? How many TCP
connections were used?
Answer the above questions for when you browsed the try1.html file for
the second time.
What is the purpose of using persistent connections?
Exercise 4 Execute tcpdump host your host and remote host -w ex5.out to capture packets
between your host and a remote host.
Use Mozilla to download the http://remote host/try2.htm file, which is an
HTML form, from the remote host.
Fill a text string, e.g., the name of the host being used, into the text field in the form
and click the submit button in the form.
180 The Web, DHCP, NTP and NAT
For the exercises in this section, we use the same network setting as the
one used in the previous exercises.
Exercise 5 In this exercise, we use guchi as the DHCP server, with a configuration file shown
in Table 8.3. Do the following.
1. Start the DHCP server on guchi in the foreground and working in the debugging
mode: /usr/sbin/dhcpd -d -f.
2. Execute tcpdump -exn -nn -s 100 -w exdhcp.out to capture the DHCP messages
in the network segment.
3. Then do the following to enable DHCP for the Ethernet interface on shakti.
Go to the system menu: System Settings/Network. In the Network
Configuration dialog, choose the Device tab, and click on the eth0 item.
Next, click the Edit button to bring up the Ethernet Device dialog. In this di-
alog, check Automatically obtain IP address settings with and se-
lect dhcp from the following drop list. When the configuration is done, save the
new configuration and then execute /etc/init.d/network restart to load the new
configuration.
When shakti is successfully reconfigured, execute ifconfig -a to display its
network interface configurations and execute netstat -rn to display its routing
table. Save the outputs for the lab report.
4. Then, repeat 3 for vayu.
5. Repeat 3 for agni.
6. Repeat 3 for apah.
Terminate tcpdump. Use ethereal to load the exdhcp.out file. Print out the DHCP
messages for the lab report.
Save the DHCP server output on guchi for the lab report.
LAB REPORT Compare the DHCP operation captured by tcpdump and that shown by
the DHCP server output. Explain how DHCP works.
Did shakti and vayu successfully obtain a set of new parameters? Com-
pare the ifconfig and netstat output with the parameters carried in the
corresponding DHCP messages.
181 8.9 NTP exercises
Answer the above question for agni. Explain why agni failed.
Answer the above question for apah. Explain why apah succeeded.
Before proceeding to the next exercise, reboot the hosts to restore their
original configurations.
Exercise 6 Execute date to display the system time of your host. Display the manual page of
date, and study its options and usages.
Try the following date commands:
date −−date=‘2 days ago’
date −−date=‘3 months 2 days’
date −−set=‘+3 minutes’
date −r file name
You can choose any file in the current directory for the file name parameter. Save
the outputs of the above commands.
LAB REPORT Submit the date outputs you saved. Explain the use of the commands.
Exercise 7 While tcpdump -n -nn -ex host your host and remote host is running, execute
rdate -p remote host to display the system time of the remote machine.
Repeat the above rdate command, but use the -u option.
Save the tcpdump outputs for the lab report.
LAB REPORT What port numbers were used by the remote machine? What port num-
bers were used by the local host?
How many bytes of data were returned by the remote time server, both in
the UDP case and in the TCP case?
What TCP header options were used?
182 The Web, DHCP, NTP and NAT
Exercise 8 In this exercise, we start the NTP server daemon on shakti and use NTP to
synchronize all the other hosts to shakti.
Study the NTP configuration file /etc/ntp.conf in shakti and in your host.
If you are using another machine, you can telnet to shakti and display the
/etc/ntp.conf file in the telnet window.
Start the NTP server on shakti by: /etc/init.d/ntpd start. To determine the status
of the NTP server, use /etc/init.d/ntpd status.
Use tcpdump -ex -n -nn host your host and shakti to capture packets between your
host and shakti.
Execute ntpdate -d -v 128.238.66.100 to synchronize your host to shakti. Study
the output of this command.
Save the ntpdate and the tcpdump outputs for the lab report.
LAB REPORT Which port does the NTP server use? Justify your answer using the
tcpdump output.
Exercise 9 Keep the NTP server running on shakti. Execute tcpdump -exn -nn host your host
and 128.238.66.100 -w ex9.out to capture the NTP messages between your host
and shakti.
Start the NTP clients on your host, by /etc/init.d/ntpd start.
Wait for several minutes. Then terminate the tcpdump program. Use ethereal to load
the ex9.out file. Analyze the captured NTP packets. Print one of the NTP packets
for the lab report.
Execute ntptrace to show the client/server relation of NTP.
LAB REPORT Submit the NTP packet captured. List the fields and their values.
What was the rate at which NTP queries were sent by the client?
Which stratum was your host in? Which stratum was the NTP server in?
interface ethernet 0
ip address 128.238.61.1 255.255.255.0
ip nat outside
interface ethernet 1
ip address 10.0.0.1 255.0.0.0
ip nat inside
access-list 8 deny host 10.0.0.7
access-list 8 permit 10.0.0.0 0.0.0.255
128.238.61.100/24 128.238.61.101/24
shakti vayu
The Internet
eth0 128.238.61.1/24
router 1
add a default route in your host’s routing table, using the router interface on your
subnet as the default router.
One student should telnet to the router and configure the router as shown in
Table 8.5. Note that there is a static translation that maps 10.0.0.7, or guchi, to
128.238.61.104.
Login to the router, execute write term to display the current router configura-
tion. Execute show ip nat translations in the Privileged EXEC mode to display the
translation table. Save both outputs for the lab report.
LAB REPORT How many entries were there in the translation table? Why?
Exercise 11 Keep the login session to the router running. Execute tcpdump -exn -nn on all
the hosts.
184 The Web, DHCP, NTP and NAT
Before any host in the private network send any packets out, ping an inside host
(e.g., fenchi) from an outside host (e.g., vayu). You may try to ping 10.0.0.5,
128.238.61.102, 128.238.61.103, or 128.238.61.104. Can you ping these IP ad-
dresses?
Let an inside host send packets to an outside host, e.g., from fenchi, execute ping
128.238.61.100. Can you ping fenchi from an outside host now? Why? Which IP
address should be used in the ping command in order to ping fenchi?
Execute show ip nat translations in the router login window to display the translation
table. Save the output for the lab report.
Exchange the data you saved with a student in the other subnet.
LAB REPORT Answer the above questions. Use the saved translation table to justify
your answers.
Compare the IP header of the ICMP query captured in the private network
with that of the same ICMP query captured in the upper subnet, list their
differences. Explain how NAT works.
In addition to the IP address, what else was changed in the ICMP query
packet?
Exercise 12 Keep the login session to the router running. Execute tcpdump -enx -s 100 ip
proto 1 -w exc.out to capture ICMP messages.
Execute sock -i -u -n1 128.238.61.101 8888 on agni to generate an ICMP port
unreachable error.
Use ethereal to load the exc.out file. Print the ICMP error message for the lab
report.
Execute show ip nat translations in the router login window to display the translation
table. Save the output for the lab report.
Exchange the data you saved with a student in the other subnet.
LAB REPORT Analyze the IP headers, the ICMP headers, and the ICMP payloads of
the ICMP port unreachable errors captured in the private network and in
the public network from the first experiment. Explain how ICMP error was
handled by the NAT router.
Exercise 13 Reboot the router to restore its default configuration. Then, configure the router
to use PAT, as given in Table 8.6. Now all the hosts in the private network use the
same IP address 128.238.61.1. However, note that there is a static translation that
maps guchi’s port 80 to 128.238.61.1 port 80.
185 8.11 Socket programming exercises
LAB REPORT From the tcpdump data, explain how PAT worked, both for a dynamic
translation and a static translation.
With PAT, can you have two web servers in the private network? If not,
why? If yes, explain how this can be done.
On the remote host, start the UDP server by UDPserver server port. Then, start the
UDP client on your host by UDPclient remote host server port a message. You may
execute the UDP client program on other hosts to connect to the same UDP server.
Terminate tcpdump, examine its output and compare the output with the UDP server
and client outputs.
Repeat the above experiments, but now use the TCPserver.c and TCPclient.c.
Exercise 15 Execute man setsockopt to display the various socket options and how to set
them.
Examine the netspy and netspyd souce code in Appendix C.2 to see how to create
a multicast socket and how to set the TTL value for the packets.
PROBLEM Examine the message exchanges of FTP. Write a FTP client program which
takes a file name as input, and upload the file to a standard FTP server on
a remote machine.
! First you need to set up the control connection to Port 21 of the remote
HINTS
! You can first run telnet remote host 21, then type help to list all the FTP
commands with the remote FTP server, as given in Table 5.1.
commands. Also, you can try the commands out in the telnet window,
e.g., use USER guest to send the user ID and PASS guest1 to send the
! Also your program needs to parse the server responses (some examples
calling the send() function of the local TCP socket.
! The FTP data connection should be established using the PORT com-
are given in Table 5.2) to find out the status of the previous FTP command.
9.1 Objectives
! SNMP and MIBs, using NET-SNMP as an example, and using NET-
! Transport layer security, including SSL and the secure Apache server.
! Network layer security, IPsec and Virtual Private Networks.
! Firewalls and IPTABLES.
! Accounting, auditing, and intrusion detection.
UDP/162
! GetNext. Fetches the value of the next object after the specified object.
! Set. Sets the value of one or more objects.
! Response. Returns the value of one or more objects.
! Trap. Reports the occurrence of some significant events on a managed
ble given the constraint on message sizes. It is used to minimize the num-
ber of protocol message exchanges required to retrieve a large amount
189 9.2 Network management
! Community Name. Defines the access scope for SNMP managers and
uration capabilities.
! Request ID. This field is used to match an SNMP request with the
type.
root
dod(6) ...
1.3.6.1 internet(1) ...
...
mib-2(1) 1.3.6.1.2.1 enterprise(1)
system(1) interfaces(2) at(3) ip(4) icmp(5) tcp(6) udp(7) ... 1.3.6.1.4.1.9 cisco(9)
9.2.3 NET-SNMP
NET-SNMP, formerly known as UCD-SNMP, is a very popular public
domain SNMP implementation consisting of an extensible SNMP agent, a
set of tools to request or set information from SNMP agents, a set of tools
to generate and handle SNMP traps, and an SNMP API library for writing
SNMP related programs. NET-SNMP is included in the Red Had Linux 9
installation CDs.
The SNMP MIBs are stored in the /usr/share/snmp/mibs directory.
The SNMP agent daemon uses the /etc/snmp/snmpd.conf configuration
file, where the community name and many other configuration options may
be set. The SNMP agent daemon snmpd is controlled by:
/etc/init.d/snmpd start|stop.
If snmpd is started, MIB objects can be accessed by the following tools
! snmpget: Retrieves management data from a remote host, given the do-
included in the NET-SNMP package.
main name or IP address of the remote host, the MIB object ID, and
the authentication information (e.g., the community name). For exam-
ple, the following command prints the time elapsed since host shakti
was started, using the community name test:
! snmpgetnext: Retrieves the value of the object with the next object ID.
snmpget -c test -v 2c shakti.poly.edu system.sysUpTime.0.
Message Message
Network
Key Key
Encryption Decryption
Attacker
Figure 9.4. The network security model.
193 9.4 Encryption, confidentiality, and authentication
F F F
w w
R1 ... Ri ... Rn
R n+1
K1 Ki Kn
Figure 9.6. The classical Feistel network.
ciphers, where the same key is used for encryption and decryption, and
public-key ciphers, where a private key is used for encryption and a public
key is used for decryption, or vice versa. The effectiveness of the encryption
schemes depends on the keys. The longer a key is, the more difficult it is
to decrypt the ciphertext by brute force. Furthermore, in an open network
environment with many servers and clients, any client may request service
from any server. For each of the client/server connections, one or more keys
may be needed. This requires keys be generated and distributed efficiently
and reliably.
Most block ciphers can be characterized by the Feistel network model
[13], as shown in Fig. 9.6. In this model, a 2w bit plaintext block is encrypted
into a 2w bit ciphertext block. The Feistel network consists of a number
of identical blocks (called rounds) concatenated in a chain. The plaintext
is first divided into two w-bit blocks, L 1 and R1 , and fed into the first
round. Each round i takes the outputs of the previous round, L i and Ri ,
as inputs. The right half of the input data, Ri , is first processed with a
round function F, using a secret key K i . The round function F performs
bit operation on the input block and the key, e.g., permutation, expansion,
and exclusive-OR. Then the exclusive-OR (denoted as ⊕ in Fig. 9.6) of the
left half of the input data, L i , and the output of F is computed. The output
of the operation is switched with Ri and fed into the next round. The same
Feistel network is used to decrypt the ciphertext, with the keys applied in
a reversed order, i.e., K n is used in round 1, K n−1 is used in round 2, and
so on so forth.
The Data Encryption Standard (DES) is the most widely used encryption
standard. DES is a block-based cipher with 16 rounds, 64-bit blocks, and
56-bit keys. With DES, the 56-bit key is fed into a key generating module
which computes 16 48-bit subkeys, one for each round. The strength of DES
is the so called Avalanche Effect, where a small change in the plaintext or
195 9.4 Encryption, confidentiality, and authentication
the 56-bit key produces a significant change in the ciphertext. This makes
the ciphertext difficult to decrypt by brute force. Since the same keys are
used in the encryption and decryption, DES is a symmetric cipher.
In 1998 the Electronic Frontier Foundation broke DES using a specially
developed computer called the DES Cracker at a cost under $250,000.
Thereafter, Triple DES (3DES) was designed to provide stronger security.
3DES uses the same DES encryption, but repeats it three times. 3DES uses
three 64-bit keys, resulting in a dramatic increase in cryptographic strength.
The Advanced Encryption Standard (AES) was developed to replace DES.
AES uses the Rijndael algorithm, which is also a multiple-round, block-
based cypher, but is not based on a Feistel network [14].
Alice, he can encrypt the message using his own private key. When Alice
receives this encrypted message from Bob, she can decrypt the message
using Bob’s public key. In this example, all other users can decrypt the
message since Bob’s public key is known to all. However, Alice knows
that the message can only be sent by Bob, since only Bob knows his own
readable by other users, he can encrypt the message using Alice’s public
key. Alice can decrypt the message using her private key. Since no one
else knows Alice’s private key, the message is indecipherable to all other
crypt the message using Alice’s public key (this ensures only Alice can
decrypt the message), and then further encrypt the ciphertext with his pri-
vate key (this guarantees the message is from Bob). When Alice receives
this message, she first decrypts the message using Bob’s public key, then
decrypts the results using her private key.
196 Network management and security
Padding 10...0
encrypted tunnel into several logical channels. SSH will replace traditional
remote access protocols, such as Rlogin, Telnet, FTP, and Remote Shell
(Rsh), where security was not a major design objective. SSH supports al-
most any kind of public-key algorithm and various types of authentication.
The SSH client and server use digital signatures to verify their identity. All
communication between the client and server is encrypted.
The OpenSSH suite is a public domain implementation of the SSH proto-
cols, including ssh, scp, and sftp. OpenSSH also includes the SSH daemon
sshd, the secure FTP daemon sftp-server, and other basic utilities. Both
Linux and Solaris platforms are supported. The OpenSSH daemon uses the
/etc/ssh/sshd config file for configuration, and can be turned on or
off by:
/sbin/service sshd start|stop.
There are multiple OpenSSH clients, one for each remote access service.
! ssh: A secure client for logging into a remote machine and executing
The following are the client programs.
commands there. For example, to login into shakti as user guest, use:
! scp: A secure client for copying files between hosts. For example, to
ssh [email protected].
9.5.2 Kerberos
Kerberos is a network authentication protocol developed by the MIT Project
Athena team, which uses symmetric key encryption for authenticating users
for network services. Kerberos uses a trusted Authentication Server and a
Ticket-Granting Server (TGS) to provide two types of tickets to a user:
a ticket-granting ticket and one or more service-granting tickets, one for
each network service. More specifically, Kerberos works in the following
way.
200 Network management and security
As discussed in Section 8.2, the HTTP requests and responses are sent as
plaintext. However, in some situations, e.g., financial transactions, extra
security for the web service is needed. Web security can be provided in
different ways by: (1) using the application layer security protocols, such
as Kerberos; (2) using the Secure Sockets Layer (SSL) in the transport layer;
and (3) using IP security (IPsec) in the Network Layer. In this section, we
discuss the SSL protocol and the secure Apache server. We will discuss
IPsec in the next section.
TCP
IP
Data
MAC
SSL consists of four protocols: the SSL Handshake Protocol, the SSL
Change Cipher Spec Protocol, the SSL Alert Protocol, and the SSL
Record Protocol, as shown in Fig. 9.8. All higher layer messages, including
the messages used in the first three SSL protocols, are encapsulated in SSL
records which are defined in the SSL Record Protocol. The SSL record
header consists of an 8-bit Content Type field, an 8-bit Major Version field,
an 8-bit Minor Version field, and a 16-bit Compressed Length field, as shown
in Fig. 9.9. The SSL record data section consists of a Message Authenti-
cation Code (MAC) (see Section 9.4.3), the actual data, and the possible
padding bytes. When a higher layer message arrives, it is first fragmented
to fixed length blocks (padding may be inserted). Each block may then be
compressed. The MAC is computed using the possibly compressed data, a
secret key, and a 32-bit long sequence number using a hash function.
Then, the data and the MAC are encrypted and the SSL record header
is appended.
SSL can negotiate an encryption algorithm and session key, as well
as authenticate for the secure connection. The SSL Handshake Protocol
is used for the client and server to authenticate each other, to negotiate an
encryption algorithm and a MAC algorithm, and to exchange the encryption
202 Network management and security
keys. The SSL Change Cipher Spec Protocol is used to update the set of
ciphers to be used on this connection. The SSL Alert Protocol is used to
deliver SSL-related alerts to the peer entity.
The Internet
key management, are performed at the two IPsec-capable devices and are
transparent to the users. There is no need to change or configure the hosts
or the programs running in the hosts for the security service. The network
shown in Fig. 9.10 is also called a Virtual Private Network (VPN). Com-
pared with traditional approaches that use a leased line to connect the office
networks, VPN provides good security at a lower cost.
IPsec uses two protocols to provide security: (1) an authentication
protocol that uses an Authentication Header (AH), and (2) an encryp-
tion/authentication protocol, called the Encapsulating Security Payload
(ESP), that encrypts the higher layer data and provides an optional au-
thentication service. Both AH and ESP support two modes of operation:
the transport mode and the tunnel mode. The Transport mode provides
protection for upper-layer protocols. As shown in Fig. 9.11, the origi-
nal IP header is untouched, while the remaining part of the IP datagram
is either authenticated by AH, or encrypted and authenticated by ESP.
The transport mode is usually used for end-to-end communication be-
tween two hosts. The tunnel mode protects the entire IP datagram. As
illustrated in Fig. 9.11, a new IP header is used to route the packet,
while the original IP datagram, including its header and data, are au-
thenticated or encrypted. For the example in Fig. 9.10, a tunnel is es-
tablished between the two IPsec gateways. An outbound IP datagram is
first encrypted or authenticated, then encapsulated and forwarded in a
new IP datagram. When the new IP datagram arrives at the destination
network’s IPsec gateway, the new header is stripped and the original IP
datagram is decrypted and restored. Recall that in the MBone, similar
tunnels are used to route multicast IP datagrams between two multicast
islands.
205 9.8 System security
encrypted
authenticated
encrypted
authenticated
Figure 9.11. Encapsulation of an IP datagram using the IPsec authentication header and
encapsulating security payload.
9.8.1 Firewalls
A firewall is a device or program inserted between a private network and
the Internet to control access. A firewall can be used to block undesired
traffic from the outside, or to prevent an internal user from receiving an
unauthorized external network service.
Usually the firewall is the only access point of a private network, i.e.,
all outbound traffic from the private network should be routed through the
firewall in order to enforce the desired access control. There are three types
of firewalls. A packet filter blocks selected network packets. An application
gateway, or a proxy server, is mainly used to regulate outbound traffic. A
proxy server acts as a relay for a specific application (e.g., web service). The
206 Network management and security
traffic between the internal client and the remote server (e.g., HTTP requests
and responses) is relayed by the proxy server. A circuit-level gateway acts
like a switch board, switching an internal connection to another external
connection.
9.8.2 iptables
Packet filtering is built into the Linux kernel. The default firewall in Linux
kernel 2.4 is the iptables (also called the netfilter). A firewall policy, also
called a rule, consists of two components: a condition (e.g., destination port
number of a packet) and the operation (called the target) on the packets
that satisfy the condition (e.g., drop). In Linux, rules are organized into
three tables, based on the operations to be performed. The filter table is the
default table for filtering packets. The nat table is used to alter packets that
create a new connection, while the mangle table is used for some specific
types of packet alteration. In each table, rules are further organized into
several chains, based on the type of packets they regulate. For example,
the filter table has three chains: the INPUT chain which consists of the
rules applied to the packets destined to the host, the OUTPUT chain which
consists of the rules applied to the packets generated by the host, and the
FORWARD chain which consists of the rules applied to the packets routed
by the host (when the host is configured to be a router).
In iptables, a packet is first dispatched to the corresponding chain. Then
the packet is checked against each rule in that chain, one at a time. If there is
a match, the target defined in that rule is performed on that packet. Rules in
the tables are configured by running the iptables command, which defines
the packet type and the corresponding target. The syntax of iptables is:
iptables [-t table-name] command chain-name parameter1 option-1 . . . \
parameterN optionN
The table-name could be filter, nat, or mangle. Commands indicate what
kind of application to perform on the table, e.g., -A means appending the
rule to the end of the specified chain and -F flushes the selected chain (i.e.,
deletes all the rules in that chain). The next parameter, chain-name is the
name of the chain to configure, i.e., INPUT, OUTPUT, or FORWARD in
the filter table. Next is a list of parameters and options, which defines the
a packet.
207 9.8 System security
! -p: indicates the IP protocol for the rule, which could be icmp, tcp, udp
or all.
! RETURN. Stops checking the packet against the rules in the current
cation.
For the exercises in this section, the network topology is given in Fig. 1.3,
where all the hosts are connected in a single network segment using their
default IP addresses, i.e., from 128.238.66.100 to 128.238.66.107.
Before the lab, the lab instructor should:
1. Backup the original snmpd configuration file:
mv /etc/snmp/snmpd.conf /etc/snmp/snmpd.conf.save.
2. Create a simple configuration file /etc/snmp/snmpd.conf with a sin-
gle line defining a read-only community guest:
rocommunity guest
Exercise 1 Use pgrep snmpd to check if snmpd is started. Try to stop and then start the SNMP
agent daemon using /etc/init.d/snmpd start|stop.
Study the snmpd configuration file /etc/snmp/snmpd.conf. Also study the default
configuration file /etc/snmp/snmpd.conf.save. This file is well commented.
Read the comments and study the configuration options.
Study the MIB files in the /usr/share/snmp/mibs directory. Examine the Interface
MIB IF-MIB.txt and the TCP MIB TCP-MIB.txt to see the MIB objects and data
types. Save these two files for the lab report.
LAB REPORT What is the community name used in this lab? What is the use of the
community name?
What is the data type for the MIB object ifMtu.2? What is the definition
of the MIB object ifPhysAddress and ifInOctets?
What is the data type and definition of tcpRtoAlgorithm? What values are
allowed for tcpRtoAlgorithm? What is the definition of tcpMaxConn?
Exercise 2 Use snmpwalk -v 2c -c guest localhost interface to display the Interface MIB.
Use snmpwalk -v 2c -c guest localhost tcp to display the TCP MIB.
You may run man snmpwalk to find out the meanings of the options used in the
commands. Compare the outputs with the MIB files you saved in the previous
exercise. Also compare the outputs of the first command with that of ifconfig -a.
Retry the snmpwalk commands, but change guest to public. Can you display the
MIBs this time?
LAB REPORT What is the MTU of the Ethernet interface? What is the MTU of the
loopback interface? Justify your answer with the snmpwalk output and the
netstat output.
Why did the snmpwalk command with a community name public fail?
Exercise 3 Execute tcpdump udp port 161 -w ex3.out to capture SNMP messages.
Execute snmpget -v 2c -c guest remote host IF-MIB::ifMtu.1 to get the MIB object
IF-MIB::ifMTU.1 from a remote machine.
Save the snmpget output and terminate tcpdump.
Use ethereal to load the ex3.out file and analyze the format of the captured SNMP
Get and Response messages. Print the messages for the lab report.
LAB REPORT What is the port number used by the SNMP agent?
What are the full text-based and numerical object ID’s of the MIB object
interface.ifMTU.2? What was the value returned? Justify the answer
using Fig. 9.3 and the ifconfig output.
Draw the format of one of the SNMP messages saved, including the name
and value of each field.
Exercise 4 Execute tcpdump -enx -s 100 -w ex4a.out host your host and remote host to
capture packets between your machine and a remote machine.
Execute ftp remote machine. When prompted, type “1111” for the login ID, and
“2222” for the login password. Then terminate tcpdump and ftp.
Use ethereal to load the ex4a.out file. Analyze and print the packets that carry the
login ID and the password for the lab report.
Repeat the above experiment, but use telnet and save the tcpdump output in the
ex4b.out file.
210 Network management and security
LAB REPORT Can you see the login ID and the password in the FTP experiment?
Submit the two packets you printed.
Can you see the login ID and the password in the TELNET experiment?
Submit the packets you printed.
What is the difference between FTP and TELNET in their transmission of
user ID’s and passwords? Which one is more secure?
Exercise 5 Execute tcpdump -enx -s 100 -w ex5a.out host your host and remote host to
capture packets between your machine and a remote machine.
Execute sftp remote machine. When prompted, type “yes” to continue the connec-
tion and “1111” for the login password. Then terminate tcpdump.
Use ethereal to load the ex5a.out file. Analyze and print one or two SSH packets
for the lab report.
Repeat the above experiment, but use ssh and save the tcpdump output in the
ex5b.out file.
LAB REPORT In each experiment, can you extract the password from the tcpdump
output? Can you read the IP, TCP, SSH headers? Can you read the TCP
data?
What is the client protocol (and version) used in both cases?
What is the port number used by the ssh server? What is the port number
used by the sftp server? Justify your answer using the tcpdump output and
the /etc/services file.
In the exercises in this section, teams of two students work together using
two workstations.
Exercise 6 Run man openssl to study the OpenSSL command line tool.
Create a new private key for the Apache server, using:
openssl genrsa 1024 > /etc/httpd/conf/ssl.key/server.key.
To create a self-signed certificate, go to the /etc/httpd/conf directory, and ex-
ecute: make testcert.
Then you will be asked a number of questions, regarding the location, affiliation,
etc. of the Apache server. After you type in the answers, a self-signed certificate is
created at /etc/httpd/conf/ssl.crt/server.crt.
211 9.12 Exercises on Firewalls and Iptables
Exercise 7 Restart the Apache server to load the new key and the new certification:
/etc/rc.d/init.d/httpd restart.
Execute tcpdump -w https.out host your host and remote host to capture the pack-
ets between your host and a remote host.
On the remote host, start the Mozilla web browser. After typing in the URL
https://your host, a dialog window titled “Website Certified by an Unknown
Authority” will pop up, reporting the reception of a certificate signed by an unknown
authority and asking if you want to continue.
Click the “View Certificate” button. Then a “Certificate Viewer” window pops up,
displaying detailed information about the received certificate. Examine the certificate
and dump the window into a picture if necessary (see Section 1.3.3 on how to dump
a window). Save the pictures for the lab report.
Click the “Continue” button in the “Website Certified by an Unknown Authority”
dialog window to accept the certificate. Then terminate tcpdump and Mozilla.
Use ethereal to load the https.out file and examine the operation of SSL.
LAB REPORT What is the port number used by the secure Apache server?
Compare the general information of the received certificate with the make
output saved in the last exercise. Are they consistent?
What is the Subject of the received certificate? Who is the Issuer of this
certificate? Are they the same?
What is the Certificate Signature Algorithm used to generate and
distribute this certificate?
When was the certificate signed? When will it expire?
Exercise 8 Execute iptables -L -v to list the existing rules in the filter table. Save the output
for the lab report.
Append a rule to the end of the INPUT chain, by executing
iptables -A INPUT -v -p TCP −−dport 23 -j DROP.
Run iptables -L -v again to display the filter table. Save the output.
212 Network management and security
On both machines in your group, execute tcpdump host your host and remote host.
Then, telnet to the host where the rule is set from the remote machine. Save the
tcpdump output for the lab report.
LAB REPORT Can you telnet to the host from the remote machine?
From the tcpdump output, how many retries did telnet make? Explain the
exponential backoff algorithm of TCP timeout and retransmission.
LAB REPORT Explain the difference between the tcpdump outputs of this exercise
and the previous exercise. How many attempts did TCP make this time?
Exercise 10 Start the graphical interface tool redhat-logviewer to examine the log files in your
host. If a log (e.g., the Apache Access Log) is too long, type a keyword (e.g.,
GET) in the “Filter for” field to display those log entries containing the keyword.
Enter the keyword “failed” to display logged failures.
Go to menu Edit/Preferences ... to see where the log files are stored.
Exercise 11 Red Hat Linux uses a utility called Webalizer to analyze the web server log files.
Webalizer reads the Apache log files and creates a set of web reports on server
statistics. It is pre-installed in Red Hat Linux 9.
To view the reports, start Mozilla and enter the URL http://localhost/usage/
index.html. Examine the web statistics displayed in the browser. Also click on
the month links in the Summary by Month table to see the statistics of each
month.
Next, enter the URL http://remote host /usage/index.html to view the reports
on the remote machine.
213 9.13 Exercises on auditing and intrusion detection
LAB REPORT List the most frequently visited pages at the local Apache server and
the remote Apache server during the most recent month, respectively.
List the web pages that have the most number of bytes transferred by the
local and the remote server during the most recent month, respectively.
Exercise 12 Execute netstat -l to display the listening sockets in your host.
Execute chkconfig −−list to list the services in the /etc/init.d/ directory and
their status. Save the output for the lab report.
References
214
215 Further reading
14. National Institute of Standards and Technology, Announcing the Advanced Encryption
Standard (AES), Federal Information Processing Standards Publication 197, November
2001.
Further reading
Finally, after years of working with network programming, I came to realize that
80% of all network programming problems were not programming problems at
all, but were from a lack of understanding of how the protocols operate.
I also realized that (there) were numerous publicly-available tools out there that
aid in understanding the protocols and anyone could use them, when shown how.
W. Richard Stevens
To the Internet
gateway 91234
apah agni vayu shakti
R1
R2
HUB
R3
yachi fenchi kenchi guchi
R4
Eth1 Eth2
8765
1. Eight1 desktop PCs with the Red Hat Linux 9.0 (or a later version)
operating system, each with an Ethernet interface card.
You can also set up the TCP/IP lab with eight Workstations with the Solaris
8 (or a later version) operating system, each equipped with an Ethernet
interface card.
2. Four1 Cisco 2600 series routers with Cisco IOS release 12.0. Each router
has two Ethernet interfaces and a console port for local configurations.
These routers will be configured to work as bridges in Chapter 3, and as
routers in Chapters 2, 4, and 5, respectively.
3. Eight Ethernet Hubs. These hubs are used to build Ethernet LAN seg-
ments with the star topology. Each hub should have at least four ports.
In some exercises, more ports are required to connect all the hosts (and
some router ports) to form a single LAN segment. In these cases, two or
more hubs could be concatenated to extend the number of ports.
4. A number of Ethernet Cables. We use 10 Base-T cables with RJ-45
connectors. In addition, a RJ-45-to-RJ-45 crossover cable and a RJ-45-
to-DB-9 adapter are needed in order to configure a router through the
console port. These generally come with a new router.
Figure. A.1 is an overview of the lab equipment. As shown in the figure,
we name the computers and the routers for easy exposition. The routers
and hubs are installed on a rack at one end of the room. The computer
1 We used eight workstations in our lab. However, a minimum setup consisting of five workstations
and two routers is needed (see Section A.4).
219 A.3 Software installation and configuration
1 shakti 128.238.66.100
2 vayu 128.238.66.101
3 agni 128.238.66.102
4 apah 128.238.66.103
5 yachi 128.238.66.104
6 fenchi 128.238.66.105
7 kenchi 128.238.66.106
8 guchi 128.238.66.107
named gateway is used for Internet access, which is optional and will be
discussed in section A.6.
This guide focuses on the Internet protocols rather than specific products.
In the experiments, we try to avoid the proprietary aspect of the hardware
and the operating system used. With minimal modifications, this guide can
be used with other systems, e.g., PCs with the Mandrake Linux or the
FreeBSD operating system.
Installing Solaris 8.0 is similar to the above. Basically, you can use all the
default settings for each installation step. When the installation finishes,
you need to create a new user named guest with a password of guest1,
and set the PATH environment for guest.
To enable the above services in Solaris, you need to edit the
/etc/inetd.conf file. Make sure that the lines corresponding to these
services are uncommented. Then reboot the machine, or run pkill -HUP
inetd to let inetd reload the new configuration.
3 You can enable these services using the graphical configuration tool as well. Invoke the system
menu by clicking the Red Hat logo at the lower left corner of the workspace. Then go to /System
Settings/Server Settings/Services as root. A dialog pops up with a list of services available
from this host. You need to simply select the services you want to enable, e.g., Telnet, then reboot
the computer.
221 A.3 Software installation and configuration
sock
Sock is a network traffic generator written by W. Richard Stevens. It can be
downloaded from W. Richard Stevens’ homepage: ftp://www.kohala.
com/start/unpv12e.html. You can download the source code package
and build the sock program locally. The README file coming with the pack-
age gives detailed instructions on building sock. Basically, you need to
build the libraries first, and then build sock.
The Transaction TCP (T/TCP) for Linux project website provides
a refined version of sock at: http://ttcplinux.sourceforge.net/
tools/tools.html. Both the binary executable and the source code pack-
age are available. In fact, you can simply download the binary code and
use it in the lab.
tcpdump
Tcpdump is a command-line-based network traffic sniffer and analyzer. It
is preinstalled in Red Hat Linux 9.0 at /usr/sbin/tcpdump.
If you are using Solaris, or your Linux system does not have a preinstalled
tcpdump, you need to install the program. tcpdump depends on the libcap
package which captures packets from a network interface. You can down-
load both the rpm packages or the source code packages for libcap and
tcpdump from the tcpdump homepage: http://www.tcpdump.org. If
you download the source code package, you need to build tcpdump locally,
by running ./configure, make, and make install.
ethereal
Ethereal is a network traffic sniffer and analyzer with a graphical user
interface. It has similar functions as tcpdump, but with an enhanced user
222 Appendix A: instructor’s guide
interface. Ethereal depends on two packages: the GTK+ version 1.2 or later
for the graphical user interface, and the libcap package for packet capture.
Both packages are preinstalled in Red Hat Linux 9.0.
Ethereal is included in the Red Hat Linux 9 installation CDs.
To install, insert the Red Hat Linux Installation CD 1 into the
CD drive and reboot the system. In the following Anaconda Red
Hat Linux installer, choose Perform an upgrade of an existing
installation, customize packages to be upgraded, and check
Skip boot loader updating. In the following Individual Package
Selection window, choose ethereal and click the Next button. Then
Ethereal will be installed.
Alternatively, you can download the source package,
ethereal-0.9.10.tar.gz (or a later version), from the Ethereal
website: http://www.ethereal.com. Then,
1. Run gunzip ethereal-0.9.10.tar.gz and tar -xvf ethereal-0.9.10.tar to
uncompress and extract the tar ball.
2. Change to the ethereal-0.9.10 directory, run ./configure, make, and
make install.
The executable is installed at /usr/local/bin/ethereal. A companion
command-line tool, tethereal, is installed in the same directory. tethereal
is useful when the graphical environment, i.e., gnome or XWindows, is not
available.
Glib and GTK+ packages are also included in the Solaris Companion Soft-
ware CD, or are downloadable from http://www.sun.com/software/
solaris/freeware/. You need to make sure that these two packages are
installed. Then, uncompress and install the package by bunzip ethereal-
x.y.z-solaris2.9-sparc-local.bz2 and pkgadd -d ethereal-x.y.z-solaris2.9-
sparc-local.
to start routed every time when the system boostraps, execute chkconfig
routed on as root.
Reboot the host, then a tftp client can only download files in the
/tftpboot directory.
224 Appendix A: instructor’s guide
JMStudio
JMStudio is a Java-based realtime streaming tool from Sun Microsys-
tems. It is provided as a demonstration of the Sun Java Media Frame-
work (JMF). We use JMStudio in the multimedia multicasting exercises in
Chapter 7.
Installing JMF
JMF works with Red Hat Linux 6.2 or a later version. The
Linux JMF package, (jmf-2 1 1e-linux-i586.bin), can be down-
loaded from http://java.sun.com/products/java-media/jmf/2.
1.1/download.html. Then, get into the directory where this installer file
is stored, and run the following:
chmod +x ./jmf-2 1 1e-linux-i586.bin.
Next, run the installer to extract JMF to a directory, e.g., /home/LAB/.
A directory called JMF-2.1.1e will be created in this directory. Then in
the configuration file /home/guest/.bash profile, set the CLASSPATH
environment parameter to reference the JMF directory:
JMFHOME=/home/LAB/JMF-2.1.1e
export JMFHOME
CLASSPATH=$JMFHOME/lib/jmf.jar:.:$CLASSPATH
export CLASSPATH
Now JMF is installed. You can find the JMFStudio executable, jmstudio,
in the $JMFHOME/bin/ directory.
Package Dependencies
DBS depends on three software packages. It uses perl 5.0 or a later
version and gnuplot to plot the measured traces. These two packages
are preinstalled in Red Hat Linux 9.0. DBS also uses ntp to synchro-
nize the clocks of all the participating hosts, which is available from
http://www.ntp.org/downloads.html. Similarly, ntp is preinstalled
in Red Hat Linux 9.0 as well.
Both perl and ntp are preinstalled in Solaris 8.0. gnuplot is in-
cluded in the Solaris Companion CD free software and can be down-
loaded from http://www.sun.com/software/solaris/freeware/
pkgs_download.html.
Installing DBS
You can download the source code package of DBS from http:
//www.kusa.ac.jp/~yukio-m/dbs/download.html. DBS supports
Linux kernel 2.0.* or later, as well as Sun OS 4.1.3, 4.1.4, and 5.5.*,
and FreeBSD. To install DBS:
1. After you download the dbs-1.2.0beta1.tar.gz file, extract it by:
gun-zip dbs-1.2.0beta1.tar.gz and tar -xvf dbs-1.2.0beta1.tar. A direc-
tory called dbs-1.2.0beta1 is created, which contains all the DBS files.
2. Go to directory ../dbs-1.2.0beta1/src, and run make.
3. Run make install as root to copy the executables to the
/usr/local/etc directory. You may add the /usr/local/etc
to user guest’s PATH environment.
When the installation is over, you need to delete the first two lines in the
/usr/local/etc/dbs view file. The first line is “#!/usr/local/bin/perl”,
226 Appendix A: instructor’s guide
and the second line is “#!/usr/local/bin/perl -d”. These two lines point to a
wrong directory for perl.
When installing DBS on Solaris, you need to uncomment the LDFLAGS line
in the Makefile. The first two lines in the /usr/local/etc/dbs_view file
should not be deleted.
Accessory files
The TFTP exercise in Chapter 5 uses two files with randomly generated
contents, a small file (1 kbyte) called small.dum and a large file (1 Mbyte)
called large.dum. You can put these two files in the /tftpboot directory.
The FTP exercise in Chapter 5 also uses these two files, but stored in a
different directory at /home/LAB/.
The DBS exercises in Chapter 6 uses three command files in the
/home/guest/ directory: TCP1.cmd, TCP2.cmd, and TCPUDP.cmd.
The files are given in Appendix C.1. Also a directory named
/home/guest/data should be created to store data files for the DBS ex-
periments.
You need a video clip for the realtime multicasting exercises in
Chapter 7. You can download the video clip from, e.g., http://www.
gomovietrailers.com, and put it in the /home/guest/ video.
The Apache exercises in Chapter 8 uses two HTML files given in Ap-
pendix C.3. These two HTML files, along with an arbitrary GIF formatted
picture file mypic.gif are stored in the /var/www/html/ directory. A Perl
CGI script, hello.pl, which is given in Appendix C.3, should be stored
in the /var/www/cgi-bin directory. Note that you need to run chmod +x
hello.pl to make it executable.
The four C programs for the socket programming exercises in Chap-
ter 8 are given in Appendix C.4. These four files may be stored in the
/home/guest directory.
DB–9
Router Connector Computer
RJ–45 RJ–45
Connector Connector
Console COM1
Port Port
you need to insert the MAC addresses of the router interfaces, which you
can find by running tcpdump in the lab or from the router documentations,
in Table A.2.
All the diagnostic tools we use in the experiments are public domain soft-
ware, which can be downloaded free of charge. For the hardware devices,
although this guide is based on a setup of eight computers and four routers,
a smaller setup is adequate. Table A.3 lists the minimum hardware require-
ments for each lab.
Also note that the experiments focus on the networking protocol op-
erations, and thus do not require high-end computers and routers. Our
experience shows that PCs with middle of range (or low) configuration
(e.g., PII 500MHZ CPU, 256M memory, and several hundred MB of hard-
drive) or Sun Ultra 5 workstations, and Cisco 2600 series routers are ade-
quate for all the exercises. The estimated budget for a 8-seat laboratory is
about $17,500, which consists of 4×$2000 for the routers, 8×$1000 for
the computers, and $1500 for accessories (hubs, cables, connectors, desks,
and chairs). Further reduction on cost can be achieved if second-hand com-
puters and routers are available or if the minimum setup shown in Table A.3
is used.
Chapter 1 2 0
Chapter 2 3 1
Chapter 3 2 2
Chapter 4 3 2
Chapter 5 2 1
Chapter 6 2 0
Chapter 7 3 2
Chapter 8 5 1
Chapter 9 2 0
230 Appendix A: instructor’s guide
wheel:x:10:root,guest
A.5.3 Sudo
Sudo is another useful tool that allows an administrator to assign privilege
for some users to run some commands as root. It also logs user behavior
for auditing purposes. Sudo is preinstalled in Red Hat Linux 9.0.
To assign a command (e.g., tcpdump) to a normal user (e.g. guest),
you need to edit the Sudo configuration file /etc/sudoers using the Sudo
editor visudo, i.e., adding a new line at the end of the /etc/sudoers file:
guest ALL=/usr/sbin/tcpdump
Note that it is a TAB character after guest in the above line. Then user
guest can run tcpdump using:
sudo /usr/sbin/tcpdump.
He or she will be prompted for user guest’s password. After entering the
correct password, tcpdump begins to run. In the next five minutes, guest
can run tcpdump without entering a password. After that, the user will be
prompted for the password again.
Sudo is not preinstalled in Solaris 8.0. You can download the package
from http://www.courtesan.com/sudo/. To install Sudo on a Solaris
machine:
1. Download the Sudo source package, sudo-1.6.3.tar.gz.
2. Uncompress and extract the source package, by gunzip sudo-
1.6.3.tar.gz and tar xvf sudo-1.6.3.tar.
3. Get into the ../sudo-1.6.3 directory. Execute: ./configure, make, and
make install.
Sudo and the Sudo editor visudo are installed at /usr/local/bin. You
may need to append these directories into the PATH environment variable
of user guest.
232 Appendix A: instructor’s guide
All experiments in this guide can be done without Internet access. In fact,
to avoid disturbing the normal operation of the campus network, it is rec-
ommended to keep the experimental network isolated. Students need to use
floppy disks or other storage media to copy the experimental data.
If Internet access is available in the lab, students can transfer the ex-
perimental data using FTP or email. For example, there could be a ninth
workstation which is multihomed, as shown in Fig. A.1. One interface of
this machine connects to the internal network, while the other interface
connects to the Internet. Note that routing and forwarding should be dis-
abled in this multihomed host to keep the laboratory network isolated. We
need to make sure that the Linux IP Forwarding module is not loaded, by
running the following command:
echo “0” > /proc/sys/net/ipv4/ip forward.
hostname router
enable password el537
line vty 0 4
password el537
!
ip routing
no decnet routing
no xns routing
no novell routing
no appletalk routing
no clns routing
no vines routing
no bridge 1
!
interface Ethernet0
ip address 128.238.61.1 255.255.255.0
!
interface Ethernet1
ip address 128.238.62.1 255.255.255.0
!
The initial configurations of the other routers are similar to that of router1,
with different interface IP addresses, as given in Table A.2.
Appendix C: source code
The following two command files are modified from the examples in the
DBS package.
C.1.1 TCP1.cmd
This is the command file for a single TCP connection.
# TCP1
{
sender {
hostname = host2;
port = 0;
so_debug = OFF;
tcp_trace = OFF;
no_delay = OFF;
send_buff = 32768;
recv_buff = 32768;
mem_align = 2048;
pattern {8192, 8192, 0.0, 0.0}
}
receiver {
hostname = host1;
port = 20000;
so_debug = OFF;
tcp_trace = OFF;
no_delay = OFF;
recv_buff = 32768;
send_buff = 32768;
mem_align = 8192;
pattern {8192, 8192, 0.0, 0.0}
}
file = data/tcp1-host2-host1;
protocol = TCP;
start_time = 0.0;
end_time = 30;
send_times = 2048;
}
236
237 C.1 Command files for the DBS experiments
C.1.2 TCPUDP.cmd
This is the command file for a single TCP connection and a UDP flow.
# TCP
{
sender {
hostname = host2;
port = 0;
so_debug = OFF;
tcp_trace = OFF;
no_delay = OFF;
send_buff = 32768;
recv_buff = 32768;
mem_align = 2048;
pattern {8192, 8192,0.0, 0.0}
}
receiver {
hostname = host1;
port = 20000;
so_debug = OFF;
tcp_trace = OFF;
no_delay = OFF;
recv_buff = 32768;
send_buff = 32768;
mem_align = 8192;
pattern {8192, 8192, 0.0, 0.0}
}
file = data/tcpudp-host2-host1;
protocol = TCP;
start_time = 0.0;
end_time = 30;
send_times = 2048;
}
# UDP
{
sender {
hostname = host3;
port = 20000;
so_debug = OFF;
tcp_trace = OFF;
no_delay = OFF;
send_buff = 32768;
recv_buff = 32768;
mem_align = 8192;
# A sample MPEG traffic paterm (GOP=12)
# This is modeled from
# Craig Partridge, Gigabit Networking,
# Addison-Wesley, p187, 1993
pattern {40960, 1024, 0.033333333, 0;
2048, 1024, 0.033333333, 0;
2048, 1024, 0.033333333, 0;
10240, 1024, 0.033333333, 0;
2048, 1024, 0.033333333, 0;
2048, 1024, 0.033333333, 0;
10240, 1024, 0.033333333, 0;
238 Appendix C: source code
C.1.3 TCP2.cmd
This is the command file for two TCP connections.
# TCP1
{
sender {
hostname = host2;
port = 0;
so_debug = OFF;
tcp_trace = OFF;
no_delay = OFF;
send_buff = 32768;
recv_buff = 32768;
mem_align = 2048;
pattern {8192, 8192,0.0, 0.0}
}
receiver {
hostname = host1;
port = 20000;
so_debug = OFF;
tcp_trace = OFF;
no_delay = OFF;
recv_buff = 32768;
send_buff = 32768;
mem_align = 8192;
pattern {8192, 8192, 0.0, 0.0}
}
file = data/tcp2-host2-host1;
protocol = TCP;
start_time = 0.0;
end_time = 30;
send_times = 2048;
}
# TCP2
{
sender {
239 C.2 Netspy source code
hostname = host3;
port = 0;
so_debug = OFF;
tcp_trace = OFF;
no_delay = OFF;
send_buff = 32768;
recv_buff = 32768;
mem_align = 2048;
pattern {8192, 8192,
0.0, 0.0}
}
receiver {
hostname = host1;
port = 20000;
so_debug = OFF;
tcp_trace = OFF;
no_delay = OFF;
recv_buff = 32768;
send_buff = 32768;
mem_align = 8192;
pattern {8192, 8192, 0.0, 0.0}
}
file = data/tcp2-host3-host1;
protocol = TCP;
start_time = 0.0;
end_time = 30;
send_times = 2048;
}
(void *) &mreq,
sizeof(mreq));
if(rc<0) {
printf("Netspy : cannot join multicast group
’%s’", \
inet_ntoa(mcastAddr));
exit(1);
}
else {
printf("\nNetspy : listening to mgroup %s:%d\n\n", \
inet_ntoa(mcastAddr),
SERVER_PORT);
/* infinite server loop */
while(1) {
cliLen=sizeof(cliAddr);
n = recvfrom(sd,msg,MAX_MSG,0, \
(struct sockaddr *) &cliAddr,
&cliLen);
if(n<0) {
printf("Netspy : cannot receive data\n");
continue;
}
printf(" == : %s\n", msg);
}/* end of infinite server loop */
}
}
C.2.2 netspyd.c source code
/******************************************/
/* netspyd.c */
/* */
/* Written by Dr Shiwen Mao */
/* Dept. ECE, Polytechnic University */
/* */
/* 7/17/2003 */
/******************************************/
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <unistd.h> /* close */
#include <utmp.h>
#include <time.h>
#include <sys/timeb.h>
#include <string.h>
#include <netdb.h>
#define MAX_LOGIN 256
int main(int argc, char *argv[]) {
242 Appendix C: source code
int sd, i;
unsigned char ttl;
struct sockaddr_in cliAddr, servAddr;
struct hostent *h;
int SERVER_PORT;
char ampm[]="AM";
struct tm* today;
char hostn[128];
char message[200];
struct utmp *upt_var;
struct utmp old_utmp[MAX_LOGIN];
int flags[MAX_LOGIN];
int old_len, found = -1;
old_len = 0;
for(i=0;i<MAX_LOGIN;i++){
flags[i] = -1;
}
gethostname(hostn, sizeof(hostn));
if(argc!=4) {
printf("usage netspyd <mgroup_addr> <port_number> \
<TTL_value>\n");
exit(1);
}
ttl = atoi(argv[3]);
SERVER_PORT = atoi(argv[2]);
h = gethostbyname(argv[1]);
if(h==NULL) {
printf("netspyd : unknown host ’%s’\n", argv[1]);
exit(1);
}
servAddr.sin_family = h->h_addrtype;
memcpy((char *) &servAddr.sin_addr.s_addr, \
h->h_addr_list[0],
h->h_length);
servAddr.sin_port = htons(SERVER_PORT);
if(!IN_MULTICAST(ntohl(servAddr.sin_addr.s_addr))) {
printf("netspyd : address ’%s’ is not multicast
\n", \
inet_ntoa(servAddr.sin_addr));
exit(1);
}
sd = socket(AF_INET,SOCK_DGRAM,0);
if (sd<0) {
printf("netspyd : cannot open socket\n");
exit(1);
}
cliAddr.sin_family = AF_INET;
243 C.2 Netspy source code
cliAddr.sin_addr.s_addr = htonl(INADDR_ANY);
cliAddr.sin_port = htons(SERVER_PORT+1);
if(bind(sd,(struct sockaddr *) &cliAddr,
sizeof(cliAddr))<0) {
perror("bind");
exit(1);
}
if(setsockopt(sd,IPPROTO_IP,IP_MULTICAST_TTL,&ttl,
sizeof(ttl))<0){
printf("netspyd : cannot set ttl = %d \n",ttl);
exit(1);
}
printf("netspyd started : \n");
printf(" [local address : %s:%d]
\n" , \
hostn, SERVER_PORT+1);
printf(" [multicast group : %s:%d]
\n\n" , \
inet_ntoa(*(struct in_addr *)h->h_addr_list[0]),
SERVER_PORT);
while(1){
setutent();
while((upt_var = getutent()) != NULL){
if(upt_var->ut_type == USER_PROCESS){
found = -1;
for(i=0;i<old_len;i++){
if(upt_var->ut_pid == old_utmp[i].ut_pid){
found = 1;
flags[i] = 1;
}
}
if(found == -1){
today = localtime(&upt_var->ut_time);
if(today->tm_hour>12){
ampm[0] = ’P’;
today->tm_hour -= 12;
}
else{
ampm[0] = ’A’;
}
printf(" == : %s logged on to %s at %.5s %s,
pid=%d\n",\
upt_var->ut_user,hostn, asctime(today)
+11, ampm, \
upt_var->ut_pid);
sprintf(message, "%s logged on to %s at %.5s
%s", \
upt_var->ut_user,hostn, asctime(today)
+11, ampm);
244 Appendix C: source code
<html>
<head>
<title>An Example HTML File</title>
</head>
<body>
<p>This is a text line.</p>
<p><a href="usage/index.html">This is a hyperlink</a>.
</p>
<p>Here is an embedded picture:
<img border="0" src="mypic.gif" width="164"
height="123"></p>
</body>
</html>
<html>
<head>
<TITLE>An Exsample HTML FORM</TITLE>
</head>
<body>
<p>
<p>
<hr>
<FORM ACTION="/cgi-bin/hello.pl" METHOD="GET">
Type you name:
<p> <INPUT TYPE="TEXT" NAME="name">
<p> <INPUT TYPE="SUBMIT">
</FORM>
<hr>
</body>
</html>
#!/usr/bin/perl
print "Content-type: text/html\r\n\r\n";
print "<html><head><title>CGI Response</title>
</head>\r\n";
print "<hr>\r\n";
print "<p>\r\n";
print "The data received by the server is:\r\n";
print "<p>\r\n";
print "$ENV{’QUERY_STRING’}\r\n";
print "<p>\r\n";
print "<hr>\r\n";
print "</body></html>\r\n";
C.4.1 UDPserver.c
/////////////////////////////////////////////////////
// UDPserver.c -- Sockets that use UDP datagrams //
// //
// Written by Dr Shiwen Mao, Polytechnic Univ. //
// December 2003. //
/////////////////////////////////////////////////////
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define BUFFLEN 100
int main(int argc, char* argv[])
{
int sockserver;
struct sockaddr_in server_addr;
struct sockaddr_in client_addr;
int addr_len, sendlen, rcvdlen;
char buf[BUFFLEN];
if(argc !=2){
printf("Usage: UDPserver server_port \n");
exit(1);
}
247 C.4 Socket programming source codes
C.4.2 UDPclient.c
/////////////////////////////////////////////////////
// UDPclient.c -- Sockets that use UDP datagrams //
// //
// Written by Dr Shiwen Mao, Polytechnic Univ. //
// December 2003. //
/////////////////////////////////////////////////////
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#define BUFFLEN 100
int main(int argc, char *argv[])
{
int sockclient;
struct sockaddr_in server_addr;
struct hostent *hent;
int sendlen,rcvdlen,addrlen;
char buf[BUFFLEN];
if (argc != 4) {
printf("Usage: UDPclient server_ip server_port
message\n");
exit(1);
}
// Get the UDP server’s IP address
if ((hent=gethostbyname(argv[1])) == NULL) {
printf("Error in gethostbyname.\n");
exit(1);
}
// Create the UDP client socket
if ((sockclient = socket(AF_INET, SOCK_DGRAM, 0))
== -1) {
printf("Error in creating UDP socket.\n");
exit(1);
}
// Set the UDP server’s address
server_addr.sin_family = AF_INET;
server_addr.sin_port = atoi(argv[2]);
server_addr.sin_addr = *((struct in_addr *)
hent->h_addr);
memset(&(server_addr.sin_zero), ’\0’, 8);
// Send the message to the UDP server
if ((sendlen=sendto(sockclient, argv[3],
249 C.4 Socket programming source codes
strlen(argv[3]), \
0, (struct sockaddr *)
&server_addr, \
sizeof(struct sockaddr)))
==-1){
printf("Error in sendto.\n");
exit(1);
}
printf("sent %d bytes to %s\n", \
sendlen, inet_ntoa
(server_addr.sin_addr));
printf("message: %s\n\n", argv[3]);
// Receive the returned message from the server
if ((rcvdlen=recvfrom(sockclient,buf, BUFFLEN-1,
0, \
(struct sockaddr *)&server_addr, &addrlen))
== -1){
printf("Error in recvfrom.\n");
exit(1);
}
printf("received %d bytes from server %s\n",
rcvdlen, \
inet_ntoa
(server_addr.sin_addr));
buf[rcvdlen] = ’\0’;
printf("received message: %s\n", buf);
// Shutdown the UDP client socket
close(sockclient);
return 0;
}
C.4.3 TCPserver.c
/////////////////////////////////////////////////////
// TCPserver.c -- A TCP server socket //
// //
// Written by Dr Shiwen Mao, Polytechnic Univ. //
// December 2003. //
/////////////////////////////////////////////////////
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define BACKLOG 10
#define BUFFLEN 100
int main(int argc, char *argv[])
250 Appendix C: source code
{
int sockserver, sockclient;
struct sockaddr_in server_addr, client_addr;
int sockin_size;
int sendlen, rcvdlen;
char buf[BUFFLEN];
if (argc != 2){
printf("Usage: TCPserver server_port\n");
exit(1);
}
// Create the TCP server socket
if ((sockserver = socket(AF_INET, SOCK_STREAM, 0))
== -1) {
printf("Error in creating the server socket.\n");
exit(1);
}
// Set the server socket address
server_addr.sin_family = AF_INET;
server_addr.sin_port = atoi(argv[1]);
server_addr.sin_addr.s_addr = INADDR_ANY;
memset(&(server_addr.sin_zero), ’\0’, 8);
// Associate the server address with the
server socket
if (bind(sockserver, (struct sockaddr *)
&server_addr, \
sizeof(struct sockaddr)) == -1) {
printf("Error in bind.\n");
exit(1);
}
// Waiting for client requests
if (listen(sockserver, BACKLOG) == -1) {
printf("Error in listen.\n");
exit(1);
}
while(1) {
// Accept a client connection request
sockin_size = sizeof(struct sockaddr_in);
if ((sockclient = accept(sockserver, \
(struct sockaddr *)&client_addr, \
&sockin_size)) == -1) {
printf("Error in accept.\n");
continue;
}
printf("TCP server: connection request from
%s\n", \
inet_ntoa
(client_addr.sin_addr));
// Receive a message from the connected client
if ((rcvdlen=recv(sockclient, buf, BUFFLEN-1, 0))
==-1){
251 C.4 Socket programming source codes
printf("Error in recv.\n");
continue;
}
buf[rcvdlen] = ’\0’;
printf("Received from client: %s\n", buf);
// Return the message to the client
if ((sendlen=send(sockclient, buf, rcvdlen, 0))
== -1){
printf("Error in send.\n");
continue;
}
printf("Sent to client: %s\n\n", buf);
// Close the client socket, terminate the TCP
connection.
close(sockclient);
}
return 0;
}
C.4.4 TCPclient.c
/////////////////////////////////////////////////////
// TCPclient.c -- A TCP client socket //
// //
// Written by Dr Shiwen Mao, Polytechnic Univ. //
// December 2003. //
/////////////////////////////////////////////////////
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#define BUFFLEN 100
int main(int argc, char *argv[])
{
int sockserver;
struct hostent *hent;
struct sockaddr_in server_addr;
int sendlen, rcvdlen;
char buf[BUFFLEN];
if (argc != 4) {
printf("Usage: TCPclient server_ip server_port
message\n");
exit(1);
}
// Get the TCP server’s IP address
252 Appendix C: source code
if ((hent=gethostbyname(argv[1])) == NULL) {
printf("Error in gethostbyname.\n");
exit(1);
}
// Create the TCP client socket
if ((sockserver = socket(AF_INET, SOCK_STREAM, 0))
== -1){
printf("Error in creating the socket.\n");
exit(1);
}
// Set the server socket address
server_addr.sin_family = AF_INET;
server_addr.sin_port = atoi(argv[2]);
server_addr.sin_addr = *((struct in_addr *)
hent->h_addr);
memset(&(server_addr.sin_zero), ’\0’, 8);
// Connect to the above server socket
if (connect(sockserver, (struct sockaddr *)
&server_addr, \
sizeof(struct sockaddr))
== -1) {
printf("Error in connect.\n");
exit(1);
}
// Send a message to the TCP server
if ((sendlen=send(sockserver, argv[3],
strlen(argv[3]), 0))==-1){
printf("Error in send.\n");
exit(1);
}
printf("Sent to server: %s\n", argv[3]);
// Receive the returned message from the server
if ((rcvdlen=recv(sockserver, buf, BUFFLEN-1, 0))
== -1) {
printf("Error in recv.\n");
exit(1);
}
buf[rcvdlen] = ’\0’;
printf("Received from server: %s\n",buf);
// Close the TCP client socket
close(sockserver);
return 0;
}
Appendix D: list of key requests
for comments (RFC)
253
254 Appendix D: list of key requests for comments (RFC)
258
259 Index
diagnostic tools 35, 39, 221 Global Positioning System see GPS
ethereal 36 GPS 169
multicast, Cisco IOS, 144 grafting 140
TCP, 124 group address 135
tcpdump 35–36 group membership 140
digital signature 197, 198
Digital Signature Standard see DSS handoff 46
Distance Vector Multicast Routing Protocol see hashing 196
DVMRP hidden terminal 47
distributed benchmark system see DBS host 4–5, 7–8, 15–17, 23–25
decryption 194–196 host ID 11–13, 78
domain name 9–10, 23, 30 HTML 159, 245
Domain Name System see DNS HTTP 3, 23, 25, 112, 119, 159, 160, 178, 200
DNS 3, 10, 23, 24, 28, 30, 101, 135, 219 hub 5, 218
DSS 198 HyperText Markup Language see HTML
DVMRP 139, 143 HyperText Transfer Protocol see HTTP
Dynamic Host Configuration Protocol see
DHCP IAB 2
ICANN 2, 10, 172
e-commerce 1 ICMP 4, 52, 58, 90, 95
editor, text 32–34 echo reply 53
EGP 82 echo request 53
email 112, 119, 159 port unreachable 91, 103
encapsulation 7, 193–196 redirect 80
Encapsulating Security Payload see ESP router discovery 81
error control 19, 111 router solicitation 81
TCP, 115 router advertisement 81
error detection 18, 115–116, 115 time exceeded 90, 91
checksum 18 unreachable error 101
cyclic redundancy check 18 IEEE 802.11 4, 45
ESP 204 IETF 2
ethernet 4 IGMP 4, 82, 138, 143, 154
ethernet address 15 infrastructure mode 46
ethernet bridge 61 initial sequence number see ISN
ethernet frame 19, 24, 51 interior gateway protocol 4, 82
ethernet LANs 44–45 Internet 1, 159
ethernet switch 45 Internet Architecture Board see IAB
exposed terminal 47 Internet Control Message Protocol see ICMP
extended-network-prefix 13 Internet Corporation for Assigned Names and
exterior gateway protocol see EGP Numbers see ICANN
Internet Engineering Task Force see IETF
fast recovery 123 Internet Group Management Protocol see IGMP
fast retransmit 123 Internet Network Information Center see
FDDI 48 InterNIC
FEC 19, 147 Internet Protocol see IP
Fiber-Distributed Data Interface see FDDI Internet Research Task Force see IRTF
File Transfer Protocol see FTP Internet Society see ISOC
filtering database 62, 63 InterNIC 2
firewall 162, 173, 205, 211 IP 2
flooding 63 address 10–13, 30, 48, 59, 78
floppy disk 34 multicast, 81
flow control 17, 111 private, 172
sliding window 119–121 public, 172
stop-and-wait 103 Control Protocol 44
forward error correction see FEC datagram 24, 48, 51–52
forwarding 17 fragmentation 101
FreeBSD 27 header 20, 101
FTP 104–106, 108, 112, 119, Security 203
159 IPv4 14
Anonymous, 106 IPv6 13–14
260 Index
Transmission Control Protocol see TCP virtual private network see VPN
transport layer 3 Voice over IP see VoIP
Trivial File Transfer Protocol see TFTP VoIP 100, 145
TTL 90–91 VPN 89, 204