lab manual(network lab)

27
Laboratory Manual of Network Lab (6CS8) B.Tech (Computer Science) VI Semester 2010-11  GLOBAL INSTITUTE OF TECHNOLOGY, JAIPUR (Affiliated to Rajasthan Technical University , Kota)

Upload: master9211

Post on 06-Apr-2018

287 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Lab Manual(Network Lab)

8/2/2019 Lab Manual(Network Lab)

http://slidepdf.com/reader/full/lab-manualnetwork-lab 1/27

Laboratory Manual

of 

Network Lab

(6CS8)

B.Tech (Computer Science)

VI Semester 

2010-11

 

GLOBAL INSTITUTE OF TECHNOLOGY, JAIPUR 

(Affiliated to Rajasthan Technical University , Kota)

Page 2: Lab Manual(Network Lab)

8/2/2019 Lab Manual(Network Lab)

http://slidepdf.com/reader/full/lab-manualnetwork-lab 2/27

Index

1. Syllabus

2. Hardware/Software Requirement

3. Rational behind the lab

4. Practical conducted in the lab

EXPERIMENT-1

Basic Concepts: About Networking Page No.-9

EXPERIMENT-2

Object: Write few basic programs of Perl. Page No.-17

STANDARD PROCEDURES

• Analyzing the Problem

• Designing the Solution:

EXPERIMENT-3

Object: To understand advance constructs of Perl Page No.-18

STANDARD PROCEDURES

• Analyzing the Problem

• Designing the Solution:

EXPERIMENT-4

Object: Find the IP address of a host or turn an IP address into a name Page No.-19

STANDARD PROCEDURES

• Analyzing the Problem

• Designing the Solution:

EXPERIMENT-5 Page No.-19

Object : Connect to an FTP server and get or put files. Automate the one-time transfer of many files to download

the file everyday, which have changed since yesterday. (use Net:FTP)

STANDARD PROCEDURES

• Analyzing the Problem

Page 3: Lab Manual(Network Lab)

8/2/2019 Lab Manual(Network Lab)

http://slidepdf.com/reader/full/lab-manualnetwork-lab 3/27

• Designing the Solution:

EXPERIMENT-6 Page No.-19

Object: Write a program to send mail. The programs should monitor system resources like disk space and notify

admin by mail when disk space becomes dangerously low. (use Net:mail)

STANDARD PROCEDURES

•Analyzing the Problem

• Designing the Solution:

EXPERIMENT-7

Object: Fetch mail from a POP3 server (use Net:pop3) Page No.-21

STANDARD PROCEDURES

• Analyzing the Problem

• Designing the Solution:

EXPERIMENT-8 Page No.-21Object: Find out who owns a domain (use Net:whois , Whois is a service provided by domain name registration

authorities to identify owners of domain names)

STANDARD PROCEDURES

• Analyzing the Problem

• Designing the Solution:

EXPERIMENT-9 Page No.-21

Object: Test whether a machine is alive. Machine can be specified using IP address or domain name of machine.

STANDARD PROCEDURES

• Analyzing the Problem

• Designing the Solution:

EXPERIMENT-10 Page No.-22

Object: You have a URL that fetch its content from a Perl script, convert it to ASCII text (by stripping html tags)

and display it.

STANDARD PROCEDURES

• Analyzing the Problem

• Designing the Solution:

EXPERIMENT-11 Page No.-24

Object: Writing a TCP Client, Writing a TCP Server and Communicate some data over TCP.

STANDARD PROCEDURES

• Analyzing the Problem

• Designing the Solution:

Page 4: Lab Manual(Network Lab)

8/2/2019 Lab Manual(Network Lab)

http://slidepdf.com/reader/full/lab-manualnetwork-lab 4/27

5. References

6. New ideas besides University Syllabus

7. Important Questions

Syllabus:

1. The lab is to be conducted in Perl programming language, Perl works on all platforms (including windows)

2. Write few basic programs of Perl.

a. A Hello World Program

 b. Write a program to add to 10 numbers.

c. Write a program of reading input from the keyboard and displaying them on monitor.

d. Write a program to take two strings as input and compare them

3. To understand advance constructs of Perl

e. Write a program to create a list of your course (all theory courses in current semester) using array and print

them.

f. Write a program to accept ten number, store it into a hash table (Perl have itself) and when asked by user tell

him that number exists or not. (do not store duplicate numbers)

g. Write a program to compute the number of lines in a file.

4. Find the IP address of a host or turn an IP address into a name.

5. Connect to an FTP server and get or put files. Automate the one-time transfer of many files to download the

file everyday, which have changed since yesterday. (use Net:FTP)

6. Write a program to send mail. The programs should monitor system resources like disk space and notify admin

 by mail when disk space becomes dangerously low. (use Net:mail)

7. Fetch mail from a POP3 server (use Net:pop3)

8. Find out who owns a domain (use Net:whois , Whois is a service provided by domain name registration

authorities to identify owners of domain names)

9. Test whether a machine is alive. machine can be specified using IP address or domain name of machine.

10. You have a URL that fetch its content from a Perl script, convert it to ASCII text (by stripping html tags) and

display it.

Page 5: Lab Manual(Network Lab)

8/2/2019 Lab Manual(Network Lab)

http://slidepdf.com/reader/full/lab-manualnetwork-lab 5/27

11. Writing a TCP Client, Writing a TCP Server and Communicate some data over TCP.

Hardware/Software Requirement:

Hardware Requirements:

Processsor: Pentium I

RAM: 128MB

Hard Disk 5GB

Software Requirements: (Operating System)

• Unix systems.

• Macintosh - (OS 7-9 and X) see The MacPerl Pages.

• Windows - see ActiveState Tools Corp.

• VMS.

System Configuration on which lab is conducted

Processor: PentiumI(800mhz)

RAM 256MB

HDD 5GB

Monitor 14’’Color 

Keyboard Multimedia

Mouse Scroll

Rational behind the Network Lab:

Introduction about Lab:

Computer networks represent one of the major drivers behind recent advancements in the Information and

Communication Technology (ICT) field. Therefore, computer networking laboratories are a key resource for

Page 6: Lab Manual(Network Lab)

8/2/2019 Lab Manual(Network Lab)

http://slidepdf.com/reader/full/lab-manualnetwork-lab 6/27

