In this chapter, we walk you through all the necessary steps to set up TCP/IP networking on your machine.
Starting with the assignment of IP addresses, we slowly work our way through the configuration of TCP/IP
network interfaces and introduce a few tools that come in handy when hunting down network installation
problems.
Most of the tasks covered in this chapter will generally have to be done only once. Afterward, you have to touch most configuration files only when adding a new system to your network or when you reconfigure your system entirely. Some of the commands used to configure TCP/IP, however, have to be executed each time the systemis booted. This is usually done by invoking them from the system /etc/rc*scripts.
Commonly, the network-specific part of this procedure is contained in a script. The name of this script varies in different Linux distributions. In many older Linux distributions, it is known as rc.netor rc.inet. Sometimes you will also see two scripts named rc.inet1and rc.inet2; the former initializes the kernel part of networking and the latter starts basic networking services and applications. In modern distributions, the rcfiles are structured in a more sophisticated arrangement; here you may find scripts in the /etc/init.d/(or /etc/rc.d/init.d/) directory that create the network devices and other rcfiles that run the network application programs. This book's examples are based on the latter arrangement.
This chapter discusses parts of the script that configure your network interfaces, while applications will be
covered in later chapters. After finishing this chapter, you should have established a sequence of commands that properly configure TCP/IP networking on your computer. You should then replace any sample commands in your configuration scripts with your commands, make sure the script is executed from the basic rcscript at startup time, and reboot your machine. The networking rcscripts that come along with your favorite Linuxdistribution should provide a solid example from which to work.
Mounting the /proc Filesystem
Some of the configuration tools of the Linux NET-2 and NET-3 release rely on the /procfilesystem for
communicating with the kernel. This interface permits access to kernel runtime information through a
filesystem-like mechanism. When mounted, you can list its files like any other filesystem, or display their
contents. Typical items include the loadavgfile, which contains the system load average, and meminfo, which
shows current core memory and swap usage.
To this, the networking code adds the netdirectory. It contains a number of files that show things like the kernel ARP tables, the state of TCP connections, and the routing tables. Most network administration tools get their information from these files.
The procfilesystem (or procfs, as it is also known) is usually mounted on /procat system boot time. The best
method is to add the following line to /etc/fstab:
# procfs mount point:
none /proc proc defaults
Then execute mount /proc from your /etc/rcscript.
The procfsis now configured into most kernels by default. If the procfsis not in your kernel, you will get a
message such as: mount: fs type procfs not supported by kernel. You will then have to
recompile the kernel and answer "yes" when asked for procfssupport.
Installing the Binaries
If you are using one of the prepackaged Linux distributions, it will contain the major networking applications
and utilities along with a coherent set of sample files. The only case in which you might have to obtain and
install new utilities is when you install a new kernel release. As they occasionally involve changes in the kernel
networking layer, you will need to update the basic configuration tools. This update at least involves
recompiling, but sometimes you may also be required to obtain the latest set of binaries. These binaries are
available at their official home site at ftp.inka.de/pub/comp/Linux/networking/NetTools/, packaged in an
archive called net-tools-XXX.tar.gz, where XXXis the version number. The release matching Linux 2.0 is
net-tools-1.45.
If you want to compile and install the standard TCP/IP network applications yourself, you can obtain the
sources from most Linux FTP servers. All modern Linux distributions include a fairly comprehensive range of
TCP/IP network applications, such as World Wide Web browsers, telnet and ftp programs, and other network applications, such as talk. If you do find something that you do need to compile yourself, the chances are good that it will compile under Linux from source quite simply if you follow the instructions included in the source package.
Setting the Hostname Most, if not all, network applications rely on you to set the local host's name to some reasonable value. Thissetting is usually made during the boot procedure by executing the hostname command. To set the hostname toname, enter:
# hostname name
It is common practice to use the unqualified hostname without specifying the domain name. For instance, hosts
at the Virtual Brewery (described in Appendix A, Example Network: The Virtual Brewery) might be called
vale.vbrew.comor vlager.vbrew.com. These are their official fully qualified domain names(FQDNs). Their
local hostnames would be the first component of the name, such as vale. However, as the local hostname is
frequently used to look up the host's IP address, you have to make sure that the resolver library is able to look up the host's IP address. This usually means that you have to enter the name in /etc/hosts
Learning Technology Is Easy
Wednesday, December 4, 2013
Chapter 2 Issues of TCP/IP Networking
Networking Interfaces
To hide the diversity of equipment that may be used in a networking environment,
TCP/IP defines an abstract interfacethrough which the hardware is accessed. This
interface offers a set of operations that is the same for all types of hardware and
basically deals with sending and receiving packets.
For each peripheral networking device, a corresponding interface has to be present
in the kernel. For example, Ethernet interfaces in Linux are called by such names
as eth0and eth1; PPP (discussed in Chapter 8, The Point-to-Point Protocol)
interfaces are named ppp0and ppp1; and FDDI interfaces are given names like
fddi0and fddi1. These interface names are used for configuration purposes when
you want to specify a particular physical device in a configuration command, and
they have no meaning beyond this use.
Before being used by TCP/IP networking, an interface must be assigned an IP
address that serves as its identification when communicating with the rest of the
world. This address is different from the interface name mentioned previously; if
you compare an interface to a door, the address is like the nameplate pinned on it.
Other device parameters may be set, like the maximum size of datagrams that can
be processed by a particular piece of hardware, which is referred to as Maximum
Transfer Unit(MTU). Other attributes will be introduced later. Fortunately, most
attributes have sensible defaults.
IP Addresses
As mentioned in Chapter 1, Introduction to Networking, the IP networking
protocol understands addresses as 32-bit numbers. Each machine must be assigned
a number unique to the networking environment.[1] If you are running a local
network that does not have TCP/IP traffic with other networks, you may assign
these numbers according to your personal preferences. There are some IP address
ranges that have been reserved for such private networks. These ranges are listed
in Table 2.1. However, for sites on the Internet, numbers are assigned by a central
authority, the Network Information Center(NIC).[2]
[1] The version of the Internet Protocol most frequently used on the
Internet is Version 4. A lot of effort has been expended in designing a
replacement called IP Version 6. IPv6 uses a different addressing
scheme and larger addresses. Linux has an implementation of IPv6,
but it isn't ready to document it in this book yet. The Linux kernel
support for IPv6 is good, but a large number of network applications
need to be modified to support it as well. Stay tuned.
[2] Frequently, IP addresses will be assigned to you by the provider
from whom you buy your IP connectivity. However, you may also
apply to the NIC directly for an IP address for your network by
sending email to hostmaster@internic.net, or by using the form at
http://www.internic.net/.
IP addresses are split up into four eight-bit numbers called octetsfor readability.
For example, quark.physics.groucho.eduhas an IP address of 0x954C0C04, which
is written as 149.76.12.4. This format is often referred to as dotted quad notation.
Another reason for this notation is that IP addresses are split into a network
number, which is contained in the leading octets, and a hostnumber, which is the
remainder. When applying to the NIC for IP addresses, you are not assigned an
address for each single host you plan to use. Instead, you are given a network
number and allowed to assign all valid IP addresses within this range to hosts on
your network according to your preferences.
The size of the host part depends on the size of the network. To accommodate
different needs, several classes of networks, defining different places to split IP
addresses, have been defined. The class networks are described here:
Class A
Class A comprises networks 1.0.0.0through 127.0.0.0. The network number
is contained in the first octet. This class provides for a 24-bit host part,
allowing roughly 1.6 million hosts per network.
Class B
Class B contains networks 128.0.0.0through 191.255.0.0; the network
number is in the first two octets. This class allows for 16,320 nets with
65,024 hosts each.
Class C
Class C networks range from 192.0.0.0through 223.255.255.0, with the
network number contained in the first three octets. This class allows for
nearly 2 million networks with up to 254 hosts.
Classes D, E, and F
Addresses falling into the range of 224.0.0.0through 254.0.0.0are either
experimental or are reserved for special purpose use and don't specify any
network. IP Multicast, which is a service that allows material to be
transmitted to many points on an internet at one time, has been assigned
addresses from within this range.
If we go back to the example in Chapter 1, we find that 149.76.12.4, the address of
quark, refers to host 12.4on the class B network 149.76.0.0.
You may have noticed that not all possible values in the previous list were allowed
for each octet in the host part. This is because octets 0and 255are reserved for
special purposes. An address where all host part bits are 0 refers to the network,
and an address where all bits of the host part are 1 is called a broadcast address.
This refers to all hosts on the specified network simultaneously. Thus,
149.76.255.255is not a valid host address, but refers to all hosts on network
149.76.0.0.
A number of network addresses are reserved for special purposes. 0.0.0.0and
127.0.0.0are two such addresses. The first is called the default route, and the latter
is the loopback address. The default route has to do with the way the IP routes
datagrams.
Network 127.0.0.0is reserved for IP traffic local to your host. Usually, address
127.0.0.1will be assigned to a special interface on your host, the loopback
interface, which acts like a closed circuit. Any IP packet handed to this interface
from TCP or UDP will be returned to them as if it had just arrived from some
network. This allows you to develop and test networking software without ever
using a "real" network. The loopback network also allows you to use networking
software on a standalone host. This may not be as uncommon as it sounds; for
instance, many UUCP sites don't have IP connectivity at all, but still want to run
the INN news system. For proper operation on Linux, INN requires the loopback
interface.
Some address ranges from each of the network classes have been set aside and
designated "reserved" or "private" address ranges. These addresses are reserved for
use by private networks and are not routed on the Internet. They are commonly
used by organizations building their own intranet, but even small networks often
find them useful. The reserved network addresses appear in Table 2.1.
Table 2.1: IP Address Ranges Reserved for
Private Use
ClassNetworks
A 10.0.0.0 through 10.255.255.255
B 172.16.0.0 through 172.31.0.0
C 192.168.0.0 through 192.168.255.0
To hide the diversity of equipment that may be used in a networking environment,
TCP/IP defines an abstract interfacethrough which the hardware is accessed. This
interface offers a set of operations that is the same for all types of hardware and
basically deals with sending and receiving packets.
For each peripheral networking device, a corresponding interface has to be present
in the kernel. For example, Ethernet interfaces in Linux are called by such names
as eth0and eth1; PPP (discussed in Chapter 8, The Point-to-Point Protocol)
interfaces are named ppp0and ppp1; and FDDI interfaces are given names like
fddi0and fddi1. These interface names are used for configuration purposes when
you want to specify a particular physical device in a configuration command, and
they have no meaning beyond this use.
Before being used by TCP/IP networking, an interface must be assigned an IP
address that serves as its identification when communicating with the rest of the
world. This address is different from the interface name mentioned previously; if
you compare an interface to a door, the address is like the nameplate pinned on it.
Other device parameters may be set, like the maximum size of datagrams that can
be processed by a particular piece of hardware, which is referred to as Maximum
Transfer Unit(MTU). Other attributes will be introduced later. Fortunately, most
attributes have sensible defaults.
IP Addresses
As mentioned in Chapter 1, Introduction to Networking, the IP networking
protocol understands addresses as 32-bit numbers. Each machine must be assigned
a number unique to the networking environment.[1] If you are running a local
network that does not have TCP/IP traffic with other networks, you may assign
these numbers according to your personal preferences. There are some IP address
ranges that have been reserved for such private networks. These ranges are listed
in Table 2.1. However, for sites on the Internet, numbers are assigned by a central
authority, the Network Information Center(NIC).[2]
[1] The version of the Internet Protocol most frequently used on the
Internet is Version 4. A lot of effort has been expended in designing a
replacement called IP Version 6. IPv6 uses a different addressing
scheme and larger addresses. Linux has an implementation of IPv6,
but it isn't ready to document it in this book yet. The Linux kernel
support for IPv6 is good, but a large number of network applications
need to be modified to support it as well. Stay tuned.
[2] Frequently, IP addresses will be assigned to you by the provider
from whom you buy your IP connectivity. However, you may also
apply to the NIC directly for an IP address for your network by
sending email to hostmaster@internic.net, or by using the form at
http://www.internic.net/.
IP addresses are split up into four eight-bit numbers called octetsfor readability.
For example, quark.physics.groucho.eduhas an IP address of 0x954C0C04, which
is written as 149.76.12.4. This format is often referred to as dotted quad notation.
Another reason for this notation is that IP addresses are split into a network
number, which is contained in the leading octets, and a hostnumber, which is the
remainder. When applying to the NIC for IP addresses, you are not assigned an
address for each single host you plan to use. Instead, you are given a network
number and allowed to assign all valid IP addresses within this range to hosts on
your network according to your preferences.
The size of the host part depends on the size of the network. To accommodate
different needs, several classes of networks, defining different places to split IP
addresses, have been defined. The class networks are described here:
Class A
Class A comprises networks 1.0.0.0through 127.0.0.0. The network number
is contained in the first octet. This class provides for a 24-bit host part,
allowing roughly 1.6 million hosts per network.
Class B
Class B contains networks 128.0.0.0through 191.255.0.0; the network
number is in the first two octets. This class allows for 16,320 nets with
65,024 hosts each.
Class C
Class C networks range from 192.0.0.0through 223.255.255.0, with the
network number contained in the first three octets. This class allows for
nearly 2 million networks with up to 254 hosts.
Classes D, E, and F
Addresses falling into the range of 224.0.0.0through 254.0.0.0are either
experimental or are reserved for special purpose use and don't specify any
network. IP Multicast, which is a service that allows material to be
transmitted to many points on an internet at one time, has been assigned
addresses from within this range.
If we go back to the example in Chapter 1, we find that 149.76.12.4, the address of
quark, refers to host 12.4on the class B network 149.76.0.0.
You may have noticed that not all possible values in the previous list were allowed
for each octet in the host part. This is because octets 0and 255are reserved for
special purposes. An address where all host part bits are 0 refers to the network,
and an address where all bits of the host part are 1 is called a broadcast address.
This refers to all hosts on the specified network simultaneously. Thus,
149.76.255.255is not a valid host address, but refers to all hosts on network
149.76.0.0.
A number of network addresses are reserved for special purposes. 0.0.0.0and
127.0.0.0are two such addresses. The first is called the default route, and the latter
is the loopback address. The default route has to do with the way the IP routes
datagrams.
Network 127.0.0.0is reserved for IP traffic local to your host. Usually, address
127.0.0.1will be assigned to a special interface on your host, the loopback
interface, which acts like a closed circuit. Any IP packet handed to this interface
from TCP or UDP will be returned to them as if it had just arrived from some
network. This allows you to develop and test networking software without ever
using a "real" network. The loopback network also allows you to use networking
software on a standalone host. This may not be as uncommon as it sounds; for
instance, many UUCP sites don't have IP connectivity at all, but still want to run
the INN news system. For proper operation on Linux, INN requires the loopback
interface.
Some address ranges from each of the network classes have been set aside and
designated "reserved" or "private" address ranges. These addresses are reserved for
use by private networks and are not routed on the Internet. They are commonly
used by organizations building their own intranet, but even small networks often
find them useful. The reserved network addresses appear in Table 2.1.
Table 2.1: IP Address Ranges Reserved for
Private Use
ClassNetworks
A 10.0.0.0 through 10.255.255.255
B 172.16.0.0 through 172.31.0.0
C 192.168.0.0 through 192.168.255.0
Linux Networking
As it is the result of a concerted effort of programmers around the world, Linux
wouldn't have been possible without the global network. So it's not surprising that
in the early stages of development, several people started to work on providing it
with network capabilities. A UUCP implementation was running on Linux almost
from the very beginning, and work on TCP/IP-based networking started around
autumn 1992, when Ross Biro and others created what has now become known as
Net-1.
After Ross quit active development in May 1993, Fred van Kempen began to work
on a new implementation, rewriting major parts of the code. This project was
known as Net-2. The first public release, Net-2d, was made in the summer of 1993
(as part of the 0.99.10 kernel), and has since been maintained and expanded by
several people, most notably Alan Cox.[4] Alan's original work was known as
Net-2Debugged. After heavy debugging and numerous improvements to the code,
he changed its name to Net-3 after Linux 1.0 was released. The Net-3 code was
further developed for Linux 1.2 and Linux 2.0. The 2.2 and later kernels use the
Net-4 version network support, which remains the standard official offering today.
[4] Alan can be reached at alan@lxorguk.ukuu.org.uk
The Net-4 Linux Network code offers a wide variety of device drivers and
advanced features. Standard Net-4 protocols include SLIP and PPP (for sending
network traffic over serial lines), PLIP (for parallel lines), IPX (for Novell
compatible networks, which we'll discuss in Chapter 15, IPX and the NCP
Filesystem), Appletalk (for Apple networks) and AX.25, NetRom, and Rose (for
amateur radio networks). Other standard Net-4 features include IP firewalling, IP
accounting (discussed later in Chapter 9, TCP/IP Firewall and Chapter 10, IP
Accounting), and IP Masquerade (discussed later in Chapter 11, IP Masquerade
and Network Address Translation. IP tunnelling in a couple of different flavors
and advanced policy routing are supported. A very large variety of Ethernet
devices is supported, in addition to support for some FDDI, Token Ring, Frame
Relay, and ISDN, and ATM cards.
Additionally, there are a number of other features that greatly enhance the
flexibility of Linux. These features include an implementation of the SMB
filesystem, which interoperates with applications like lanmanagerand Microsoft
Windows, called Samba, written by Andrew Tridgell, and an implementation of
the Novell NCP (NetWare Core Protocol).[5]
[5] NCP is the protocol on which Novell file and print services are
based.
wouldn't have been possible without the global network. So it's not surprising that
in the early stages of development, several people started to work on providing it
with network capabilities. A UUCP implementation was running on Linux almost
from the very beginning, and work on TCP/IP-based networking started around
autumn 1992, when Ross Biro and others created what has now become known as
Net-1.
After Ross quit active development in May 1993, Fred van Kempen began to work
on a new implementation, rewriting major parts of the code. This project was
known as Net-2. The first public release, Net-2d, was made in the summer of 1993
(as part of the 0.99.10 kernel), and has since been maintained and expanded by
several people, most notably Alan Cox.[4] Alan's original work was known as
Net-2Debugged. After heavy debugging and numerous improvements to the code,
he changed its name to Net-3 after Linux 1.0 was released. The Net-3 code was
further developed for Linux 1.2 and Linux 2.0. The 2.2 and later kernels use the
Net-4 version network support, which remains the standard official offering today.
[4] Alan can be reached at alan@lxorguk.ukuu.org.uk
The Net-4 Linux Network code offers a wide variety of device drivers and
advanced features. Standard Net-4 protocols include SLIP and PPP (for sending
network traffic over serial lines), PLIP (for parallel lines), IPX (for Novell
compatible networks, which we'll discuss in Chapter 15, IPX and the NCP
Filesystem), Appletalk (for Apple networks) and AX.25, NetRom, and Rose (for
amateur radio networks). Other standard Net-4 features include IP firewalling, IP
accounting (discussed later in Chapter 9, TCP/IP Firewall and Chapter 10, IP
Accounting), and IP Masquerade (discussed later in Chapter 11, IP Masquerade
and Network Address Translation. IP tunnelling in a couple of different flavors
and advanced policy routing are supported. A very large variety of Ethernet
devices is supported, in addition to support for some FDDI, Token Ring, Frame
Relay, and ISDN, and ATM cards.
Additionally, there are a number of other features that greatly enhance the
flexibility of Linux. These features include an implementation of the SMB
filesystem, which interoperates with applications like lanmanagerand Microsoft
Windows, called Samba, written by Andrew Tridgell, and an implementation of
the Novell NCP (NetWare Core Protocol).[5]
[5] NCP is the protocol on which Novell file and print services are
based.
Chapter 1 Introduction to Networking
TCP/IP traces its origins to a research project funded by the United States Defense
Advanced Research Projects Agency (DARPA) in 1969. The ARPANET was an
experimental network that was converted into an operational one in 1975 after it
had proven to be a success.
In 1983, the new protocol suite TCP/IP was adopted as a standard, and all hosts on
the network were required to use it. When ARPANET finally grew into the
Internet (with ARPANET itself passing out of existence in 1990), the use of
TCP/IP had spread to networks beyond the Internet itself. Many companies have
now built corporate TCP/IP networks, and the Internet has grown to a point at
which it could almost be considered a mainstream consumer technology. It is
difficult to read a newspaper or magazine now without seeing reference to the
Internet; almost everyone can now use it.
For something concrete to look at as we discuss TCP/IP throughout the following
sections, we will consider Groucho Marx University (GMU), situated somewhere
in Fredland, as an example. Most departments run their own Local Area Networks,
while some share one and others run several of them. They are all interconnected
and hooked to the Internet through a single high-speed link.
Suppose your Linux box is connected to a LAN of Unix hosts at the Mathematics
department, and its name is erdos. To access a host at the Physics department, say
quark, you enter the following command:
$ rlogin quark.physics
Welcome to the Physics Department at GMU
(ttyq2) login:
At the prompt, you enter your login name, say andres, and your password. You are
then given a shell[2] on quark, to which you can type as if you were sitting at the
system's console. After you exit the shell, you are returned to your own machine's
prompt. You have just used one of the instantaneous, interactive applications that
TCP/IP provides: remote login.
[2] The shell is a command-line interface to the Unix operating
system. It's similar to the DOS prompt in a Microsoft Windows
environment, albeit much more powerful.
While being logged into quark, you might also want to run a graphical user
interface application, like a word processing program, a graphics drawing
program, or even a World Wide Web browser. The X windows system is a fully
network-aware graphical user environment, and it is available for many different
computing systems. To tell this application that you want to have its windows
displayed on your host's screen, you have to set the DISPLAYenvironment
variable:
$ DISPLAY=erdos.maths:0.0
$ export DISPLAY
If you now start your application, it will contact your X server instead of quark's,
and display all its windows on your screen. Of course, this requires that you have
X11 runnning on erdos. The point here is that TCP/IP allows quarkand erdosto
send X11 packets back and forth to give you the illusion that you're on a single
system. The network is almost transparent here.
Another very important application in TCP/IP networks is NFS, which stands for
Network File System. It is another form of making the network transparent,
because it basically allows you to treat directory hierarchies from other hosts as if
they were local file systems and look like any other directories on your host. For
example, all users' home directories can be kept on a central server machine from
which all other hosts on the LAN mount them. The effect is that users can log in to
any machine and find themselves in the same home directory. Similarly, it is
possible to share large amounts of data (such as a database, documentation or
application programs) among many hosts by maintaining one copy of the data on a
server and allowing other hosts to access it. We will come back to NFS in Chapter
14, The Network File System.
Of course, these are only examples of what you can do with TCP/IP networks. The
possibilities are almost limitless, and we'll introduce you to more as you read on
through the book.
We will now have a closer look at the way TCP/IP works. This information will
help you understand how and why you have to configure your machine. We will
start by examining the hardware, and slowly work our way up
Advanced Research Projects Agency (DARPA) in 1969. The ARPANET was an
experimental network that was converted into an operational one in 1975 after it
had proven to be a success.
In 1983, the new protocol suite TCP/IP was adopted as a standard, and all hosts on
the network were required to use it. When ARPANET finally grew into the
Internet (with ARPANET itself passing out of existence in 1990), the use of
TCP/IP had spread to networks beyond the Internet itself. Many companies have
now built corporate TCP/IP networks, and the Internet has grown to a point at
which it could almost be considered a mainstream consumer technology. It is
difficult to read a newspaper or magazine now without seeing reference to the
Internet; almost everyone can now use it.
For something concrete to look at as we discuss TCP/IP throughout the following
sections, we will consider Groucho Marx University (GMU), situated somewhere
in Fredland, as an example. Most departments run their own Local Area Networks,
while some share one and others run several of them. They are all interconnected
and hooked to the Internet through a single high-speed link.
Suppose your Linux box is connected to a LAN of Unix hosts at the Mathematics
department, and its name is erdos. To access a host at the Physics department, say
quark, you enter the following command:
$ rlogin quark.physics
Welcome to the Physics Department at GMU
(ttyq2) login:
At the prompt, you enter your login name, say andres, and your password. You are
then given a shell[2] on quark, to which you can type as if you were sitting at the
system's console. After you exit the shell, you are returned to your own machine's
prompt. You have just used one of the instantaneous, interactive applications that
TCP/IP provides: remote login.
[2] The shell is a command-line interface to the Unix operating
system. It's similar to the DOS prompt in a Microsoft Windows
environment, albeit much more powerful.
While being logged into quark, you might also want to run a graphical user
interface application, like a word processing program, a graphics drawing
program, or even a World Wide Web browser. The X windows system is a fully
network-aware graphical user environment, and it is available for many different
computing systems. To tell this application that you want to have its windows
displayed on your host's screen, you have to set the DISPLAYenvironment
variable:
$ DISPLAY=erdos.maths:0.0
$ export DISPLAY
If you now start your application, it will contact your X server instead of quark's,
and display all its windows on your screen. Of course, this requires that you have
X11 runnning on erdos. The point here is that TCP/IP allows quarkand erdosto
send X11 packets back and forth to give you the illusion that you're on a single
system. The network is almost transparent here.
Another very important application in TCP/IP networks is NFS, which stands for
Network File System. It is another form of making the network transparent,
because it basically allows you to treat directory hierarchies from other hosts as if
they were local file systems and look like any other directories on your host. For
example, all users' home directories can be kept on a central server machine from
which all other hosts on the LAN mount them. The effect is that users can log in to
any machine and find themselves in the same home directory. Similarly, it is
possible to share large amounts of data (such as a database, documentation or
application programs) among many hosts by maintaining one copy of the data on a
server and allowing other hosts to access it. We will come back to NFS in Chapter
14, The Network File System.
Of course, these are only examples of what you can do with TCP/IP networks. The
possibilities are almost limitless, and we'll introduce you to more as you read on
through the book.
We will now have a closer look at the way TCP/IP works. This information will
help you understand how and why you have to configure your machine. We will
start by examining the hardware, and slowly work our way up
hashCode And equals Methods Override
In this Java tutorial, we will discuss about hashCode, equals methods
and what role they play in an object. Through this article we will find
answer for the following questions,

For a primitive type, determining the equality is simple. We all know an int value of 10 is always equal to 10. But this equals() method is about equality of two objects. When we say object, it will have properties. To decide about equality those properties are considered. It is not necessary that all properties must be taken into account to determine the equality and with respect to the class definition and context it can be decided. Then the equals() method can be overridden.

Example Code Output:
bengalTiger1 and bengalTiger2: true
bengalTiger1 and siberianTiger: false
bengalTiger1 hashCode: 1398212510
bengalTiger2 hashCode: 1398212510
siberianTiger hashCode: –1227465966
hashCode() method is used in hashtables to determine the equality of keys. If you want more details about hashCode, their default implementation, buckets, different hashing techniques you should go through my earliest tutorial on Java Hashtable. I guarantee you will enjoy, just read it :-).
When an application is executed, the hashcode (an integer) returned for an object should be same till another execution of that application. Now coming to the important point which is the contract between hashCode and equals method,
Default implementation given is hashCode() method in Object class uses the internal address of the object and converts it into integer and returns it. This is the lowest form of equality implementation and provides guaranteed results for hastables implementation. When we override equals() and change the meaning of equality for an object then the same should be reflected by overriding the hashCode method.
May be you should also go through String equals also at this juncture as String equality is one of the celebrated topic in Java.
- What is the purpose of hashCode and equals methods?
- How hashCode and equals are implemented?
- Why hashCode should also be overridden when equals is overridden?
equals Method
equals() method is used to determine the equality of two objects. To bring in little bit of Mathematics flavor lets see the properties of equality. When we say equality, it should adhere by the following properties,- Reflexive: Always, a = a. In Java, a.equals(a) should always be true.
- Symmetric: If a = b, then b = a. In Java, if a.equals(b) is true, then b.equals(a) should be true.
- Transitive: If a = b and b = c, then a = c. In Java, if a.equals(b) and b.equals(c) is true, then a.equals(c) should be true.
For a primitive type, determining the equality is simple. We all know an int value of 10 is always equal to 10. But this equals() method is about equality of two objects. When we say object, it will have properties. To decide about equality those properties are considered. It is not necessary that all properties must be taken into account to determine the equality and with respect to the class definition and context it can be decided. Then the equals() method can be overridden.
Override equals Method
Let us take an example scenario to understand equals() method and study how to override it in our custom implementation. We have a Tiger class and two instances of Tiger are equal if they have the same color and stripePattern is our definition of equality. In our example, though there is an additional property ‘height’, it is excluded from the equals definition to denote that it is entirely our choice.package com.javapapers.java; public class Tiger { private String color; private String stripePattern; private int height; @Override public boolean equals(Object object) { boolean result = false ; if (object == null || object.getClass() != getClass()) { result = false ; } else { Tiger tiger = (Tiger) object; if ( this .color == tiger.getColor() && this .stripePattern == tiger.getStripePattern()) { result = true ; } } return result; } // just omitted null checks @Override public int hashCode() { int hash = 3 ; hash = 7 * hash + this .color.hashCode(); hash = 7 * hash + this .stripePattern.hashCode(); return hash; } public static void main(String args[]) { Tiger bengalTiger1 = new Tiger( "Yellow" , "Dense" , 3 ); Tiger bengalTiger2 = new Tiger( "Yellow" , "Dense" , 2 ); Tiger siberianTiger = new Tiger( "White" , "Sparse" , 4 ); System.out.println( "bengalTiger1 and bengalTiger2: " + bengalTiger1.equals(bengalTiger2)); System.out.println( "bengalTiger1 and siberianTiger: " + bengalTiger1.equals(siberianTiger)); System.out.println( "bengalTiger1 hashCode: " + bengalTiger1.hashCode()); System.out.println( "bengalTiger2 hashCode: " + bengalTiger2.hashCode()); System.out.println( "siberianTiger hashCode: " + siberianTiger.hashCode()); } public String getColor() { return color; } public String getStripePattern() { return stripePattern; } public Tiger(String color, String stripePattern, int height) { this .color = color; this .stripePattern = stripePattern; this .height = height; } } |
Example Code Output:
bengalTiger1 and bengalTiger2: true
bengalTiger1 and siberianTiger: false
bengalTiger1 hashCode: 1398212510
bengalTiger2 hashCode: 1398212510
siberianTiger hashCode: –1227465966
hashCode Method
In the above example did you notice we have overridden another method hashCode() along with equals()? There is an importance to it. We must override hashCode() when we override equals(). Why hashCode should also be overridden when equals is overridden? Because, they both serve the same purpose but in different contexts.hashCode() method is used in hashtables to determine the equality of keys. If you want more details about hashCode, their default implementation, buckets, different hashing techniques you should go through my earliest tutorial on Java Hashtable. I guarantee you will enjoy, just read it :-).
When an application is executed, the hashcode (an integer) returned for an object should be same till another execution of that application. Now coming to the important point which is the contract between hashCode and equals method,
- if two objects are equal, that is obj1.equals(obj2) is true then, obj1.hashCode() and obj2.hashCode() must return same integer.
Override hashCode Method
To honor the above contract we should always override hashCode() method whenever we override equals() method. If not, what will happen? If we use hashtables in our application, it will not behave as expected. As the hashCode is used in determining the equality of values stored, it will not return the right corresponding value for a key.Default implementation given is hashCode() method in Object class uses the internal address of the object and converts it into integer and returns it. This is the lowest form of equality implementation and provides guaranteed results for hastables implementation. When we override equals() and change the meaning of equality for an object then the same should be reflected by overriding the hashCode method.
May be you should also go through String equals also at this juncture as String equality is one of the celebrated topic in Java.
Java Decompiler
Decompiler is to reverse engineer source code from object code. A
decompiler for java should get the respective source file from its Java binary class file.
Java decompiler world is in mess, yes it really looks like kid’s mud play. To our surprise, it is difficult to find a decent Java decompiler in the whole web world.

We may find lots and lots of software tools claiming to be Java decompilers. But if we dig deep then we can find that 90% of them are just the user interface and the underlying engine will be JAD decompiler.
JAD is copright software by Pavel Kouznetsov. JAD was written in C++ and its first version was released before 1999 and its last stable release version was to provide support for JDK 1.4.
JAD does not support JDK 1.5 and later. It is no longer developed or maintained. If you still want to get a feel of JAD, download its last official stable version 1.5.8g using the below link. I have hosted it as a mirror. This is a copyrighted software by Pavel Kouznetsov and cannot be bundled with any commercial software.
Download JAD – jad158g.win – for Windows
There are couple of options for decompiler for Java which looks promising,
I wrote a simple Java factorial program to test JD Java decompiler and that program is as follows:

JD Java decompiler provides a plugin for Eclipse IDE, so that we can decompile a Java class file within the Eclipse IDE itself.
Install the JD-Eclipse plugin as shown in the next screen shot.

JD Java decompile Eclipse plugin will take some good time to install, may be you should have a big coffee during the time. On a side note, Eclipse should still refine its plugin installation process. Once installed a java class file can be just opened and decompiled on the go.
Java decompiler world is in mess, yes it really looks like kid’s mud play. To our surprise, it is difficult to find a decent Java decompiler in the whole web world.
JAva Decompiler (JAD – No longer maintained)
When we say decompiler for Java, it is almost synonymous to JAD. JAD was/is the popular Java decompiler we can find. Very long back, when I started learning Java, I remember using JAD, may be with JDK1.2 or so. It was very popular and almost the only tool for Java class decompilation.We may find lots and lots of software tools claiming to be Java decompilers. But if we dig deep then we can find that 90% of them are just the user interface and the underlying engine will be JAD decompiler.
JAD is copright software by Pavel Kouznetsov. JAD was written in C++ and its first version was released before 1999 and its last stable release version was to provide support for JDK 1.4.
JAD does not support JDK 1.5 and later. It is no longer developed or maintained. If you still want to get a feel of JAD, download its last official stable version 1.5.8g using the below link. I have hosted it as a mirror. This is a copyrighted software by Pavel Kouznetsov and cannot be bundled with any commercial software.
Download JAD – jad158g.win – for Windows
DJ Java Decompiler (UI for JAD)
In that case, what is DJ Java decompiler? DJ Java decompiler is GUI for JAD and provided by Atanas Neshkov. Its last stable version was released on August 2011. Since JAD is no longer maintained, it does not make sense to use DJ Java decompiler either as it is just the UI for JAD.Java Decompiler Options
I can hear you shouting. JAD cannot be used and DJ too is also just an UI for JAD, so what are the options we have for decompiler in Java? We couldn’t find anything other than these!There are couple of options for decompiler for Java which looks promising,
- JD Java Decompiler
- Procyon
1. JD Java Decompiler
Let us first explore JD Java decompiler project and do some simple Java class decompilations. JD-gui is a light weight application with a sleek user interface.I wrote a simple Java factorial program to test JD Java decompiler and that program is as follows:
Java Factorial Sample
package com.javapapers.java; import java.util.Scanner; public class JavaFactorial { public static void main(String args[]) { int n, factorial = 1 ; System.out.print( "Factorial of: " ); Scanner input = null ; try { input = new Scanner(System.in); n = input.nextInt(); } finally { input.close(); } if (n < 0 ) System.out.println( "Try greater than 0." ); else { for ( int i = 1 ; i <= n; i++) factorial = factorial * i; System.out.println( "Factorial " + n + " = " + factorial); } } } |
Decompiled Java Source
Following is the screen shot of both the Java factorial source in Eclipse IDE and its decompiled source using JD-gui Java decompiler. It is simple and easy, just open the .class Java binary file using the gui and it works clean.Decompile Java using Eclipse (JD-Eclipse plugin)
No Java tool is complete unless it provides a plugin for Eclipse IDE. Eclipse is the most popular Java IDE.JD Java decompiler provides a plugin for Eclipse IDE, so that we can decompile a Java class file within the Eclipse IDE itself.
Install the JD-Eclipse plugin as shown in the next screen shot.
JD Java decompile Eclipse plugin will take some good time to install, may be you should have a big coffee during the time. On a side note, Eclipse should still refine its plugin installation process. Once installed a java class file can be just opened and decompiled on the go.
2. Procyon Decompiler for Java
Procyon Java Decompiler is by mstrobel and hosted in Bitbucket. Procyon is a suite of tools containing lot more than the Java decompiler. It is very actively under development (I noticed a commit in Bitbucket during writing this article). Procyon is early in its development, he is just started and not offers a complete version yet. Still why I chose to give a coverage is primarily for two reasons,- almost no one is actively working in this Java world for decompilers (at least as far as I know) – Procyon is actively developed
- Procyon Java Decompiler is open source
Excel Export in Spring MVC
Export as excel is one of the most wanted feature in an enterprise
application. In this tutorial let us learn about export as excel feature
using Spring MVC framework. If you are a beginner, go through the Spring MVC tutorial before taking this. We will be using Spring 3 annotation based approach for the web application.
If you have learned Spring MVC, there is not much to discuss, in this excel export tutorial. All you have to know is, Spring provides a class AbstractExcelView which is a view in the MVC. We need to extend this class and write our custom classes. Then configure our custom class as the view in the MVC.
Maven is used to manage the dependencies. If you do not have Maven, it is better to download and setup Maven.
If you have learned Spring MVC, there is not much to discuss, in this excel export tutorial. All you have to know is, Spring provides a class AbstractExcelView which is a view in the MVC. We need to extend this class and write our custom classes. Then configure our custom class as the view in the MVC.
- Extend AbstractExcelView and write a custom excel view. There is a method buildExcelDocument in this class, which we should override to build the excel.
- Configure the new custom class, which we have created as the view in the Spring MVC. We should imagine this new java class file as a replacement for the JSP which we generally will have in the view.
Maven is used to manage the dependencies. If you do not have Maven, it is better to download and setup Maven.
Animal.java
Domain classpackage com.javapapers.spring.mvc; public class Animal { private int id; private String animalName; private String animalType; private boolean aggressive; private int weight; public Animal( int id, String animalName, String animalType, boolean aggressive, int weight) { super (); this .id = id; this .animalName = animalName; this .animalType = animalType; this .aggressive = aggressive; this .weight = weight; } public int getId() { return id; } public void setId( int id) { this .id = id; } public String getAnimalName() { return animalName; } public void setAnimalName(String animalName) { this .animalName = animalName; } public String getAnimalType() { return animalType; } public void setAnimalType(String animalType) { this .animalType = animalType; } public boolean getAggressive() { return aggressive; } public void setAggressive( boolean aggressive) { this .aggressive = aggressive; } public int getWeight() { return weight; } public void setWeight( int weight) { this .weight = weight; } } |
AnimalListExcelView.java
This is the important class in the excel export tutorial. This serves as the View in Spring MVC by extending the Spring’s AbstractExcelView class.package com.javapapers.spring.mvc; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.springframework.web.servlet.view.document.AbstractExcelView; public class AnimalListExcelView extends AbstractExcelView { @Override protected void buildExcelDocument(Map model, HSSFWorkbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception { HSSFSheet excelSheet = workbook.createSheet( "Animal List" ); setExcelHeader(excelSheet); List<Animal> animalList = (List<Animal>) model.get( "animalList" ); setExcelRows(excelSheet,animalList); } public void setExcelHeader(HSSFSheet excelSheet) { HSSFRow excelHeader = excelSheet.createRow( 0 ); excelHeader.createCell( 0 ).setCellValue( "Id" ); excelHeader.createCell( 1 ).setCellValue( "Name" ); excelHeader.createCell( 2 ).setCellValue( "Type" ); excelHeader.createCell( 3 ).setCellValue( "Aggressive" ); excelHeader.createCell( 4 ).setCellValue( "Weight" ); } public void setExcelRows(HSSFSheet excelSheet, List<Animal> animalList){ int record = 1 ; for (Animal animal : animalList) { HSSFRow excelRow = excelSheet.createRow(record++); excelRow.createCell( 0 ).setCellValue(animal.getId()); excelRow.createCell( 1 ).setCellValue(animal.getAnimalName()); excelRow.createCell( 2 ).setCellValue(animal.getAnimalType()); excelRow.createCell( 3 ).setCellValue(animal.getAggressive()); excelRow.createCell( 4 ).setCellValue(animal.getWeight()); } } } |
ZooController.java
Just added couple of methods from the previous MVC hello world tutorial.package com.javapapers.spring.mvc; import java.util.List; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; @Controller public class ZooController { protected AnimalService animalService = new AnimalService(); @RequestMapping (value = "/AnimalList" , method = RequestMethod.GET) public String getAnimals(Model model) { List<Animal> animalList = animalService.getAnimalList(); model.addAttribute( "animalList" , animalList); return "AnimalList" ; } @RequestMapping (value = "/export" , method = RequestMethod.GET) public ModelAndView getExcel() { List<Animal> animalList = animalService.getAnimalList(); return new ModelAndView( "AnimalListExcel" , "animalList" , animalList); } @RequestMapping ( "/" ) public String hello() { return "hello" ; } @RequestMapping (value = "/hi" , method = RequestMethod.GET) public String hi( @RequestParam ( "name" ) String name, Model model) { String message = "Hi " + name + "!" ; model.addAttribute( "message" , message); return "hi" ; } } |
AnimalService.java
Access DAO via service layer for data.package com.javapapers.spring.mvc; import java.util.ArrayList; import java.util.List; /* Our software gurus talk lot about layering Generally the layer will be like, controller -> Service -> Business -> DAO Just to demonstrate that we have this class */ public class AnimalService { private static List<Animal> animalList = new ArrayList<Animal>(); static { animalList.add( new Animal( 1 , "Lion" , "Wild" , true , 100 )); animalList.add( new Animal( 2 , "Tiger" , "Wild" , true , 90 )); animalList.add( new Animal( 3 , "Goat" , "Domestic" , true , 20 )); animalList.add( new Animal( 4 , "Elephant" , "Wild" , true , 1000 )); } public List<Animal> getAnimalList() { //internally we will call business -> DAO return animalList; } } |
AnimalList.jsp
A JSP view in the Spring MVC<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> < html > < body > < h1 >Example for Spring MVC Excel Export</ h1 > < h2 >Animal List</ h2 > < h3 >< a href = "./export" >Export</ a ></ h3 > < table border = "1px" cellpadding = "8px" > < tr > < td >Id</ td > < td >Name</ td > < td >Type</ td > < td >Aggressive</ td > < td >Weight</ td > </ tr > < c:forEach items = "${animalList}" var = "animal" > < tr > < td >< c:out value = "${animal.id}" /></ td > < td >< c:out value = "${animal.animalName}" /></ td > < td >< c:out value = "${animal.animalType}" /></ td > < td >< c:out value = "${animal.aggressive}" /></ td > < td >< c:out value = "${animal.weight}" /></ td > </ tr > </ c:forEach > </ table > </ body > </ html > |
spring-context.xml
Spring Configuration<? xml version = "1.0" encoding = "UTF-8" ?> < beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc = "http://www.springframework.org/schema/mvc" xmlns:context = "http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> < context:component-scan base-package = "com.javapapers.spring.mvc" /> < mvc:annotation-driven /> < bean class = "org.springframework.web.servlet.view.XmlViewResolver" > < property name = "location" > < value >/WEB-INF/spring-excel-views.xml</ value > </ property > < property name = "order" value = "0" /> </ bean > < bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver" > < property name = "prefix" value = "/view/" /> < property name = "suffix" value = ".jsp" /> < property name = "order" value = "1" /> </ bean > </ beans > |
spring-excel-views.xml
Excel Export View Spring Configuration< beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> < bean id = "AnimalListExcel" class = "com.javapapers.spring.mvc.AnimalListExcelView" > </ bean > </ beans > |
web.xml
<? xml version = "1.0" encoding = "UTF-8" ?> < web-app xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns = "http://java.sun.com/xml/ns/javaee" xmlns:web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id = "WebApp_ID" version = "2.5" > < display-name >Spring MVC Excel Export</ display-name > < servlet > < servlet-name >springMVCDispatcher</ servlet-name > < servlet-class > org.springframework.web.servlet.DispatcherServlet </ servlet-class > < init-param > < param-name >contextConfigLocation</ param-name > < param-value >/WEB-INF/config/spring-context.xml</ param-value > </ init-param > < load-on-startup >1</ load-on-startup > </ servlet > < servlet-mapping > < servlet-name >springMVCDispatcher</ servlet-name > < url-pattern >/</ url-pattern > </ servlet-mapping > </ web-app > |
pom.xml
< project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" > < modelVersion >4.0.0</ modelVersion > < groupId >com.javapapers.spring</ groupId > < artifactId >springexcelexport</ artifactId > < packaging >war</ packaging > < version >0.0.1-SNAPSHOT</ version > < name >Spring MVC Excel Export</ name > < properties > < project.build.sourceEncoding >UTF-8</ project.build.sourceEncoding > </ properties > < dependencies > < dependency > < groupId >org.springframework</ groupId > < artifactId >spring-core</ artifactId > < version >3.0.5.RELEASE</ version > </ dependency > < dependency > < groupId >org.springframework</ groupId > < artifactId >spring-web</ artifactId > < version >3.0.5.RELEASE</ version > </ dependency > < dependency > < groupId >org.springframework</ groupId > < artifactId >spring-webmvc</ artifactId > < version >3.0.5.RELEASE</ version > </ dependency > < dependency > < groupId >org.springframework</ groupId > < artifactId >spring-context</ artifactId > < version >3.0.5.RELEASE</ version > </ dependency > < dependency > < groupId >org.springframework</ groupId > < artifactId >spring-beans</ artifactId > < version >3.0.5.RELEASE</ version > </ dependency > <!-- Excel --> < dependency > < groupId >org.apache.poi</ groupId > < artifactId >poi</ artifactId > < version >3.6</ version > </ dependency > < dependency > < groupId >javax.servlet</ groupId > < artifactId >servlet-api</ artifactId > < version >2.5</ version > < scope >provided</ scope > </ dependency > < dependency > < groupId >javax.servlet</ groupId > < artifactId >jstl</ artifactId > < version >1.2</ version > </ dependency > < dependency > < groupId >com.thoughtworks.xstream</ groupId > < artifactId >xstream</ artifactId > < version >1.3.1</ version > </ dependency > < dependency > < groupId >taglibs</ groupId > < artifactId >standard</ artifactId > < version >1.1.2</ version > </ dependency > </ dependencies > < build > < finalName >springexcelexport</ finalName > < plugins > < plugin > < groupId >org.apache.maven.plugins</ groupId > < artifactId >maven-war-plugin</ artifactId > < version >2.2</ version > </ plugin > < plugin > < groupId >org.apache.maven.plugins</ groupId > < artifactId >maven-surefire-plugin</ artifactId > < version >2.16</ version > < configuration > < skipTests >true</ skipTests > </ configuration > </ plugin > < plugin > < groupId >org.apache.tomcat.maven</ groupId > < artifactId >tomcat7-maven-plugin</ artifactId > < version >2.1</ version > < configuration > < url >http://localhost:8080/manager/text</ url > < server >TomcatAppServer</ server > < path >/springexcelexport</ path > </ configuration > </ plugin > </ plugins > </ build > </ project > |
Output
Subscribe to:
Posts (Atom)