those academic organizations that aim to provide their students with the necessary facilities for experimenting as

well as learning basic and advanced concepts in networking. In traditional computing laboratories, regular users

are not allowed to modify the production network infrastructure or change the workstation network settings, as

this might cause severe problems in terms of service availability and distributed resource management

Typically, users of a computer networking laboratory are students learning and experimenting with the network

itself. Therefore, they should be allowed to experiment on real equipment, modify the network topology, and

intentionally cause and solve failures and other connectivity problems in order to understand how things work in

real-life environments. As a consequence, fully-functional networking laboratory facilities are difficult to designimplement and manage while complying with budget, academic and management objectives. For these reasons

computer networking experiments are often implemented within virtual or simulated environments, even though

this approach may limit the student learning experience. This is the rationale behind the development of

computer networking laboratories incorporating innovative management infrastructures. These infrastructures

allow performance of all the required computer and equipment maintenance tasks in an efficient way while stil

supporting true hands-on (i.e., not simulated) experiences for students as well as providing test bed setups for

research activities.

APPROACHES TO NETWORK LABORATORY DESIGN

A computer network laboratory infrastructure consists of several components:

• active network devices, such as switches, hubs, routers, wireless access points, firewalls;

• passive network devices, such as cabling, patch panels, equipment racks;

• terminal nodes, i.e. personal computers, laptops, PDAs.

In addition, all of these devices require an appropriate management infrastructure (a management plane) in order

to configure them appropriately and to allow interactions that comply with the objectives of a specific laboratory

experiment. Network laboratories can be implemented via several approaches, such as simulated environments,virtualized and physical infrastructures.

Simulation environments are typically used when the experiments to be performed are too expensive or too

difficult to be undertaken with real equipment. In this case, dedicated software is used to simulate the most

relevant behaviors of the network elements and their interactions. Among the most popular network simulation

tools are ns2 and OPNET.

Virtualized infrastructures are based on the concept of virtual machines (VMs), which are used to create multiple

instances of servers, clients and routing systems within the same physical machine. Virtualization software, such

as VMware or Xen, is employed to make a limited set of systems represent a larger set of network equipment and

hosts . It also enables the administrator to easily restore each system configuration to a default state by reloading

a VM when required .

Introduction of Perl Language:

Perl is a programming language which can be used for a large variety of tasks. Both Perl interpreters and Perl

documentation are freely available for Unix, MVS, VMS, MS/DOS, Macintosh, OS/2, Amiga, and other

operating systems. (On Windows systems, Perl can be used in DOS command line mode.)

Page 7: Lab Manual(Network Lab)

8/2/2019 Lab Manual(Network Lab)

http://slidepdf.com/reader/full/lab-manualnetwork-lab 7/27

A typical simple use of Perl would be for extracting information from a text file and printing out a report or for

converting a text file into another form. In fact, the name "Perl" was formed from the expression "  P ractical

 E  xtraction and  Report  Language" . But Perl provides a large number of tools for quite complicated problems

including system administration tasks, which can often be programmed rather  portably in Perl.

Perl can handle strings, dates, binary data, database connectivity, streams, sockets and many more. This ability

to manipulate multiple data types help immensely in data conversion (and by the way, it is much faster thanPL/SQL!). Perl also has provision for lists (or arrays) and for hashes (associative arrays). Perl also supports

references, which are similar to the pointers in C. Lists, hashes and references together make it possible todefine and manipulate powerful custom-defined data-types.

Introduction about Internet Layer:

This model is sometimes called the DOD model since it was designed for the department of defense It is also

called the TCP/IP four layer protocol, or the internet protocol. It has the following layers:

Link - Device driver and interface card which maps to the data link and physical layer of the OSI model.

 Network - Corresponds to the network layer of the OSI model and includes the IP, ICMP, and IGMP protocols.

Transport - Corresponds to the transport layer and includes the TCP and UDP protocols.

Application - Corresponds to the OSI Session, Presentation and Application layers and includes FTP, Telnet ping, Rlogin, rsh, TFTP, SMTP, SNMP, DNS, your program, etc.

Please note the four layer TCP/IP protocol. Each layer has a set of data that it generates.

The Link layer corresponds to the hardware, including the device driver and interface card. The link layer has

data packets associated with it depending on the type of network being used such as ARCnet, Token ring orethernet. In our case, we will be talking about ethernet.The network layer manages the movement of packets

around the network and includes IP, ICMP, and IGMP. It is responsible for making sure that packages reachtheir destinations, and if they don't, reporting errors.

The transport layer is the mechanism used for two computers to exchange data with regards to software. Thetwo types of protocols that are the transport mechanisms are TCP and UDP. There are also other types of

 protocols for systems other than TCP/IP but we will talk about TCP and UDP in this document.

The application layer refers to networking protocols that are used to support various services such as FTP,

Telnet, BOOTP, etc. Note here to avoid confusion, that the application layer is generally referring to protocolssuch as FTP, telnet, ping, and other programs designed for specific purposes which are governed by a specific

set of protocols defined with RFC's (request for comments). However a program that you may write can define

its own data structure to send between your client and server program so long as the program you run on boththe client and server machine understand your protocol. For example when your program opens a socket to

another machine, it is using TCP protocol, but the data you send depends on how you structure it.

Assuming that the protocol stack being used is TCP/IP and the user is going to use an FTP client program to get

or send files from/to a FTP server the following will essentially happen:

1. The user will start the FTP client program on the sending computer.2. The user will select the address (If the user selected a name, a description of DNS would need to be

described complicating this scenario) and port of the server.

Page 8: Lab Manual(Network Lab)

8/2/2019 Lab Manual(Network Lab)

http://slidepdf.com/reader/full/lab-manualnetwork-lab 8/27

3. The user will indicate to the FTP client program that they want to connect to the server.

4. The application layer will send information through the presentation layer to the session layer telling itto open a connection to the other computer at a specific address and port. The presentation layer will not

do much at this time, and the presentation layer is actually handled by the FTP program.

5. The session layer will negociate through to the FTP server for a connection. There are severasynchronization signals sent between the client and server computers just to establish the connection

This is a description of the sending of a signal from the client to the server:

1. The session layer of the client will send a data packet (SYN) signal to the transport layer.

2. The transport layer will add a header (TCP header) to the packet indicating what the source poris and what the destination port is. There are also some other flags and information that will not

 be discussed here to minimize complexity of this explanation.

3. The network layer will add source IP address and destination IP address along with otherinformation in a IP header.

4. The datalink layer will determine (using ARP and routing information which is not discussed

here for brevity) the hardware address of the computer the data is being sent to. An additionalheader (ethernet) will be added at this layer which indicates the hardware address to receive the

message along with other information.

5. The information will be transmitted across the physical wire (hardware layer) until the signalreaches the network card of the server computer. The signal may go through several hubs or

repeaters.6. The FTP server will normally only look for ethernet frames that are matching its own hardware

address.7. The FTP server will see the ethernet frame matching its address and strip the ethernet header

information and send it to the network layer.

8. The network layer will examine the IP address information, strip the IP header, and if the IPaddress matches its own, will send the information to the transport layer.

9. The transport layer will look at the TCP port number and based on the port number and services

 being run, will strip the TCP header and send the information to the appropriate program whichis servicing the requested port.

10. At this point, the session layer in the FTP program will conduct a series of data exchanges

 between itself through all the lower layers to the client computer until a session is established.6. At this point information may be sent through several FTP commands between the client and the server

Every transmission passes through the network layers from the application layer down to the hardware

layer and back up the layers on the receiving computer.

7. When the client decides to terminate the session layer will be informed by the higher layers and willnegociate for the closing of the connection.

Page 9: Lab Manual(Network Lab)

8/2/2019 Lab Manual(Network Lab)

http://slidepdf.com/reader/full/lab-manualnetwork-lab 9/27

EXPERIMENT-1

Basic Concepts: About Networking.

What is Internet

The Internet is a global interconnected network of computers. Using the Internet you can look at documents andimages even view videos or listen to sound files from anywhere in the world using your computer. You can also

use the Internet to publish, so that others can look at your information in any of a number of standard file

formats.

You can also use the Internet to send messages through e-mail, as long as you know the e-mail address of therecipient. The Internet can also be used to transfer files between any two people or computers. The Internet also

creates new communities of individuals, belonging to newsgroups where information is shared between people

with similar interests, even though individuals could be geographically dispersed. Letters and files can be

 posted to newsgroups, where others can share them.

Internet is the world's largest computer network, the network of networks, scattered all over the world. It was

created nearly 25 years ago as a project for the U.S. Department of Defense. Its goal was to create a method for

widely separated computers to transfer data efficiently even in the event of a nuclear attack. From a handful ofcomputer and users in the 1960s, today the Internet has grown to thousands of regional networks that can

connect millions of users. Any single individual, company, or country does not own this global network.

How Internet works

When you connect computers together, you get a "network" which allows computers to "talk" to each other.This communication was originally part of the "operating system" of a computer. The Internet originally arose

as a bunch of UNIX-based (UNIX is an operating system) computers linked together, so a lot of the terms onthe Internet have their origins in the UNIX world. This means a lot of weird cryptic terms or acronyms are used

(words made up from initial letters of longer words). The standard for communicating on the Internet is called"TCP/IP" (pronounced as TCPIP without the '/') which is short for Transmission Control Protocol/Internet

Protocol.

The key concept in TCP/IP is that every computer has to know or can figure out where all other computers areon the network, and can send data by the quickest route, even if part of the route is down. The reason the route

is down might include a computer is shut down or a phone line disconnected or in repair. This is done by

maintaining indexes of all IP addresses in a domain at multiple servers strategically spread around the country

so that messages are quickly routed along the fastest path.

TCP/IP transfers information in small chunks called "packets." Each packet includes the following information

the computer (or last few computers) the data came from, the computer to which it is headed, the data itself, and

error-checking information (to ensure that the individual packet was accurately and completely sent and

received). The elegance of TCP/IP is that a large file can be broken into multiple packets, each sent overdifferent paths in the network. These packets then re-assembled at the other end into one file and saved on the

destination computer.

To access the Internet you need an Internet Service Provider or "ISP". The ISP is connected to the Internet"backbone" which is the permanent cabling of the Internet. This backbone may consist of copper wire, fiber

optic cable, microwave, and even satellite connections between any two points. To you it doesn't matter – the

Page 10: Lab Manual(Network Lab)

8/2/2019 Lab Manual(Network Lab)

http://slidepdf.com/reader/full/lab-manualnetwork-lab 10/27

Internet's TCP/IP works this out for you. You can connect to the Internet in one of two basic ways, dialing into

an Internet Service Provider's computer, or with a direct connection to an Internet Service Provider. Thedifference is mainly in the speed and cost.

The previous figure gives a pictorial representation of how Internet works. You want to access a web site that is

hosted on a server somewhere in the world (say USA) and you want to access the information from India. You

connect (using a computer and modem - Dial up access) to your local Internet Access Provider, then you type inthe address of your site. Your request is sent form the local ISP's server through the different computers in the

network (Internet backbone) till it reaches the server where you have hosted your site. It is like a letter traveling

though the various postal networks and reaching the addressee’s place. Then the information stored on the website that you are trying to access is sent back to your computer so that you can access it.

Networking Basics

 The Internet protocol suite is the set of protocols that implement the protocol stack on which

the Internet runs. It is sometimes called the TCP/IP protocol suite, after two of the many

protocols that make up the suite: the Transmission Control Protocol ( TCP) and the Internet

Protocol (IP), which were the first two defined. The authoritative reference on this subject is RFC

1122.

 The Internet protocol suite can be described by analogy with the OSI model, which describes the

layers of a protocol stack, not all of which correspond well with Internet practice. In a protocol

stack, each layer solves a set of problems involving the transmission of data, and provides a

well-defined service to the higher layers. Higher layers are logically closer to the user and dea

with more abstract data, relying on lower layers to translate data into forms that can eventually

be physically manipulated.

 The Internet model was produced as the solution to a practical engineering problem. The OSI

model, on the other hand, was a more theoretical approach, and was also produced at an earlier

Page 11: Lab Manual(Network Lab)

8/2/2019 Lab Manual(Network Lab)

http://slidepdf.com/reader/full/lab-manualnetwork-lab 11/27

stage in the evolution of  networks. Therefore, the OSI model is easier to understand, but the

 TCP/IP model is the one in actual use. It is helpful to have an understanding of the OSI mode

before learning TCP/IP, as the same principles apply, but are easier to understand in the OS

model. The following diagram attempts to show where various TCP/IP and other protocols would

reside in the original OSI model:

7

 

Applicati

on 

e.g. HTTP, SMTP, SNMP, FTP, Telnet, NFS

6

 

Presentat

ion e.g. XDR, ASN.1, SMB, AFP

5

 Session e.g. ISO 8327 / CCITT X.225, RPC, NetBIOS, ASP

4

 Transport e.g. TCP, UDP, RTP, SPX, ATP

3

 Network  

e.g. IP, ICMP, IGMP, X.25, CLNP, ARP, OSPF, RIP,

IPX, DDP

2

 Data Link 

e.g. Ethernet, Token ring, PPP, HDLC, Frame

relay, ISDN, ATM

1

 Physical e.g. electricity, radio, laser

Commonly, the top three layers of the OSI model (Application, Presentation and Session) are considered as asingle Application Layer in the TCP/IP suite. Because the TCP/IP suite has no unified session layer on which

higher layers are built, these functions are typically carried out (or ignored) by individual applications. A

simplified TCP/IP interpretation of the stack is shown below:

As we see on the diagram above, computers running on the Internet communicate to each other

using either the Transmission Control Protocol (TCP) or the User Datagram Protocol (UDP). When

you write Java programs that communicate over the network, you are programming at the

application layer. Typically, you don't need to concern yourself with the TCP and UDP layers

Instead, you can use the classes in the java.net package. These classes provide system-

Page 12: Lab Manual(Network Lab)

8/2/2019 Lab Manual(Network Lab)

http://slidepdf.com/reader/full/lab-manualnetwork-lab 12/27

independent network communication. However, to decide which Java classes your programs

should use, you do need to understand how TCP and UDP differ.

TCP

When two applications want to communicate to each other reliably, they establish a connection

and send data back and forth over that connection. This is analogous to making a telephone call

If you want to speak to Aunt Beatrice in Kentucky, a connection is established when you dial her

phone number and she answers. You send data back and forth over the connection by speaking

to one another over the phone lines. Like the phone company, TCP guarantees that data sent

from one end of the connection actually gets to the other end and in the same order it was sent.

Otherwise, an error is reported.

TCP provides a point-to-point channel for applications that require reliable communications. The Hypertext

Transfer Protocol (HTTP), File Transfer Protocol (FTP), and Telnet are all examples of applications that require

a reliable communication channel. The order in which the data is sent and received over the network is criticalto the success of these applications. When HTTP is used to read from a URL, the data must be received in the

order in which it was sent. Otherwise, you end up with a jumbled HTML file, a corrupt zip file, or some other

invalid information.

Definition:  TCP (Transmission Control Protocol) is a connection-based protocol that provides a

reliable flow of data between two computers.

UDP

 The UDP protocol provides for communication that is not guaranteed between two applications

on the network. UDP is not connection-based like TCP. Rather, it sends independent packets of

data, called datagrams, from one application to another. Sending datagrams is much like

sending a letter through the postal service: The order of delivery is not important and is not

guaranteed, and each message is independent of any other.

Definition:  UDP (User Datagram Protocol) is a protocol that sends independent packets of data

called datagrams, from one computer to another with no guarantees about arrival. UDP is not

connection-based like TCP.

For many applications, the guarantee of reliability is critical to the success of the transfer of information from

one end of the connection to the other. However, other forms of communication don't require such strictstandards. In fact, they may be slowed down by the extra overhead or the reliable connection may invalidate the

service altogether.

Consider, for example, a clock server that sends the current time to its client when requested to do so. If the

client misses a packet, it doesn't really make sense to resend it because the time will be incorrect when the clientreceives it on the second try. If the client makes two requests and receives packets from the server out of order,

it doesn't really matter because the client can figure out that the packets are out of order and make another

request. The reliability of TCP is unnecessary in this instance because it causes performance degradation andmay hinder the usefulness of the service.

Another example of a service that doesn't need the guarantee of a reliable channel is the ping command. The

 purpose of the ping command is to test the communication between two programs over the network. In fact,

Page 13: Lab Manual(Network Lab)

8/2/2019 Lab Manual(Network Lab)

http://slidepdf.com/reader/full/lab-manualnetwork-lab 13/27

 ping needs to know about dropped or out-of-order packets to determine how good or bad the connection is. A

reliable channel would invalidate this service altogether.

The UDP protocol provides for communication that is not guaranteed between two applications on the network.

UDP is not connection-based like TCP. Rather, it sends independent packets of data from one application to

another. Sending datagrams is much like sending a letter through the mail service: The order of delivery is not

important and is not guaranteed, and each message is independent of any others.

Note: Many firewalls and routers have been configured not to allow UDP packets. If you'rehaving trouble connecting to a service outside your firewall, or if clients are having trouble

connecting to your service, ask your system administrator if UDP is permitted.

Understanding Ports

Generally speaking, a computer has a single physical connection to the network. All data

destined for a particular computer arrives through that connection. However, the data may be

intended for different applications running on the computer. So how does the computer know to

which application to forward the data? Through the use of  ports.

Data transmitted over the Internet is accompanied by addressing information that identifies the computer and

the port for which it is destined. The computer is identified by its 32-bit IP address, which IP uses to deliver

data to the right computer on the network. Ports are identified by a 16-bit number, which TCP and UDP use todeliver the data to the right application.

In connection-based communication such as TCP, a server application binds a socket to a specific port number

This has the effect of registering the server with the system to receive all data destined for that port. A client can

then rendezvous with the server at the server's port, as illustrated here:

Definition: The TCP and UDP protocols use ports to map incoming data to a particular process

running on a computer.

In datagram-based communication such as UDP, the datagram packet contains the port number of its destination

and UDP routes the packet to the appropriate application, as illustrated in this figure:

Port numbers range from 0 to 65,535 because ports are represented by 16-bit numbers. The port

numbers ranging from 0 - 1023 are restricted; they are reserved for use by well-known services

Page 14: Lab Manual(Network Lab)

8/2/2019 Lab Manual(Network Lab)

http://slidepdf.com/reader/full/lab-manualnetwork-lab 14/27

such as HTTP and FTP and other system services. These ports are called well-known ports. Your

applications should not attempt to bind to them.

Networking Classes in the JDK 

 Through the classes in java.net, Java programs can use TCP or UDP to communicate over the

Internet. The URL, URLConnection, Socket, and ServerSocket classes all use TCP to communicate

over the network. The DatagramPacket, DatagramSocket, and MulticastSocket classes are for use

with UDP.

The Internet Protocol Suite 

The java.net package provides a set of classes that support network programming using the communication

 protocols employed by the Internet. These protocols are known as the   Internet protocol suite and include the

 Internet Protocol (IP), the Transport Control Protocol (TCP), and the User Datagram Protocol (UDP) as wel

as other, less-prominent supporting protocols. Although this section cannot provide a full description of theInternet protocols, it gives you the basic information that you need to get started with Java network

 programming. In order to take full advantage of this chapter, you need an Internet connection.

What Is the Internet and How Does It Work?

Asking the question What is the Internet? may bring about a heated discussion in some circles. In this book, the

 Internet is defined as the collection of all computers that are able to communicate, using the Internet protocol

suite, with the computers and networks registered with the  Internet Network Information Center  (InterNIC)This definition includes all computers to which you can directly (or indirectly through a firewall) send Internet

Protocol packets.

Computers on the Internet communicate by exchanging packets of data, known as Internet Protocol, or IP,

 packets. IP is the network protocol used to send information from one computer to another over the Internet. All

computers on the Internet (by our definition in this book) communicate using IP. IP moves informationcontained in IP packets. The IP packets are routed via special routing algorithms from a source computer that

sends the packets to a destination computer that receives them. The routing algorithms figure out the best wayto send the packets from source to destination.

In order for IP to send packets from a source computer to a destination computer, it must have some way of

identifying these computers. All computers on the Internet are identified using one or more IP addresses. A

computer may have more than one IP address if it has more than one interface to computers that are connectedto the Internet.

IP addresses are 32-bit numbers. They may be written in decimal, hexadecimal, or other formats, but the most

common format is dotted decimal notation. This format breaks the 32-bit address up into four bytes and writeseach byte of the address as unsigned decimal integers separated by dots. For example, one of my IP addresses is0xccD499C1. Because 0xcc = 204, 0xD4 = 212, 0x99 = 153, and 0xC1 = 193, my address in dotted decimal form

is 204.212.153.193.

IP addresses are not easy to remember, even using dotted decimal notation. The Internet has adopted a

mechanism, referred to as the  Domain Name System (DNS), whereby computer names can be associated withIP addresses. These computer names are referred to as domain names. The DNS has several rules that determine

how domain names are constructed and how they relate to one another. For the purposes of this chapter, it is

sufficient to know that domain names are computer names and that they are mapped to IP addresses.

Page 15: Lab Manual(Network Lab)

8/2/2019 Lab Manual(Network Lab)

http://slidepdf.com/reader/full/lab-manualnetwork-lab 15/27

The mapping of domain names to IP addresses is maintained by a system of  domain name servers. These

servers are able to look up the IP address corresponding to a domain name. They also provide the capability tolook up the domain name associated with a particular IP address, if one exists.

As I mentioned, IP enables communication between computers on the Internet by routing data from a source

computer to a destination computer. However, computer-to-computer communication only solves half of the

network communication problem. In order for an application program, such as a mail program, to communicatewith another application, such as a mail server, there needs to be a way to send data to specific programs within

a computer.

Ports are used to enable communication between programs. A  port  is an address within a computer. Port

addresses are 16-bit addresses that are usually associated with a particular application protocol. An applicationserver, such as a Web server or an FTP server, listens on a particular port for service requests, performs

whatever service is requested of it, and returns information to the port used by the application program

requesting the service.

Internet services

Servers in Internet provide various services, accessible by the Internet users. Examples of such services are

WWW, FTP, IRC, E-Mail, etc.

Popular Internet application protocols are associated with well-known ports and wel-known Internet services

The server programs implementing these protocols listen on these ports for service requests. The well-known

 ports for some common Internet application protocols are:

Port Protocol Service description21 File Transfer Protocol (FTP) Transfers files

22 SSH (Secure Shell Protocol)

Allows secure remote

administration through standard

shell (console)

25 Simple Mail Transfer Protocol Send email

80HyperText Transfer Protocol

(HTTP)

Accesse the WWW (World Wide

Web)110 Post Office Protocol Receive email

The well-known ports are used to standardize the location of Internet services.

What is WWW

A technical definition of the World Wide Web is: all the resources and users on the Internet that

are using the Hypertext Transfer Protocol (HTTP). A broader definition is:

"The World Wide Web is the universe of network-accessible information, an embodiment of

human knowledge."

Actually, World Wide Web is a distributed information system of  Internet  servers that support specially

formatted documents. The documents are formatted in a markup language called HTML ( HyperText Markup Language) that supports links to other documents, as well as graphics, audio, and video files. This means youcan jump from one document to another simply by clicking on hot spots. Not all Internet servers are part of the

World Wide Web. World Wide Web is not synonymous with the Internet !

Page 16: Lab Manual(Network Lab)

8/2/2019 Lab Manual(Network Lab)

http://slidepdf.com/reader/full/lab-manualnetwork-lab 16/27

There are several applications called Web browsers that make it easy to access the World Wide Web; Two of

the most popular being Netscape Navigator (Mozilla) and Microsoft's Internet Explorer .

Connection-Oriented Versus Connectionless Communication

Transport protocols are used to deliver information from one port to another and thereby enable communication  between application programs. They use either a connection-oriented or connectionless method o

communication. TCP is a connection-oriented protocol and UDP is a connectionless transport protocol.

The TCP connection-oriented protocol establishes a communication link between a source port/IP address and a

destination port/IP address. The ports are bound together via this link until the connection is terminated and thelink is broken. An example of a connection-oriented protocol is a telephone conversation. A telephone

connection is established, communication takes place, and then the connection is terminated.

The reliability of the communication between the source and destination programs is ensured through error-

detection and error-correction mechanisms that are implemented within TCP. TCP implements the connectionas a stream of bytes from source to destination. This feature allows the use of the stream I/O classes provided byjava.io.

The UDP connectionless protocol differs from the TCP connection-oriented protocol in that it does not establisha link for the duration of the connection. An example of a connectionless protocol is postal mail. To mail

something, you just write down a destination address (and an optional return address) on the envelope of the

item you're sending and drop it in a mailbox. When using UDP, an application program writes the destination

 port and IP address on a datagram and then sends the datagram to its destination. UDP is less reliable than TCP because there are no delivery-assurance or error-detection and -correction mechanisms built into the protocol.

Application protocols such as FTP, SMTP, and HTTP use TCP to provide reliable, stream-based

communication between client and server programs. Other protocols, such as the Time Protocol, use UDP because speed of delivery is more important than end-to-end reliability.

The Client/Server Computing Model and the Internet

The Internet provides a variety of services that contribute to its appeal. These services include e-mail

newsgroups, file transfer, remote login, and the Web. Internet services are organized according to a client/serverarchitecture. Client programs, such as Web browsers and file transfer programs, create connections to servers,

such as Web and FTP servers. The clients make requests of the server, and the server responds to the requests

 by providing the service requested by the client.

The Web provides a good example of client/server computing. Web browsers are the clients and Web serversare the servers. Browsers request HTML files from Web servers on your behalf by establishing a connection

with a Web server and submitting file requests to the server. The server receives the file requests, retrieves thefiles, and sends them to the browser over the established connection. The browser receives the files and displaysthem to your browser window.

Sockets and Client/Server Communication

Clients and servers establish connections and communicate via  sockets. Connections are communication linksthat are created over the Internet using TCP. Some client/server applications are also built around the

connectionless UDP. These applications also use sockets to communicate.

Page 17: Lab Manual(Network Lab)

8/2/2019 Lab Manual(Network Lab)

http://slidepdf.com/reader/full/lab-manualnetwork-lab 17/27

Sockets are the endpoints of Internet communication. Clients create client sockets and connect them to server

sockets. Sockets are associated with a host address and a port address. The host address is the IP address of thehost where the client or server program is located. The port address is the communication port used by the client

or server program. Server programs use the well-known port number associated with their application protocol.

A client communicates with a server by establishing a connection to the socket of the server. The client and

server then exchange data over the connection. Connection-oriented communication is more reliable thanconnectionless communication because the underlying TCP provides message-acknowledgment, error

detection, and error-recovery services.

When a connectionless protocol is used, the client and server communicate by sending datagrams to each other's

socket. The UDP is used for connectionless protocols. It does not support reliable communication like TCP.

EXPERIMENT-2

Object: Write few basic programs of Perl.

a. A Hello World Program

#!/usr/local/bin/perl

#

# Program to do the obvious

#

  print 'Hello world.'; # Print a message

Every perl program starts with this statement as its very first line: #!/usr/local/bin/perl

Comments can be inserted in a program using the "#" symbol.

 b. Write a program to add to 10 numbers.

#!/usr/local/bin/perl

#PICK A NUMBER$x = 81;$add=$x+1+2+3+4+5+6+7+8+9;Print” total value $add; #print the total value

Page 18: Lab Manual(Network Lab)

8/2/2019 Lab Manual(Network Lab)

http://slidepdf.com/reader/full/lab-manualnetwork-lab 18/27

c. Write a program of reading input from the keyboard and displaying them on monitor.

#!/usr/bin/perl$userinput = <STDIN>;chomp ($userinput);print "User typed $userinput\n";

d. Write a program to take two strings as input and compare them

#!/usr/bin/perluse strict;use warnings;

my $string1 = 'three';my $string2 = 'five';

if ($string1 == $string2) {print "Equal\n";} else {print "Not equal\n";}

EXPERIMENT-3

Object: To understand advance constructs of Perl.

e. Write a program to create a list of your course (all theory courses in current semester) using array and

 print them.

#!/usr/bin/perl

print "content-type: text/html \n\n"; #HTTP HEADER

# DEFINE AN ARRAY@coins = ("MBA","B.tech","M.tech");

# PRINT THE WHOLE ARRAYprint "@coins";

# PRINT EACH SCALAR ELEMENTprint "<br />";

print $coins[0]; #Prints the first elementprint "<br />";print $coins[1]; #Prints the 2nd elementprint "<br />";print $coins[2]; #Prints the 3rd element

f. Write a program to accept ten number, store it into a hash table.

#!/usr/bin/perl

print "content-type: text/html \n\n";

Page 19: Lab Manual(Network Lab)

8/2/2019 Lab Manual(Network Lab)

http://slidepdf.com/reader/full/lab-manualnetwork-lab 19/27

# DEFINE A HASH%coins = ( "Quarter" , 25,

"Dime" , 10,"Nickel", 5 );

 # LOOP THROUGH ITwhile (($key, $value) = each(%coins)){

print $key.", ".$value."<br />";}

g. Write a program to compute the number of lines in a file.

#!/usr/bin/perl

open(FILE, "< $file") or die "can't open $file: $!";$count++ while <FILE>;# $count now holds the number of lines read

EXPERIMENT-4

Object: Find the IP address of a host or turn an IP address into a name.

#!/usr/bin/perluse Socket;

use Sys::Hostname;my $host = hostname();my $addr = inet_ntoa(scalar(gethostbyname($name)) || 'localhost');

EXPERIMENT-5

Object: Connect to an FTP server and get or put files. Automate the one-time transfer of many files to download

the file everyday, which have changed since yesterday. (use Net:FTP)

#!/usr/bin/perluse Net::FTP;#procedure:$ftp = Net::FTP->new("ftp.host.com") or die "Can't connect: $@\n";$ftp->login($username, $password) or die "Couldn't login\n";$ftp->cwd($directory) or die "Couldn't change directory\n";

$ftp->get($filename) or die "Couldn't get $filename\n";$ftp->put($filename) or die "Couldn't put $filename\n";

EXPERIMENT-6

Object: Write a program to send mail. The programs should monitor system resources like disk space and notify

admin by mail when disk space becomes dangerously low. (use Net:mail)

Simple mail sending:

#!/usr/local/bin/perl -w

Page 20: Lab Manual(Network Lab)

8/2/2019 Lab Manual(Network Lab)

http://slidepdf.com/reader/full/lab-manualnetwork-lab 20/27

use Net::SMTP;

$smtp = Net::SMTP->new('mailhost');

$smtp->mail($ENV{USER});$smtp->to('postmaster');

$smtp->data();$smtp->datasend("To: postmaster\n");

$smtp->datasend("\n");$smtp->datasend("A simple test message\n");$smtp->dataend();

$smtp->quit;

Another Solution for monitoring Disk Space

#!/usr/bin/perl# Available under BSD License. See url for more info:# http://www.cyberciti.biz/tips/howto-write-perl-script-to-monitor-disk-space.htmluse strict;use warnings;use Filesys::DiskSpace;

 # file system to monitormy $dir = "/home"; # warning levelmy $warning_level=10; # email setupmy $to='[email protected]';my $from='[email protected]';my $subject='Low Disk Space'; # get df

my ($fs_type, $fs_desc, $used, $avail, $fused, $favail) = df $dir; # calculatemy $df_free = (($avail) / ($avail+$used)) * 100.0; # compareif ($df_free < $warning_level) {my $out = sprintf("WARNING Low Disk Space on $dir : %0.2f%% ()\n",$df_free); # send email using UNIX/Linux sendmailopen(MAIL, "|/usr/sbin/sendmail -t"); ## Mail Headerprint MAIL "To: $to\\n";

print MAIL "From: $from\\n";print MAIL "Subject: $subject\\n"; ## Mail Bodyprint MAIL $out; close(MAIL);}

Another solution

Page 21: Lab Manual(Network Lab)

8/2/2019 Lab Manual(Network Lab)

http://slidepdf.com/reader/full/lab-manualnetwork-lab 21/27

Use the CPAN module Mail::Mailer:

use Mail::Mailer;

$mailer = Mail::Mailer->new("sendmail");$mailer->open({ From => $from_address,

To => $to_address,Subject => $subject,

})

or die "Can't open: $!\n";print $mailer $body;$mailer->close();

Or, use the sendmail program directly:

open(SENDMAIL, "|/usr/lib/sendmail -oi -t -odq")or die "Can't fork for sendmail: $!\n";

print SENDMAIL <<"EOF";From: User Originating Mail <me\@host>To: Final Destination <you\@otherhost>Subject: A relevant subject line

Body of the message goes here, in as many lines as you like.EOFclose(SENDMAIL) or warn "sendmail didn't close nicely";

EXPERIMENT-7

Object: Fetch mail from a POP3 server (use Net:pop3).

#!/usr/bin/perl

use Net::FTP;

$pop = Net::POP3->new($mail_server)or die "Can't open connection to $mail_server : $!\n";

defined ($pop->login($username, $password))or die "Can't authenticate: $!\n";

$messages = $pop->listor die "Can't get list of undeleted messages: $!\n";

foreach $msgid (keys %$messages) {$message = $pop->get($msgid);unless (defined $message) {

warn "Couldn't fetch $msgid from server: $!\n";next;

}# $message is a reference to an array of lines

$pop->delete($msgid);}

EXPERIMENT-8

Object: Find out who owns a domain (use Net:whois , Whois is a service provided by domain name registration

authorities to identify owners of domain names)

#!/usr/bin/perl

use Net::Whois;

Page 22: Lab Manual(Network Lab)

8/2/2019 Lab Manual(Network Lab)

http://slidepdf.com/reader/full/lab-manualnetwork-lab 22/27

$domain_obj = Net::Whois::Domain->new($domain_name)or die "Couldn't get information on $domain_name: $!\n";

# call methods on $domain_obj to get name, tag, address, etc.

EXPERIMENT-9

Object: Test whether a machine is alive. machine can be specified using IP address or domain name of machine.

#!/usr/bin/perl

use Net::Ping;

$p = Net::Ping->new()or die "Can't create new ping object: $!\n";

print "$host is alive" if $p->ping($host);$p->close;

 Another solution

use Net::Ping;

$p = Net::Ping->new();print "$host is alive.\n" if $p->ping($host);$p->close();

$p = Net::Ping->new("icmp");$p->bind($my_addr); # Specify source interface of pingsforeach $host (@host_array){

print "$host is ";print "NOT " unless $p->ping($host, 2);print "reachable.\n";sleep(1);

}$p->close();

$p = Net::Ping->new("tcp", 2);# Try connecting to the www port instead of the echo port$p->{port_num} = getservbyname("http", "tcp");while ($stop_time > time()){

print "$host not reachable ", scalar(localtime()), "\n"unless $p->ping($host);

sleep(300);}undef($p);

# High precision syntax (requires Time::HiRes)$p = Net::Ping->new();$p->hires();($ret, $duration, $ip) = $p->ping($host, 5.5);printf("$host [ip: $ip] is alive (packet return time: %.2f ms)\n", 1000 * $duration)if $ret;

$p->close();

# For backward compatibilityprint "$host is alive.\n" if pingecho($host);

Page 23: Lab Manual(Network Lab)

8/2/2019 Lab Manual(Network Lab)

http://slidepdf.com/reader/full/lab-manualnetwork-lab 23/27

EXPERIMENT-10

Object: You have a URL that fetch its content from a Perl script, convert it to ASCII text (by stripping html

tags) and display it.

Fetching a URL from a Perl Script

#!/usr/bin/perl

use LWP::Simple;$content = get($URL);#-----------------------------use LWP::Simple;unless (defined ($content = get $URL)) {

die "could not get $URL\n";}#-----------------------------# download the following standalone program#!/usr/bin/perl -w# titlebytes - find the title and size of documentsuse LWP::UserAgent;use HTTP::Request;

use HTTP::Response;use URI::Heuristic;my $raw_url = shift or die "usage: $0 url\n";my $url = URI::Heuristic::uf_urlstr($raw_url);$| = 1; # toflush next lineprintf "%s =>\n\t", $url;my $ua = LWP::UserAgent->new();$ua->agent("Schmozilla/v9.14 Platinum"); # give it time, it'll get theremy $req = HTTP::Request->new(GET => $url);$req->referer("http://wizard.yellowbrick.oz");

# perplex the log analysersmy $response = $ua->request($req);if ($response->is_error()) {

printf " %s\n", $response->status_line;} else {

my $count;my $bytes;my $content = $response->content();$bytes = length $content;$count = ($content =~ tr/\n/\n/);printf "%s (%d lines, %d bytes)\n", $response->title(), $count, $bytes; }

Converting ASCII to HTML:

use HTML::Entities;$_ = encode_entities($_, "\200-\377");

if (/^\s/) {# Paragraphs beginning with whitespace are wrapped in <PRE>s{(.*)$} {<PRE>\n$1</PRE>\n}s; # indented verbatim

} else {s{^(>.*)} {$1<BR>}gm; # quoted texts{<URL:(.*?)>} {<A HREF="$1">$1</A>}gs # embedded URL (good)

||s{(http:\S+)} {<A HREF="$1">$1</A>}gs; # guessed URL (bad)s{\*(\S+)\*} {<STRONG>$1</STRONG>}g; # this is *bold* heres{\b_(\S+)\_\b} {<EM>$1</EM>}g; # this is _italics_ here

Page 24: Lab Manual(Network Lab)

8/2/2019 Lab Manual(Network Lab)

http://slidepdf.com/reader/full/lab-manualnetwork-lab 24/27

s{^} {<P>\n}; # add paragraph tag}

#-----------------------------BEGIN {

print "<TABLE>";$_ = encode_entities(scalar <>);s/\n\s+/ /g; # continuation lineswhile ( /^(\S+?:)\s*(.*)$/gm ) { # parse heading

print "<TR><TH ALIGN='LEFT'>$1</TH><TD>$2</TD></TR>\n";

}print "</TABLE><HR>";

}

Converting HTML to ASCII:

#-----------------------------$ascii = `lynx -dump $filename`;#-----------------------------use HTML::FormatText;use HTML::Parse;

$html = parse_htmlfile($filename);$formatter = HTML::FormatText->new(leftmargin => 0, rightmargin => 50);

$ascii = $formatter->format($html);#-----------------------------use HTML::TreeBuilder;use HTML::FormatText;

$html = HTML::TreeBuilder->new();$html->parse($document);

$formatter = HTML::FormatText->new(leftmargin => 0, rightmargin => 50);

$ascii = $formatter->format($html);#-----------------------------

EXPERIMENT-11

Object: Writing a TCP Client, Writing a TCP Server and Communicate some data over TCP

TCP Client:

#!/usr/bin/perl

use IO::Socket;

$socket = IO::Socket::INET->new(PeerAddr => $remote_host,PeerPort => $remote_port,Proto => "tcp",Type => SOCK_STREAM)

or die "Couldn't connect to $remote_host:$remote_port : $@\n";

# ... do something with the socketprint $socket "Why don't you call me anymore?\n";

$answer = <$socket>;

# and terminate the connection when we're doneclose($socket);

Page 25: Lab Manual(Network Lab)

8/2/2019 Lab Manual(Network Lab)

http://slidepdf.com/reader/full/lab-manualnetwork-lab 25/27

or create a socket by hand for better control:

use Socket;

# create a socketsocket(TO_SERVER, PF_INET, SOCK_STREAM, getprotobyname('tcp'));

# build the address of the remote machine$internet_addr = inet_aton($remote_host)

or die "Couldn't convert $remote_host into an Internet address: $!\n";$paddr = sockaddr_in($remote_port, $internet_addr);

# connectconnect(TO_SERVER, $paddr)

or die "Couldn't connect to $remote_host:$remote_port : $!\n";

# ... do something with the socketprint TO_SERVER "Why don't you call me anymore?\n";

# and terminate the connection when we're doneclose(TO_SERVER);

TCP Server:#!/usr/bin/perl

use IO::Socket;

$server = IO::Socket::INET->new(LocalPort => $server_port,Type => SOCK_STREAM,Reuse => 1,Listen => 10 ) # or SOMAXCONN

or die "Couldn't be a tcp server on port $server_port : $@\n";

while ($client = $server->accept()) {# $client is the new connection

}

close($server);

Or, craft it by hand for better control:

use Socket;

# make the socketsocket(SERVER, PF_INET, SOCK_STREAM, getprotobyname('tcp'));

# so we can restart our server quicklysetsockopt(SERVER, SOL_SOCKET, SO_REUSEADDR, 1);

# build up my socket address$my_addr = sockaddr_in($server_port, INADDR_ANY);bind(SERVER, $my_addr)

or die "Couldn't bind to port $server_port : $!\n";

# establish a queue for incoming connectionslisten(SERVER, SOMAXCONN)

or die "Couldn't listen on port $server_port : $!\n";

# accept and process connectionswhile (accept(CLIENT, SERVER)) {

# do something with CLIENT

Page 26: Lab Manual(Network Lab)

8/2/2019 Lab Manual(Network Lab)

http://slidepdf.com/reader/full/lab-manualnetwork-lab 26/27

}

close(SERVER);

Communicating Over TCP:

Use print or < > :

print SERVER "What is your name?\n";chomp ($response = <SERVER>);

Or, use send and recv :

defined (send(SERVER, $data_to_send, $flags))or die "Can't send : $!\n";

recv(SERVER, $data_read, $maxlen, $flags)or die "Can't receive: $!\n";

Or, use the corresponding methods on an IO::Socket object:

use IO::Socket;

$server->send($data_to_send, $flags)or die "Can't send: $!\n";

$server->recv($data_read, $flags)or die "Can't recv: $!\n";

To find out whether data can be read or written, use the select function, which is nicely wrapped by the

standard IO::Socket class:

use IO::Select;

$select = IO::Select->new();$select->add(*FROM_SERVER);$select->add($to_client);

@read_from = $select->can_read($timeout);foreach $socket (@read_from) {

# read the pending data from $socket}

References:

1. Network Programming with Perl (1st edition) by Lincoln Stein

2. Programming the Network with Perl by Paul Barry

3. Perl Cookbook by Tom Christiansen & Nathan Torkington

Page 27: Lab Manual(Network Lab)

8/2/2019 Lab Manual(Network Lab)

http://slidepdf.com/reader/full/lab-manualnetwork-lab 27/27

New ideas besides University Syllabus:

1. Programs regarding to the different Client-Server Architecture.

2. Programs based on the Encryption/Decryption techniques.

3. Make able to make many network application programs.

Important Questions:

1. You want to exchange messages with another process using UDP (datagrams).

2. You want to write a UDP server.

3. You want to simulate a telnet connection from your program by logging into a remote machine, issuing

commands, and reacting to what is sent.