You are on page 1of 104

(Kalasalingam Academy of Research and Education)

Anand Nagar, Krishnankoil-626190.

• Dr.S.Radhakrishnan., HoD/CSE
• Mr.M.Gomathy Nayagam
• Ms.D.Kavitha
• Mr.B.Barnidharan
• Ms.M.Chitra
Introduction

Purpose of the Laboratory:


The main goal of this laboratory is to give you a basic idea about the network
related UNIX commands, different process involved to create a socket programming and
the idea about to create client server based application using TCP or UDP protocol.
After you completed this laboratory experiment, you should be familiar in socket
programming, get a clear idea about the layered concept of network design and the
protocols used in various layers, apply the concepts of routing and congestion in
networks, able to know about cryptography and its applications in network security and
get exposure in Internet and Web Technologies

Do's and Don'ts in the Lab:


Do's
• Be punctual

• Wear the prescribed uniform.

• Remove the foot wares strictly.

• While entering the Lab, the students should sign in the student login register.

• Keep personal belonging in allotted place.

• Student should bring their ID card during the lab hour

• Submit the observation record of previous experiments.

• Students are allowed to do experiments only during lab hours.

• Use the allotted system and login as per the instruction only.

• Take the printouts regularly.

• While leaving the lab arrange the chairs you were sittings in the proper way.

• Help to maintain the lab clean.

• Maintain strict discipline.


Don'ts
• Don’t use the system for typing letters, reports etc., during the lab hours.

2
• Don’t use other’s logins.

• Don’t change the configurations/system settings.

• Don’t bring floppies, CDs inside the lab without permission.

• Don’t load unauthorized software.

Lesson Plan:
No of Cumulative
Expt.
Name of the Experiment Periods No of
No
Periods
1. Basic Unix Commands 3 3
2. Introduction to Socket Programming 3 6
Application for Client-Server Environment
3. 3 9
(TCP,UDP)
4. Multicast Client/ Server Application 3 12
5. Data Link Layer Operations 3 15
6. Domain Name Service 3 21
7. Getting the MAC Address 3 24
8. HTTP Download 3 27
9. Cryptography 3 30
10. Remote Command Execution 3 33
11 Remote Command Invocation 3 36
Model Lab – I 3 39

3
Lab Session: 1 Basic UNIX Commands

Aim:

 To study the various basic and network related UNIX commands.

System and Software Requirements:

 PC with UNIX/ Linux Operating systems.

Basic UNIX/ Linux Commands and its Purpose


Basic Commands

S.NO COMMAND PURPOSE


1 man Shows help on a specific command.
<commandname>
2 pwd command prints the full pathname of your current
working directory
Shows you what directory you are in currently, your
working directory.
3 ls Lists your files
ls –l
Lists your files in 'long format', which contains the
exact size of the file, who owns the file and who has the
right to look at it, and when it was last modified.
ls -a
Lists all files, including the ones whose filenames
begin in a dot, which you do not always want
to see. There are many more options, for example to list
fFiles by size, by date, recursively etc.
ls -al
Lists files and directories in alphabetical order.
ls -F
Shows the difference between directories and
ordinary files.
4 alljobs Lists all your jobs that are currently running.
5 cd Connects to your login directory
cd .
Takes you to the directory you're currently in.
cd ..
Connects to the directory one level up from the
current

4
directory
cd dirname
Connects to the directory named dirname.

6 chmod change the permissions of a file


Symbol Meaning
U User
G Group
O Other
A All
R Read
W write (and delete)
X execute (and access directory)
+ add permission
- take away permission
chmod go-rwx biglist to remove read write and execute
permissions on the file biglist for the group and others,
type
7 chgrp group-name Changes group affiliation of filename to group-name.
filename chgrp -R group-name dirname
Changes group affiliation of dirname and all
files within dirname to group.

8 mkdir dirname make a new directory


9 rmdir dirname Removes the directory "dirname".

10 cp filename1 Copies one file to another file.


filename 2
11 cat filename(1) prints out the contents of a series of files one after the
filename(2)... other
filename(n)
12 more filename(1) prints out the contents of named files, one screen full at a
filename(2)... time
filename(n)
13 less filename Displays file with minimal space.

14 ln -s {source} {dest} Creates a symbolic link from {source} to {dest}.


Allows you to move around with ease instead of using
long and complicated path names.
15 mv command changes the name or location of a file or
directory
mv oldfile newfile

5
mv file(1) file(2)... file(n) directory
mv olddir newdir

16 diff file1 file2 ompares the contents of two files.


17 cmp {file1} {file2} Compares the contents of two files from each other.
Reports the first different character found, and the line
number.
18 Rm removes files and directories
-i Inquire before removing a file
-r Recursively remove a directory and all its
contents and subdirectories
19 bp filename A special SSC command that sends a file to the line
printer in Bunche Hall.
20 Cancel Terminates a command for a printer request.
21 (ctrl)-z Hold down "Ctrl" key and "z" at the same time. Stops a
job and puts it in the background
22 whoami returns your username.
23 date Displays the date and time.
24 df -k Shows disk space in Kbytes available on the system.
25 quota –v Shows current disk usage and limits.
26 file filename(s) Looks at "filename(s)" and tells what type of files they
are.

27 which {command} Reports the directory from which the {command} would
be run if it was given as a command line argument.
28 Whereis Reports the directory in which the {command} binary
{command} resides.
29 wc filename tells you how many lines, words, and characters there are
in a file
30 find Finds files and directory names.

find -ls will list all files.


find -mtime 1 will list files modified that day.

31 ff find files anywhere on the system


32 lprm Terminates a printer request.

33 lpstat Reports the status of printer and jobs.


34 lpq Lists print spool.
35 mime filename Encodes or decodes MIME64 files.

36 passwd Changes your password. You'll be asked to enter your old


password
37 ps Reports system processes.
38 public filename Makes files publically accessible
39 tail -30 filename Shows the last 30 lines of a file

6
40 who Shows who is logged onto the local system.
41 compress filename Compressing your large datasets is useful when you're
running out of disk space.
42 uncompress Expands one or more files, created with compress, to their
filename original form.
43 uuencode filename Encodes file into ASCII text format in order to send
through e-mail.

44 uudecode filename Decodes files encoded in ASCII text format.

45 zip filename Puts files into the .zip format.


46 unzip filename.zip Reads files with the .zip extension.

47 pine Starts the pine mail program.


48 mail Sends and receives mail.
49 write username lets you exchange one-line messages with another user
50 elm {login-name} Runs a screen oriented mail reader. With a "login-name",
starts elm to send mail to "login-name". Otherwise, it
starts elm for an interactive session.
51 source .login Runs your login file.
52 grep Scans a file for the occurrence of a word or string and
prints out any line in which it is found
wc [-l] [-w] [-c] counts the lines, words and characters in a file
filename... -l Prints the number of lines in the files.
-w Prints the number of words in the files.
-c Prints the number of characters in the files

53 pico filename Edits the file named filename with the Pico, an editor that
is easy for new users to learn.
54 setenv Sets environment variables. Most frequently used to tell X
which display you are on with "setenv DISPLAY
displayname:0". Also used in .cshrc file to set "EDITOR"
and "PRINTER" environment variables. This tells
programs which editor you prefer, and which printer you
want your output to be printed on.
55 env Prints out the values for all the current environment
variables. Some typical environment variables are
"DISPLAY", "EDITOR", and "PRINTER".
56 spell {filename} Checks the spelling of the words in the standard input by
default, checks words in "filename" if a name is supplied
on the command line. If a word is misspelled it is printed
to stdout ( usually the screen ).
57 cc A compiler for the "C" programming language. "cc" is
ANSI compatible on the SGI, IBM, and newer Sun
machines. You might try also try "gcc", GNU CC, which
is also available on the SGI, SUN, and IBM machines. A

7
typical invocation might be "cc -g file.c -o executable
name -llib".
c++ {filename}

A compiler for the C++ programming language.


Command line parameters are similar to the "cc"
compiler’s. A typical invocation might be "c++ -g file.cpp
-o executable name -llib".
58 ghostview X PostScript pre viewer. PostScript is a text processing
{filename.ps} and graphics language, and ghostview is handy for
looking at the resulting page or picture before you send it
to the printer.
59 gossip Anonymous local message center.
60 kermit File transfer program. Allows you to transfer files
between computers - your PC at home to/from the
computers at school, for instance. For more information,
look in the online manual pages
61 vn Runs the screen oriented network news program. Old and
slow - maybe try "trn" or "tin".
62 Trn Threaded, full page network news reader . Quicker than
vn.
63 Tin Threaded, full page network news reader. Easier than trn.
64 logout Exits and disconnects your network connection.
65 Clear Clears the shell.
66 Exit Exits out of a shell.

Network related commands:


1. netstat
ABOUT NETSTAT

Shows network status

SYNTAX

netstat [-a] [-n] [-v]

netstat [-g | -m | -p | -s | -f address_family ] [-n] [-P protocol]

netstat [ -i ] [ -I interface ] [ interval ]

netstat -r [-a] [-n] [-v ]

8
netstat -M [-n] [-s ]

netstat -D [ -I interface ]

-a Show the state of all sockets and all routing table entries; normally,
sockets used by server processes are not shown and only interface, host,
network, and default routes are shown.
-n Show network addresses as numbers. netstat normally displays
addresses as symbols. This option may be used with any of the display
formats.
-v Verbose. Show additional information for the sockets and the routing
table.
-g Show the multicast group memberships for all interfaces.
-m Show the STREAMS statistics.
-p Show the address resolution (ARP) tables.
-s Show per-protocol statistics. When used with the -M option, show
multicast routing statistics instead.
-i Show the state of the interfaces that are used for TCP/IP traffic.
-r Show the routing tables.
-M Show the multicast routing tables. When used with the -s option, show
multicast routing statistics instead.
-d Show the state of all interfaces that are under Dynamic Host
Configuration Protocol (DHCP) control.
-D Show the status of DHCP configured interfaces.
-f address_family imit statistics or address control block reports to those of the specified
address_family, which can be one of:

inet For the AF_INET address family


unix For the AF_UNIX address family
-P protocol Limit display of statistics or state of all sockets to those applicable to
protocol.
- I interface Show the state of a particular interface. interface can be any valid
interface such as ie0 or
le0.

EXAMPLES

netstat - displays generic net statistics of the host you are currently connected to.

2. ping

9
ABOUT PING

Sends ICMP ECHO_REQUEST packets to network hosts

SYNTAX

ping -s [-d] [-l] [-L] [-n] [-r] [-R] [-v] [ -i interface_address ] [-I interval] [-t ttl] host
[packetsize] [count]

-d Set the SO_DEBUG socket option.


-l Loose source route. Use this option in the IP header to send the packet
to the given host and back again. Usually specified with the -R option.
-L Turn off loopback of multicast packets. Normally, if there are members
in the host group on the out- going interface, a copy of the multicast
packets will be delivered to the local machine.
-n Show network addresses as numbers. ping normally displays addresses
as host names.
-r Bypass the normal routing tables and send directly to a host on an
attached network. If the host is not on a directly-attached network, an
error is returned. This option can be used to ping a local host through an
interface that has been dropped by the router daemon.
-R Record route. Sets the IP record route option, which will store the route
of the packet inside the IP header. The contents of the record route will
only be printed if the -v option is given, and only be set on return
packets if the target host preserves the record route option across echos,
or the -l option is given.
-v Verbose output. List any ICMP packets, other than
ECHO_RESPONSE, that are received.
-I Specify the outgoing interface address to use for multicast packets. The
interface_address default interface address for multicast packets is determined from the
(unicast) routing tables.
-I interval Specify the interval between successive transmissions. The default is
one second.
-t ttl Specify the IP time to live for unicast and multicast packets. The
default time to live for unicast packets is set with ndd (using the
icmp_def_ttl variable). The default time to live for multicast is one hop.
Host The network host.
Packetsize Specified size of packetsize. Default is 64.
Count Amount of times to send the ping request.

EXAMPLES

ping computerhope.com - Would ping the host computerhope.com to see if it is alive.

10
Note: Many ISP's are disabling the ping command in helping to prevent possible Denial
Of Service attacks. In addition some commands may not be available or results may vary
when pinging a host.

3. telnet
ABOUT TELNET

Uses the telnet protocol to connect to another remote computer.

SYNTAX

telnet [-8] [-E] [-L] [-c] [-d] [-r] [ -e escape_char ] [ -l user ] [-n file ] [ host [ port ] ]

-8 Specifies an 8-bit data path. Negotiating the TELNET BINARY option


is attempted for both input and output.
-E Stops any character from being recognized as an escape character.
-L Specifies an 8-bit data path on output. This causes the BINARY option
to be negotiated on output.
-c Disables the reading of the user's telnetrc file.
-d Sets the initial value of the debug toggle to
TRUE.
-r Specifies a user interface similar to rlogin . In this mode, the escape
character is set to the
tilde (~) character, unless modified by the -e option. The rlogin escape
character is only recognized when it is preceded by a carriage return. In
this mode, the telnet escape
character, normally '^]', must still precede a telnet command. The rlogin
escape character
can also be followed by '.\r' or '^Z', and, like rlogin, closes or suspends
the connection, respectively. This option is an uncommitted inter- face
and may change in the future.
-e escape_char Sets the initial escape character to escape_char. escape_char may also
be a two character sequence consisting of '^' followed by one character.
If the second character is '?', the DEL character is selected. Otherwise,
the second character is converted to a control character and used as the
escape character. If the escape character is the null string (that is, -e ''),
it is disabled.
-l user When connecting to a remote system that understands the ENVIRON
option, then user will be sent to the remote system as the value for the
ENVIRON variable USER.
-n file Opens tracefile for recording trace information.

11
EXAMPLES

telnet host.com - Would open a telnet session to the domain host.com

4. ifconfig
ABOUT

The "ifconfig" command allows the operating system to setup network interfaces and
allow the user to view information about the configured network interfaces.

SYNTAX

ifconfig [-L] [-m] interface [create] [address_family] [address[/prefixlength]


[dest_address]] [parameters]
ifconfig interface destroy
ifconfig -a [-L] [-d] [-m] [-u] [address_family]
ifconfig -l [-d] [-u] [address_family]
ifconfig [-L] [-d] [-m] [-u] [-C]

address For the DARPA-Internet family, the address is either a host name
present in the host name data base, or a DARPA Internet address
expressed in the Internet standard ``dot notation''.

It is also possible to use the CIDR notation (also known as the slash
notation) to include the netmask. That is, one can specify an address
like 192.168.0.1/16.
addres_family Specify the address family which affects interpretation of the remaining
parameters. Since an interface can receive transmissions in differing
protocols with different naming schemes, specifying the address family
is recommended. The address or protocol families currently supported
are ``inet'', ``inet6'',
dest_address Specify the address of the correspondent on the other end of a point to
point link.
interface This parameter is a string of the form ``name unit'', for example, ``en0''.
add Another name for the alias parameter. Introduced for compatibility with
BSD/OS.
alias Establish an additional network address for this interface. This is
sometimes useful when changing network numbers, and one wishes to
accept packets addressed to the old interface. If the address is on the
same subnet as the first network address for this interface, a netmask of
0xffffffff has to be specified.
-alias Remove the network address specified. This would be used if you
incorrectly specified an alias, or it was no longer needed. If you have

12
incorrectly set an NS address having the side effect of specifying the
host portion, removing all NS addresses will allow you to respecify the
host portion.
anycast (Inet6 only.) Specify that the address configured is an anycast address.
Based on the current specification, only routers may configure anycast
addresses. Anycast address will not be used as source address of any of
outgoing IPv6 packets.
arp Enable the use of the Address Resolution Protocol in mapping between
network level addresses and link level addresses (default). This is
currently implemented for mapping between DARPA Internet
addresses and IEEE 802 48-bit MAC addresses (Ethernet, FDDI, and
Token Ring addresses).
-arp Disable the use of the Address Resolution Protocol
broadcast (Inet only.) Specify the address to use to represent broadcasts to the
network. The default broadcast address is the address with a host part of
all 1's.
debug Enable driver dependent debugging code; usually, this turns on extra
console error logging.
-debug Disable driver dependent debugging code.
delete Another name for the -alias parameter.
down Mark an interface ``down''. When an interface is marked ``down'', the
system will not attempt to transmit messages through that interface. If
possible, the interface will be reset to disable reception as well. This
action does not automatically disable routes using the interface.
ether Another name for the lladdr parameter.
lladdr addr Set the link-level address on an interface. This can be used to e.g. set a
new MAC address on an ethernet interface, though the mechanism used
is not ethernet-specific. The address addr is specified as a series of
colon-separated hex digits. If the interface is already up when this
option is used, it will be briefly brought down and then brought back up
again in order to ensure that the receive filter in the underlying ethernet
hardware is properly reprogrammed.
media type If the driver supports the media selection system, set the media type of
the interface to type. Some interfaces support the mutually exclusive
use of one of several different physical media connectors. For example,
a 10Mb/s Ethernet interface might support the use of either AUI or
twisted pair connectors. Setting the media type to ``10base5/AUI''
would change the currently active connector to the AUI port. Setting it
to ``10baseT/UTP'' would activate twisted pair. Refer to the interfaces'
driver specific documentation or man page for a complete list of the
available types.
-mediaopt opts If the driver supports the media selection system, set the specified
media options on the interface. The opts argument is a comma
delimited list of options to apply to the interface. Refer to the interfaces'

13
driver specific man page for a complete list of available options.
tunnel src_addr (IP tunnel devices only.) Configure the physical source and destination
dest_addr address for IP tunnel interfaces. The arguments src_addr and dest_addr
are interpreted as the outer source/destination for the encapsulating
IPv4/IPv6 header.
deletetunnel Unconfigure the physical source and destination address for IP tunnel
interfaces previously configured with tunnel.
create Create the specified network pseudo-device. If the interface is given
without a unit number, try to create a new device with an arbitrary unit
number. If creation of an arbitrary device is successful, the new device
name is printed to standard output.
destroy Destroy the specified network pseudo-device.
plumb Another name for the create parameter. Included for Solaris
compatibility.
unplumb Another name for the destroy parameter. Included for Solaris
compatibility.
metric n Set the routing metric of the interface to n, default 0. The routing metric
is used by the routing protocol. Higher metrics have the effect of
making a route less favorable; metrics are counted as addition hops to
the destination network or host.
mtu n Set the maximum transmission unit of the interface to n, default is
interface specific. The MTU is used to limit the size of packets that are
transmitted on an interface. Not all interfaces support setting the MTU,
and some interfaces have range restrictions.
netmask mask (Inet only.) Specify how much of the address to reserve for subdividing
networks into subnetworks. The mask includes the network part of the
local address and the subnet part, which is taken from the host field of
the address. The mask can be specified as a single hexadecimal number
with a leading `0x', with a dot-notation Internet address, or with a
pseudo-network name listed in the network table. The mask contains 1's
for the bit positions in the 32-bit address which are to be used for the
network and subnet parts, and 0's for the host part. The mask should
contain at least the standard network portion, and the subnet field
should be contiguous with the network portion. The netmask can also
be specified in CIDR notation after the address. See the address option
above for more information.
prefixlen len (Inet6 only.) Specify that len bits are reserved for subdividing networks
into sub-networks. The len must be integer, and for syntactical reason it
must be between 0 to 128. It is almost always 64 under the current IPv6
assignment rule. If the parameter is omitted, 64 is used.
remove Another name for the -alias parameter. Introduced for compatibility
with BSD/OS.
link[0-2] Enable special processing of the link level of the interface. These three
options are interface specific in actual effect, how- ever, they are in

14
general used to select special modes of operation. An example of this is
to enable SLIP compression, or to select the connector type for some
Ethernet cards. Refer to the man page for the specific driver for more
information.
-link[0-2] Disable special processing at the link level with the specified interface.
up Mark an interface ``up''. This may be used to enable an interface after
an ``ifconfig down''. It happens automatically when setting the first
address on an interface. If the interface was reset when previously
marked down, the hardware will be re-initialized.

EXAMPLES

ifconfig eth0 - View the network settings on the first Ethernet adapter installed in the
computer.

5. traceout
ABOUT TRACEROUTE

Print the route packets take to network host

SYNTAX

traceroute [-d] [-F] [-I] [-n] [-v] [-x] [-f first_ttl] [-g gateway [-g gateway] | -r] [-i
iface] [-m max_ttl] [-p port] [-q nqueries] [-s src_addr] [-t tos] [-w waittime ] host
[packetlen]

-d Set the SO_DEBUG socket option.


-F Set the "don't fragment" bit.
-I Use ICMP ECHO instead of UDP datagrams.
-n Print hop addresses numerically rather than symbolically and
numerically. This saves a nameserver address-to-name lookup for each
gateway found on the path.
-v Verbose output. For each hop, the size and the destination of the
response packets is displayed. Also ICMP packets received other than
TIME_EXCEEDED and UNREACHABLE are listed as well.
-x Prevent traceroute from calculating checksums. Note that checksums
are usually required for the last hop when using ICMP ECHO probes.
See the -I option.
-f first_ttl Set the starting ttl value to first_ttl, to override the default value 1.
traceroute skips processing for those intermediate gateways which are
less than first_ttl hops away.

15
-g gateway Specify a loose source route gateway. The user can specify more than
one gateway by using -g for each gateway. The maximum that can be
set is 8.
-r Bypass the normal routing tables and send directly to a host on an
attached network. If the host is not on a directly-attached network, an
error is returned. This option can be used to send probes to a local host
through an interface that has been dropped by the router deamon.
-i iface Specify a network interface to obtain the source IP address for outgoing
probe packets. This is normally only useful on a multi-homed host. The
-s option is also another way to do this. Note that this option does not
provide a way to specify the interface on which the probe packets are
sent.
-m max_ttl Set the maximum ttl used in outgoing probe packets. The default is 30
hops, which is the same default used for TCP connections.
-p port Set the base UDP port number used in probes. The default is 33434.
traceroute hopes that nothing is listening on UDP ports (base+(nhops-
1)*nqueries) to (base+(nhops*nqueries)-1)at the destination host, so
that an ICMP PORT_UNREACHABLE message will be returned to
terminate the route tracing. If something is listening on a port in the
default range, this option can be used to select an unused port
range.nhops is defined as the number of hops between the source and
the destination.
-q nqueries Set the desired number of probe queries. The default is 3.
-s src_addr Use the following address, which usually is given as an IP address, not
a hostname, as the source address in outgoing probe packets. On multi-
homed hosts, those with more than one IP address, this option can be
used to force the source address to be something other than the IP
address traceroute picks by default. If the IP address is not one of this
machine's interface addresses, an error is returned and nothing is sent.
When used together with the -i option, the given IP address should be
configured on the specified interface. Otherwise, an error will be
returned.
-t tos Set the tos(type-of-service) in probe packets to the specified value. The
default is zero. The value must be an integer in the range from 0 to 255.
Gateways along the path may route the probe packet differently
depending upon the tos value set in the probe packet.
-w waittime Set the time, in seconds, to wait for a response to a probe. The default is
five (5) seconds.
host The network host.

EXAMPLES

traceroute computerhope.com - would display results similar to the following:

16
traceroute to computerhope.com (166.70.10.23), 30 hops max, 40 byte packets
1 198.60.22.1 (198.60.22.1) 2.303 ms 1.424 ms 2.346 ms
2 krunk3.xmission.com (198.60.22.6) 0.742 ms * 1.521 ms

Exercise Questions for Lab Session-I


1. Refer Annexure- I
2. Refer Annexure-II
3. Refer Annexure-III

Lab Session: 2 Introduction to Socket Programming


2a. Socket Creation

Aim:

 To create a program with socket for basic communication

System and Software Requirements:

 PC with UNIX/ Linux Operating systems.


 C compiler in Linux Environment
Theory
Sockets are interfaces that can "plug into" each other over a network. Once so
"plugged in", the programs so connected communicate.
A "server" program is exposed via a socket connected to a certain /etc/services
port number. A "client" program can then connect its own socket to the server's socket, at
which time the client program's writes to the socket are read as stdin to the server
program, and stdout from the server program are read from the client's socket reads. This
is one subset of socket programming, but it's perhaps the easiest to master, so this is
where you should start.

There are different kinds of sockets available depending on which UNIX flavors
we run. Some of them are: There are DARPA Internet addresses (Internet Sockets), path

17
names on a local node (Unix Sockets), CCITT X.25 addresses (X.25 Sockets that you can
safely ignore). This document deals only with the first: Internet Sockets.
Two Types of Internet Sockets:
One is “Stream Sockets”; the other is “Datagram Sockets”, which may hereafter be
referred to as “SOCK_STREAM” and “SOCK_DGRAM”, respectively. Datagram sockets
are sometimes called “connectionless sockets”.
Stream sockets are reliable two-way connected communication streams. If you output
two items into the socket in the order “1, 2”, they will arrive in the order “1, 2” at the opposite
end. They will also be error-free.
What uses stream sockets? Well, you may have heard of the telnet application, yes? It
uses stream sockets. All the characters you type need to arrive in the same order you type them,
right? Also, web browsers use the HTTP protocol which uses stream sockets to get pages. Indeed,
if you telnet to a web site on port 80, and type “GET / HTTP/1.0” and hit RETURN twice, it'll
dump the HTML back at you! How do stream sockets achieve this high level of data transmission
quality? They use a protocol called
“The Transmission Control Protocol”, otherwise known as “TCP” (see RFC 7936 for extremely
detailed info on TCP.) TCP makes sure your data arrives sequentially and error-free. You may
have heard “TCP” before as the better half of “TCP/IP” where “IP” stands for “Internet Protocol”
(see RFC 7917.) IP deals primarily with Internet routing and is not generally responsible for data
integrity.

What about Datagram sockets? Why are they called connectionless? What is the deal,
here, anyway? Why are they unreliable? Well, here are some facts: if you send a datagram, it may
arrive. It may arrive out of order. If it arrives, the data within the packet will be error-free.

Datagram sockets also use IP for routing, but they don't use TCP; they use the “User
Datagram Protocol”, or “UDP” (see RFC 7688.)

Why are they connectionless? Well, basically, it's because you don't have to maintain an
open connection as you do with stream sockets. You just build a packet, slap an IP header on it
with destination information, and send it out. No connection needed. They are generally used
either when a TCP stack is unavailable or when a few dropped packets here and there don't mean
the end of the Universe. Sample applications: tftp (trivial file transfer protocol, a little brother to
FTP), dhcpcd (a DHCP client), multiplayer games, streaming audio, video conferencing, etc.

“tftp and dhcpcd are used to transfer binary applications from one host to another! Data
can't be lost if you expect the application to work when it arrives! What kind of dark magic is
this?”
tftp and similar programs have their own protocol on top of UDP. For example, the tftp
protocol says that for each packet that gets sent, the recipient has to send back a packet that says,
“I got it!” (an “ACK” packet.) If the sender of the original packet gets no reply in, say, five
seconds, he'll retransmit the packet until he finally gets an ACK. This acknowledgment procedure
is very important when implementing reliable SOCK_DGRAM applications.

For unreliable applications like games, audio, or video, you just ignore the dropped
packets, or perhaps try to cleverly compensate for them. (Quake players will know the
manifestation this effect by the technical term: accursed lag. The word “accursed”, in this case,
represents any extremely profane utterance.)

18
Why would you use an unreliable underlying protocol? Two reasons: speed and speed.
It's way faster to fire-and-forget than it is to keep track of what has arrived safely and make sure
it's in order and all that. If you're sending chat messages, TCP is great; if you're sending 40
positional updates per second of the players in the world, maybe it doesn't matter so much if one
or two get dropped, and UDP is a good choice.

Low level Nonsense and Network Theory


It's time to talk about how networks really work, and to show some examples of how
SOCK_DGRAM packets are built. Practically, you can probably skip this section. It's good
background, however.

Data Encapsulation! This is very very important. Basically, it says this: a packet is born,
the packet is wrapped (“encapsulated”) in a header (and rarely a footer) by the first
protocol (say, the TFTP protocol), then the whole thing (TFTP header included) is
encapsulated again by the next protocol (say, UDP), then again by the next (IP), then
again by the final protocol on the hardware (physical) layer (say, Ethernet).

When another computer receives the packet, the hardware strips the Ethernet
header, the kernel strips the IP and UDP headers, the TFTP program strips the TFTP
header, and it finally has the data. Now I can finally talk about the infamous Layered
Network Model (aka “ISO/OSI”). This Network Model describes a system of network
functionality that has many advantages over other models. For instance, you can write
sockets programs that are exactly the same without caring how the data is physically
transmitted (serial, thin Ethernet, AUI, whatever) because programs on lower levels deal
with it for you. The actual network hardware and topology is transparent to the socket
programmer.

Without any further ado, I'll present the layers of the full-blown model.
Remember this for network class exams:
• Application
• Presentation
• Session
• Transport
• Network
• Data Link
• Physical

19
The Physical Layer is the hardware (serial, Ethernet, etc.). The Application Layer
is just about as far from the physical layer as you can imagine—it's the place where users
interact with the network.
Now, this model is so general you could probably use it as an automobile repair
guide if you really wanted to. A layered model more consistent with Unix might be:
• Application Layer (telnet, ftp, etc.)
• Host-to-Host Transport Layer (TCP, UDP)
• Internet Layer (IP and routing)
• Network Access Layer (Ethernet, wi-fi, or whatever)
At this point in time, you can probably see how these layers correspond to the
encapsulation of the original data. See how much work there is in building a simple
packet? Jeez! And you have to type in the packet headers yourself using “cat”! Just
kidding. All you have to do for stream sockets is send() the data out.

All you have to do for datagram sockets is encapsulate the packet in the method
of your choosing and sendto() it out. The kernel builds the Transport Layer and Internet
Layer on for you and the hardware does the Network Access Layer. Ah, modern
technology. So ends our brief foray into network theory. Oh yes, I forgot to tell you
everything I wanted to say about routing: nothing! That's right, I'm not going to talk
about it at all. The router strips the packet to the IP header, consults its routing table, blah
blah blah. Check out the IP RFC9 if you really really care.

Procedure Used to Create Socket


socket (struct proc *p, struct socket_args *uap, int retval)
struct sock_args
{
int domain,
int type,
int protocol;
};

In the socket system call:

• p is a pointer to the proc structure of the process that makes the socket call.
• uap is a pointer to the socket_args structure that contains the arguments passed to the
process in the socket system call.
• retval is the return value of the system call.

The socket system call creates a new socket by assigning a new descriptor. The new
descriptor is returned to the calling process. Any subsequent system calls are identified
with the created socket. The socket system call also assigns the protocol to the created
socket descriptor.

In order to create a socket, we use the system call as,

20
int socketdescriptor = socket ( int domain, int type, int protocol);

where domain specifies the name of the family to which socket belongs, type specifies
the communication mode, protocol is one in which has the default value of zero. The
return value is the integer value of which value can be greater than 3, then the socket
cannot be created and there is error in the socket.
Open one text editor with the help of gedit ,type the following code and stored it
in the some filename (ex. Create.c) with extension c.

Algorithms
• Start the program.
• Include the necessary header files such as stdio.h and sys/socket.h
• Declare the socket descriptor.
• Using the socket system call to create a new socket (Both TCP and UDP).
• Check the return value of socket descriptor.
• If it is 0, then it is standard I/P else if it is 1, then it is standard O/P else if it is
2, then it is standard error.
• Display the return socket descriptor integer value.
• End the program.
Program
#include <stdio.h>
#include <sys/socket.h>
int main()
{
printf (“\n Socket Creation in C \n”);
int i_socketdescriptor;
int i_sock;
i_socketdescriptor = socket ( AF_INET, SOCK_STREAM,0);
if(i_socketdescriptor == -1)
{
printf( “Socket Descriptro : %d \n”, i_socketdescriptor);
printf(“\n CREATION ERROR\n”);
}
else
{
printf( “Socket Descriptro : %d \n”, i_socketdescriptor);
printf(“\n NO ERROR\n”);
}

i_sock = socket (PF_INET, SOCK_DGRAM,0);


if(i_sock == -1)
{

21
printf( “Socket Descriptor for PF_INET : %d \n”, i_sock);
printf(“\n CREATION ERROR\n”);
}
else
{
printf( “Socket Descriptor for PF_INET : %d \n”, i_sock);
printf(“\n CREATED SUCCESSFULLY\n”);
}
}

How to Run the Program


[root @ root] $ cc create.c
[root @ root] $ ./a.out

Output
Socket Creation in C
Socket Descriptor : 3
NO ERROR
Socket Descriptor for PF-INET : 4
CREATED SUCCESSFULLY

Exercises
1.Create UDP, TCP Sockets in Windows using JAVA programming.
2. Create UDP, TCP Sockets in windows using C Programming.

22
2b. Socket Binding

Aim:

 To bind the socket to specified port for proper communication.

System and Software Requirements:

 PC with UNIX/ Linux Operating systems.


 C compiler in Linux Environment

Theory
The bind() function associates a local address with a socket. Specifically, bind()
assigns a local name to an unnamed socket. This routine is used on an unconnected
datagram or stream socket, before a subsequent connect() or listen(). When socket()
creates a socket, it exists in a name space (address family) but it has no name assigned.
The bind() call requests that the name pointed to by name be assigned to the socket. The
interpretation of name depends upon the address family of the socket. The syntax for bind
of function is :

#include <sys/types.h>
#include <sys/socket.h>
int bind(int s, const struct sockaddr *name, socklen_t namelen);

where,
s- Specifies the integer descriptor of the unbounded socket.
name - Points to a sockaddr structure containing the address to be bound to the socket. The length and
format of the address depend on the address family of the socket.

namelen - Specifies the length of name in bytes.

RETURN VALUES:

23
If successful, bind() returns a value of zero. On failure, it returns -1 and sets errno to one of the following
values:

EACCES - For sockets in the AF_UNIX address family, the specified address does not specify a disk file local
to the machine.

For sockets in the AF_UNIX address family, a component of the path prefix denies search permission, or the
requested name requires writing in a directory with a mode that denies write permission.

EADDRINUSE -The specified address is already in use. [See the SO_REUSEADDR socket option under
Stockpot().

EAFNOSUPPORT - The protocol used in the creation of specified socket does not support the specified
address family.

EBADF - s is not a valid descriptor.

EFAULT - name is an invalid pointer or the namelen parameter is too small (less than the size of a struct
sockaddr).

EINVAL - The socket is already bound to an address.

ENETDOWN - The Windows sockets implementation has detected that the network subsystem has failed.

ENOBUFS - Not enough buffers are available; there are too many connections.

ENOTSOCK - The descriptor is not a socket.

Algorithms

• Start the program.


• Include necessary header file such as sys/socket.h, sys/types.h and netinet/in.h.
• Create the socket with the system call socket() and assigned to some socket
descriptor.
• Check the socket descriptor value for proper creation.
• Describe the structure with family, port number and IP address.
• Bind the socket and port number with the system call bind().
• Check the socket and port number are properly bound or not.
• Print the bind value and port number on the screen.
• End the Program.
Program
#include <stdio.h>
#include <sys/socket.h>
#include<tsys/types.h>
#include<netinet/in.h>

int main()
{
int isocketdescriptor, iBindValue;
struct sockeaddr_in sAddr;
isocketdescriptor = socket (AF_INET, SOCK_STREAM,0);

24
if (isocketdescriptor <=2 && iscoketdescriptor = = -1)
printf( “\n Error in Socket Creation is %d”, isocketdescriptor);
else
printf(“\n The value of Socket Descriptor is %d”, isocketdescriptor);
sAddr.sin_family = AF_INET;
sAddr.sin_port = htons(1037);
sAddr.sin_addr.s_addr = INADDR_ANY;
bzero ( sAddr.sin_zero, 8);
iBindValue = bind(iscoketdescriptor, (struct sockaddr *) &sAddr, sizeof(sAddr));
if (iBindValue = = -1)
printf( “\n Error in Binding\n”);
else
{
printf (“\n The bind value is %d\n”, iBindValue);
printf(“\n The value for the port is %d\n”, ntohs (sAddr.sin_port));
printf(“\n The address is %s\n”, inet_ntoa(sAddr.sin_addr));
}
}
How to Run the Program
[root @ root] $ cc bind.c
[root @ root] $ ./a.out

Output
The value of Socket Descriptor is 3
The bind value is 0
The value for the port is 1037
The address is 0.0.0.0

Exercises
1. Find out and write program for the equivalent socket binding function in Windows
using JAVA programming.
2. Find out and write program for the equivalent socket binding function in windows
using C Programming.

25
2c. Socket Listening
Aim:

 To listen the request from client by server through created socket.

System and Software Requirements:

 PC with UNIX/ Linux Operating systems.


 C compiler in Linux Environment

Theory
The listen() function shall mark a connection-mode socket, specified by the
socket argument, as accepting connections. The syntax of listen() system call is :

#include <sys/socket.h>
int listen(int socket, int backlog);

The backlog argument provides a hint to the implementation which the


implementation shall use to limit the number of outstanding connections in the socket's
listen queue. Implementations may impose a limit on backlog and silently reduce the
specified value. Normally, a larger backlog argument value shall result in a larger or
equal length of the listen queue. Implementations shall support values of backlog up to
SOMAXCONN, defined in <sys/socket.h>.
The implementation may include incomplete connections in its listen queue. The
limits on the number of incomplete connections and completed connections queued may
be different.
The implementation may have an upper limit on the length of the listen queue-
either global or per accepting socket. If backlog exceeds this limit, the length of the listen
queue is set to the limit.
If listen() is called with a backlog argument value that is less than 0, the function
behaves as if it had been called with a backlog argument value of 0.

26
A backlog argument of 0 may allow the socket to accept connections, in which
case the length of the listen queue may be set to an implementation-defined minimum
value.
The socket in use may require the process to have appropriate privileges to use the
listen() function.

RETURN VALUE
Upon successful completions, listen() shall return 0; otherwise, -1 shall be returned and errno set to
indicate the error.

ERRORS
The listen() function shall fail if:

[EBADF] - The socket argument is not a valid file descriptor.

[EDESTADDRREQ] - The socket is not bound to a local address, and the protocol
does not support listening on an unbound socket.
[EINVAL] - The socket is already connected.

[ENOTSOCK] - The socket argument does not refer to a socket.

[EOPNOTSUPP] - The socket protocol does not support listen().

The listen() function may fail if:

[EACCES] - The calling process does not have the appropriate privileges.

[EINVAL] - The socket has been shut down.

[ENOBUFS] - Insufficient resources are available in the system to complete the call.

Algorithms
• Start the program
• Include necessary header files such as sys/socket.h, sys/types.h, neinet/in.h
• Create socket with the system call socket() for establishing connection and assigned some socket
descriptor.
• Check the socket descriptor value for proper creation.
• Describe the structure with family, port number and IP address.
• Bind the socket and port number with the system call bind()
• Check the socket and port number are properly bound or not.
• Using the system call listen() for listening request coming from client by server and it will return
some integer value.
• If the returned integer value is -1, then the server is not listening.

27
• End the program.

Program
#include <stdio.h>
#include <sys/socket.h>
#include<tsys/types.h>
#include<netinet/in.h>

int main()
{
int isocketdescriptor, iBindValue, iAcceptval,istatus;
struct sockeaddr_in sAddr;
isocketdescriptor = socket (AF_INET, SOCK_STREAM,0);
if (isocketdescriptor <=2 && iscoketdescriptor = = -1)
printf( “\n Error in Socket Creation is %d”, isocketdescriptor);
else
printf(“\n The value of Socket Descriptor is %d”, isocketdescriptor);
sAddr.sin_family = AF_INET;
sAddr.sin_port = htons(5404);
sAddr.sin_addr.s_addr = INADDR_ANY;
bzero ( sAddr.sin_zero, 8);
iBindValue = bind(iscoketdescriptor, (struct sockaddr *) &sAddr, sizeof(sAddr));
if (iBindValue = = -1)
printf( “\n Error in Binding\n”);
else
{
printf (“\n The bind value is %d\n”, iBindValue);
printf(“\n The value for the port is %d\n”, ntohs (sAddr.sin_port));
printf(“\n The address is %s\n”, inet_ntoa(sAddr.sin_addr));
}
istatus = listen ( iscoketdescriptor, 10);
if(istatus = = -1)
printf(“\n Error in Listening”);
else
printf(“\n The server is in Listening Mode \n”);

28
}
How to Run the Program
[root @ root] $ cc listen.c
[root @ root] $ ./a.out

Output
The value of Socket Descriptor is 3
The bind value is 0
The value for the port is 5404
The address is 0.0.0.0

Exercises
1. Find out and write program for the equivalent socket listening function in Windows
using JAVA programming.
2. Find out and write program for the equivalent socket listening function in windows
using C Programming.

29
2d. Message Transfer between Client/Server
Aim:

 To send a request from client to server and get the acknowledgement


message.

System and Software Requirements:

 PC with UNIX/ Linux Operating systems.


 C compiler in Linux Environment

Theory
A network architecture in which each computer or process on the network is
either a client or a server. Servers are powerful computers or processes dedicated to
managing disk drives (file servers), printers (print servers), or network traffic (network
servers ). Clients are PCs or workstations on which users run applications. Clients rely on
servers for resources, such as files, devices, and even processing power.

Another type of network architecture is known as a peer-to-peer architecture


because each node has equivalent responsibilities. Both client/server and peer-to-peer
architectures are widely used, and each has unique advantages and disadvantages.

Client-server architectures are sometimes called two-tier architectures.

The client-server characteristic describes the relationship of cooperating programs


in an application. The server component provides a function or service to one or many
clients, which initiate requests for such services.

Functions such as email exchange, web access and database access, are built on
the client-server model. For example, a web browser is a client program running on a
user's computer that may access information stored on a web server on the Internet. Users

30
accessing banking services from their computer use a web browser client to send a
request to a web server at a bank. That program may in turn forward the request to its
own database client program that sends a request to a database server at another bank
computer to retrieve the account information. The balance is returned to the bank
database client, which in turn serves it back to the web browser client displaying the
results to the user.

The client-server model has become one of the central ideas of network
computing. Many business applications being written today use the client-server model.
So do the Internet's main application protocols, such as HTTP, SMTP, Telnet, DNS. In
marketing, the term has been used to distinguish distributed computing by smaller
dispersed computers from the "monolithic" centralized computing of mainframe
computers. But this distinction has largely disappeared as mainframes and their
applications have also turned to the client-server model and become part of network
computing.

Each instance of the client software can send data requests to one or more
connected servers. In turn, the servers can accept these requests, process them, and return
the requested information to the client. Although this concept can be applied for a variety
of reasons to many different kinds of applications, the architecture remains fundamentally
the same.

The most basic type of client-server architecture employs only two types of hosts:
clients and servers. This type of architecture is sometimes referred to as two-tier. It
allows devices to share files and resources. The two tier architecture means that the client
acts as one tier and application in combination with server acts as another tier.

The interaction between client and server is often described using sequence
diagrams. Sequence diagrams are standardized in the Unified Modeling Language.

Specific types of clients include web browsers, email clients, and online chat
clients.

Specific types of servers include web servers, ftp servers, application servers,
database servers, name servers, mail servers, file servers, print servers, and terminal
servers. Most web services are also types of servers.

Function
1. Bzero()
The bzero() function copies n bytes, each with a value of zero, into string s.
e.g. void bzero(char *s, int n);
PARAMETERS
s
Points to a buffer that zeros are copied into.
n
Is the number of zeros to be copied into the buffer.

31
RETURN VALUES
None.

2. Listen()
DESCRIPTION

The listen() function shall mark a connection-mode socket, specified by the


socket argument, as accepting connections.

The backlog argument provides a hint to the implementation which the


implementation shall use to limit the number of outstanding connections in the
socket's listen queue. Implementations may impose a limit on backlog and silently
reduce the specified value. Normally, a larger backlog argument value shall result in
a larger or equal length of the listen queue. Implementations shall support values of
backlog up to SOMAXCONN, defined in <sys/socket.h>.

The implementation may include incomplete connections in its listen queue.


The limits on the number of incomplete connections and completed connections
queued may be different.

The implementation may have an upper limit on the length of the listen
queue-either global or per accepting socket. If backlog exceeds this limit, the length
of the listen queue is set to the limit.

If listen() is called with a backlog argument value that is less than 0, the
function behaves as if it had been called with a backlog argument value of 0.

A backlog argument of 0 may allow the socket to accept connections, in which


case the length of the listen queue may be set to an implementation-defined
minimum value.

The socket in use may require the process to have appropriate privileges to
use the listen() function.

e.g., int listen(int socket, int backlog);

RETURN VALUE

Upon successful completions, listen() shall return 0; otherwise, -1 shall be


returned and errno set to indicate the error.

ERRORS

The listen() function shall fail if:

[EBADF]
The socket argument is not a valid file descriptor.
[EDESTADDRREQ]

32
The socket is not bound to a local address, and the protocol does not
support listening on an unbound socket.
[EINVAL]
The socket is already connected.
[ENOTSOCK]
The socket argument does not refer to a socket.
[EOPNOTSUPP]
The socket protocol does not support listen().

The listen() function may fail if:

[EACCES]
The calling process does not have the appropriate privileges.
[EINVAL]
The socket has been shut down.
[ENOBUFS]
Insufficient resources are available in the system to complete the call.

3. Send()

The send() function shall initiate transmission of a message from the specified
socket to its peer. The send() function shall send a message only when the socket is
connected (including when the peer of a connectionless socket has been set via
connect()).

The send() function takes the following arguments:

socket
Specifies the socket file descriptor.
buffer
Points to the buffer containing the message to send.
length
Specifies the length of the message in bytes.
flags
Specifies the type of message transmission. Values of this argument are
formed by logically OR'ing zero or more of the following flags:
MSG_EOR
Terminates a record (if supported by the protocol).
MSG_OOB
Sends out-of-band data on sockets that support out-of-band
communications. The significance and semantics of out-of-band data are protocol-
specific.

The length of the message to be sent is specified by the length argument. If the
message is too long to pass through the underlying protocol, send() shall fail and no data
shall be transmitted.

33
Successful completion of a call to send() does not guarantee delivery of the
message. A return value of -1 indicates only locally-detected errors.

If space is not available at the sending socket to hold the message to be


transmitted, and the socket file descriptor does not have O_NONBLOCK set, send() shall
block until space is available. If space is not available at the sending socket to hold the
message to be transmitted, and the socket file descriptor does have O_NONBLOCK set,
send() shall fail. The select() and poll() functions can be used to determine when it is
possible to send more data.

The socket in use may require the process to have appropriate privileges to use the
send() function.

e.g., ssize_t =send(int socket, const void *buffer, size_t length, int
flags);

RETURN VALUE

Upon successful completion, send() shall return the number of bytes sent. Otherwise, -1
shall be returned and errno set to indicate the error.

ERRORS

The send() function shall fail if:

[EAGAIN] or [EWOULDBLOCK]
The socket's file descriptor is marked O_NONBLOCK and the requested
operation would block.
[EBADF]
The socket argument is not a valid file descriptor.
[ECONNRESET]
A connection was forcibly closed by a peer.
[EDESTADDRREQ]
The socket is not connection-mode and no peer address is set.
[EINTR]
A signal interrupted send() before any data was transmitted.
[EMSGSIZE]
The message is too large to be sent all at once, as the socket requires.
[ENOTCONN]
The socket is not connected or otherwise has not had the peer pre-specified.
[ENOTSOCK]
The socket argument does not refer to a socket.
[EOPNOTSUPP]
The socket argument is associated with a socket that does not support one or more
of the values set in flags.
[EPIPE]

34
The socket is shut down for writing, or the socket is connection-mode and is no
longer connected. In the latter case, and if the socket is of type SOCK_STREAM,
the SIGPIPE signal is generated to the calling thread.

The send() function may fail if:

[EACCES]
The calling process does not have the appropriate privileges.
[EIO]
An I/O error occurred while reading from or writing to the file system.
[ENETDOWN]
The local network interface used to reach the destination is down.
[ENETUNREACH]
No route to the network is present.
[ENOBUFS]
Insufficient resources were available in the system to perform the operation.

4. Accept()
DESCRIPTION

The accept() function shall extract the first connection on the queue of pending
connections, create a new socket with the same socket type protocol and address family
as the specified socket, and allocate a new file descriptor for that socket.

The accept() function takes the following arguments:

socket
Specifies a socket that was created with socket(), has been bound to an
address with bind(), and has issued a successful call to listen().
address
Either a null pointer, or a pointer to a sockaddr structure where the
address of the connecting socket shall be returned.
address_len
Points to a socklen_t structure which on input specifies the length of the
supplied sockaddr structure, and on output specifies the length of the stored
address.

If address is not a null pointer, the address of the peer for the accepted connection
shall be stored in the sockaddr structure pointed to by address, and the length of this
address shall be stored in the object pointed to by address_len.

If the actual length of the address is greater than the length of the supplied
sockaddr structure, the stored address shall be truncated.

35
If the protocol permits connections by unbound clients, and the peer is not bound,
then the value stored in the object pointed to by address is unspecified.

If the listen queue is empty of connection requests and O_NONBLOCK is not set
on the file descriptor for the socket, accept() shall block until a connection is present. If
the listen() queue is empty of connection requests and O_NONBLOCK is set on the file
descriptor for the socket, accept() shall fail and set errno to [EAGAIN] or
[EWOULDBLOCK].

The accepted socket cannot itself accept more connections. The original socket
remains open and can accept more connections.

e.g., int accept(int socket, struct sockaddr *restrict address,


socklen_t *restrict address_len);

RETURN VALUE

Upon successful completion, accept() shall return the non-negative file descriptor
of the accepted socket. Otherwise, -1 shall be returned and errno set to indicate the error.

ERRORS

The accept() function shall fail if:

[EAGAIN] or [EWOULDBLOCK]
O_NONBLOCK is set for the socket file descriptor and no connections are
present to be accepted.
[EBADF]
The socket argument is not a valid file descriptor.
[ECONNABORTED]
A connection has been aborted.
[EINTR]
The accept() function was interrupted by a signal that was caught before a valid
connection arrived.
[EINVAL]
The socket is not accepting connections.
[EMFILE]
{OPEN_MAX} file descriptors are currently open in the calling process.
[ENFILE]
The maximum number of file descriptors in the system are already open.
[ENOTSOCK]
The socket argument does not refer to a socket.
[EOPNOTSUPP]
The socket type of the specified socket does not support accepting connections.

The accept() function may fail if:

36
[ENOBUFS]
No buffer space is available.
[ENOMEM]
There was insufficient memory available to complete the operation.
[EPROTO]
[XSR]
A protocol error has occurred; for example, the STREAMS protocol stack
has not been initialized
5.Connect()

DESCRIPTION
The connect() function shall attempt to make a connection on a socket. The
function takes the following arguments:
socket
Specifies the file descriptor associated with the socket.
address
Points to a sockaddr structure containing the peer address. The length and
format of the address depend on the address family of the socket.
address_len
Specifies the length of the sockaddr structure pointed to by the address
argument.
If the socket has not already been bound to a local address, connect() shall bind it
to an address which, unless the socket's address family is AF_UNIX, is an unused local
address.
If the initiating socket is not connection-mode, then connect() shall set the
socket's peer address, and no connection is made. For SOCK_DGRAM sockets, the peer
address identifies where all datagrams are sent on subsequent send() functions, and limits
the remote sender for subsequent recv() functions. If address is a null address for the
protocol, the socket's peer address shall be reset.
If the initiating socket is connection-mode, then connect() shall attempt to establish a
connection to the address specified by the address argument. If the connection cannot be
established immediately and O_NONBLOCK is not set for the file descriptor for the
socket, connect() shall block for up to an unspecified timeout interval until the connection
is established. If the timeout interval expires before the connection is established,
connect() shall fail and the connection attempt shall be aborted. If connect() is interrupted
by a signal that is caught while blocked waiting to establish a connection, connect() shall
fail and set errno to [EINTR], but the connection request shall not be aborted, and the
connection shall be established asynchronously.
If the connection cannot be established immediately and O_NONBLOCK is set
for the file descriptor for the socket, connect() shall fail and set errno to
[EINPROGRESS], but the connection request shall not be aborted, and the connection
shall be established asynchronously. Subsequent calls to connect() for the same socket,
before the connection is established, shall fail and set errno to [EALREADY].
When the connection has been established asynchronously, select() and poll() shall
indicate that the file descriptor for the socket is ready for writing.
The socket in use may require the process to have appropriate privileges to use the
connect() function.

37
e.g., int connect(int socket, const struct sockaddr *address,
socklen_t address_len);
RETURN VALUE
Upon successful completion, connect() shall return 0; otherwise, -1 shall be returned and
errno set to indicate the error.
ERRORS
The connect() function shall fail if:
[EADDRNOTAVAIL]
The specified address is not available from the local machine.
[EAFNOSUPPORT]
The specified address is not a valid address for the address family of the
specified socket.
[EALREADY]
A connection request is already in progress for the specified socket.
[EBADF]
The socket argument is not a valid file descriptor.
[ECONNREFUSED]
The target address was not listening for connections or refused the
connection request.
[EINPROGRESS]
O_NONBLOCK is set for the file descriptor for the socket and the
connection cannot be immediately established; the connection shall be established
asynchronously.
[EINTR]
The attempt to establish a connection was interrupted by delivery of a
signal that was caught; the connection shall be established asynchronously.
[EISCONN]
The specified socket is connection-mode and is already connected.
[ENETUNREACH]
No route to the network is present.
[ENOTSOCK]
The socket argument does not refer to a socket.
[EPROTOTYPE]
The specified address has a different type than the socket bound to the
specified peer address.
[ETIMEDOUT]
The attempt to connect timed out before a connection was made.
If the address family of the socket is AF_UNIX, then connect() shall fail if:
[EIO]
An I/O error occurred while reading from or writing to the file system.
[ELOOP]
A loop exists in symbolic links encountered during resolution of the
pathname in address.
[ENAMETOOLONG]
A component of a pathname exceeded {NAME_MAX} characters, or an
entire pathname exceeded {PATH_MAX} characters.
[ENOENT]

38
A component of the pathname does not name an existing file or the
pathname is an empty string.
[ENOTDIR]
A component of the path prefix of the pathname in address is not a
directory.
The connect() function may fail if:
[EACCES]
Search permission is denied for a component of the path prefix; or write
access to the named socket is denied.
[EADDRINUSE]
Attempt to establish a connection that uses addresses that are already in
use.
[ECONNRESET]
Remote host reset the connection request.
[EHOSTUNREACH]
The destination host cannot be reached (probably because the host is down
or a remote router cannot reach it).
[EINVAL]
The address_len argument is not a valid length for the address family; or
invalid address family in the sockaddr structure.
[ELOOP]
More than {SYMLOOP_MAX} symbolic links were encountered during
resolution of the pathname in address.
[ENAMETOOLONG]
Pathname resolution of a symbolic link produced an intermediate result
whose length exceeds {PATH_MAX}.
[ENETDOWN]
The local network interface used to reach the destination is down.
[ENOBUFS]
No buffer space is available.
[EOPNOTSUPP]
The socket is listening and cannot be connected.

6. Recv()

The recv() function shall receive a message from a connection-mode or


connectionless-mode socket. It is normally used with connected sockets because it does
not permit the application to retrieve the source address of received data.

The recv() function takes the following arguments:

socket
Specifies the socket file descriptor.
buffer
Points to a buffer where the message should be stored.
length

39
Specifies the length in bytes of the buffer pointed to by the buffer
argument.
flags
Specifies the type of message reception. Values of this argument
are formed by logically OR'ing zero or more of the following
values:
MSG_PEEK
Peeks at an incoming message. The data is treated as unread and
the next recv() or similar function shall still return this data.
MSG_OOB
Requests out-of-band data. The significance and semantics of out-
of-band data are protocol-specific.
MSG_WAITALL
On SOCK_STREAM sockets this requests that the function block
until the full amount of data can be returned. The function may return the
smaller amount of data if the socket is a message-based socket, if a signal
is caught, if the connection is terminated, if MSG_PEEK was specified, or
if an error is pending for the socket.

The recv() function shall return the length of the message written to the buffer
pointed to by the buffer argument. For message-based sockets, such as SOCK_DGRAM
and SOCK_SEQPACKET, the entire message shall be read in a single operation. If a
message is too long to fit in the supplied buffer, and MSG_PEEK is not set in the flags
argument, the excess bytes shall be discarded. For stream-based sockets, such as
SOCK_STREAM, message boundaries shall be ignored. In this case, data shall be
returned to the user as soon as it becomes available, and no data shall be discarded.

If the MSG_WAITALL flag is not set, data shall be returned only up to the end of
the first message.

If no messages are available at the socket and O_NONBLOCK is not set on the
socket's file descriptor, recv() shall block until a message arrives. If no messages are
available at the socket and O_NONBLOCK is set on the socket's file descriptor, recv()
shall fail and set errno to [EAGAIN] or [EWOULDBLOCK].

e.g., ssize_t= recv(int socket, void *buffer, size_t length, int flags);

RETURN VALUE

Upon successful completion, recv() shall return the length of the message in
bytes. If no messages are available to be received and the peer has performed an orderly
shutdown, recv() shall return 0. Otherwise, -1 shall be returned and errno set to indicate
the error.

40
ERRORS

The recv() function shall fail if:

[EAGAIN] or [EWOULDBLOCK]
The socket's file descriptor is marked O_NONBLOCK and no data is
waiting to be received; or MSG_OOB is set and no out-of-band data is available
and either the socket's file descriptor is marked O_NONBLOCK or the socket
does not support blocking to await out-of-band data.
[EBADF]
The socket argument is not a valid file descriptor.
[ECONNRESET]
A connection was forcibly closed by a peer.
[EINTR]
The recv() function was interrupted by a signal that was caught, before
any data was available.
[EINVAL]
The MSG_OOB flag is set and no out-of-band data is available.
[ENOTCONN]
A receive is attempted on a connection-mode socket that is not connected.
[ENOTSOCK]
The socket argument does not refer to a socket.
[EOPNOTSUPP]
The specified flags are not supported for this socket type or protocol.
[ETIMEDOUT]
The connection timed out during connection establishment, or due to a
transmission timeout on active connection.

The recv() function may fail if:

[EIO]
An I/O error occurred while reading from or writing to the file system.
[ENOBUFS]
Insufficient resources were available in the system to perform the
operation.
[ENOMEM]
Insufficient memory was available to fulfill the request.

7. htonl(), htons(), htohl() and htohs()

These functions shall convert 16-bit and 32-bit quantities between network byte
order and host byte order.

On some implementations, these functions are defined as macros.

The uint32_t and uint16_t types are defined in <inttypes.h>.

41
e.g., #include <arpa/inet.h>
uint32_t htonl(uint32_t hostlong);
uint16_t htons(uint16_t hostshort);
uint32_t ntohl(uint32_t netlong);
uint16_t ntohs(uint16_t netshort);

RETURN VALUE

The htonl() and htons() functions shall return the argument value converted from
host to network byte order.

The ntohl() and ntohs() functions shall return the argument value converted from
network to host byte order.

Algorithms
Client
• Start the program
• Include necessary header files such as sys/socket.h, sys/types.h, neinet/in.h
• Create socket with the system call socket() for establishing connection and assigned some socket
descriptor.
• Check the socket descriptor value for proper creation.
• Describe the structure with family, port number and IP address.
• Bind the socket and port number with the system call bind()
• Check the socket and port number are properly bound or not.
• Receive a message from server using recv() system calls.
• Display the message on client Screen
• End the program.

Server
• Start the program
• Include necessary header files such as sys/socket.h, sys/types.h, neinet/in.h
• Create socket with the system call socket() for establishing connection and assigned some socket
descriptor.
• Check the socket descriptor value for proper creation.
• Describe the structure with family, port number and IP address.
• Bind the socket and port number with the system call bind()
• Check the socket and port number are properly bound or not.
• Using the system call listen() for listening request coming from client by server and it will return
some integer value.
• If the returned integer value is -1, then the server is not listening.
• Send a welcome message to client using send() system calls.
• End the program.

42
Program
Client
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<stdlib.h>
#include<stdio.h>
#include<unistd.h>
#include<errno.h>
#include<string.h>
int main()
{
int sock,by_recv;
char send_data[1024],recv_data[1024];
struct hostnet*host;
struct sockaddr_in server_addr;
host=gethostbyname("127.0.0.1");
if((sock=socket(AF_INET,SOCK_STREAM,0))==-1)
{
perror("socket");
exit(1);
}
server_addr.sin_family=AF_INET;
server_addr.sin_port=htons(5000);
server_addr.sin_addr=*((struct in_addr*)host->h_addr);
bzero(&(server_addr.sin_zero),8);
if(connect(sock,(struct sockaddr*)&server_addr,sizeof(struct
sockaddr))==-1)
{
perror("Connect");
exit(1);
}
while(1)
{
by_recv=recv(sock,recv_data,1024,0);
recv_data[by_recv]='\0';
if(strcmp(recv_data,"q")==0||strcmp(recv_data,"Q")==0)
{
close(sock);
break;
}
else
printf("\n RECIVED DATA=%s",recv_data);
printf("\n SEND(q or Q to quit):");
gets(send_data);
if(strcmp(send_data,"q")==0||strcmp(send_data,"Q")!=0)
send(sock,send_data,strlen(send_data),0);
else
{
send(sock,send_data,strlen(send_data),0);
close(sock);
break;
}

43
}
return 0;
}

Server
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<stdlib.h>
#include<stdio.h>
#include<unistd.h>
#include<errno.h>
#include<string.h>
int main()
{
int sock,con,by_rec,true=1;
char send_data[1024],recv_data[1024];
struct sockaddr_in server_addr,cli_addr;
int sin_size;
if((sock=socket(AF_INET,SOCK_STREAM,0))==-1)
{
perror("socket");
exit(1);
}
if(setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&true,sizeof(int))==-1)
{
perror("setsockopt");
exit(1);
}
server_addr.sin_family=AF_INET;
server_addr.sin_port=htons(5000);
server_addr.sin_addr.s_addr=INADDR_ANY;
bzero(&(server_addr.sin_zero),8);
if(bind(sock,(struct sockaddr*)&server_addr,sizeof(struct sockaddr))==-
1)
{
perror("unable to bind");
exit(1);
}
if(listen(sock,5)==-1)
{
perror("Listen");
exit(1);
}
printf("\n TCP Server waiting for client on port 5000");
fflush(stdout);
while(1)
{
sin_size=sizeof(struct sockaddr_in);
con=accept(sock,(struct sockaddr*)&cli_addr,&sin_size);
printf("\n I got a connection from(%s,
%d)",inet_ntoa(cli_addr.sin_addr),ntohs(cli_addr.sin_port));
while(1)
{

44
printf("\n SEND(q or Q to quit):");
gets(send_data);
if(strcmp(send_data,"q")==0||strcmp(send_data,"Q")==0)
{
send(con,send_data,strlen(send_data),0);
close(con);
break;
}
else
send(con,send_data,strlen(send_data),0);
by_rec=recv(con,recv_data,1024,0);
recv_data[by_rec]='\0';
if(strcmp(recv_data,"q")==0||strcmp(recv_data,"Q")==0)
{
close(con);
break;
}
else
printf("\n RECIVED DATA=%s",recv_data);
fflush(stdout);
}
}
close(sock);
return 0;
}

How to Run the Server Program


[root @ root] $ cc server.c
[root @ root] $ ./a.out

Output of the Server Program


Server Program
**************************
Socket created successfully
Socket descriptor value: 3
**************************
Successful Binding
Bind desc : 0
IP Address : 0.0.0.0
*************************
Processor is in Listener Mode
Message is sent
*************************

How to Run the Client Program


[root @ root] $ cc client.c
[root @ root] $ ./a.out

45
Output of the Client Program
Client program
Socket created
Socket descriptor value:3
Connected to the server
Message is received

Lab Session: 3 Application for Client-Server Environment (TCP,UDP)


3a. File Transfer Between Client and Server Using FTP

Aim:

 To Transfer the file between client and server using Transmission Control
Protocol.

System and Software Requirements:

 PC with UNIX/ Linux Operating systems.


 C compiler in Linux Environment

Theory

The purpose of networking applications is to allow different types of information


to be sent between networked devices. In the world of computers, information is most
often arranged into discrete units called files. When those files are created specifically for
the purpose of communication, they are often called messages. One of the most important
groups of TCP/IP applications is the one that describes the basic mechanisms for moving
these files between inter networked devices: file and message transfer applications.

File Transfer Protocol (FTP) is a standard network protocol used to exchange


and manipulate files over a TCP/IP based network, such as the Internet. FTP is built on a
client-server architecture and utilizes separate control and data connections between the
client and server applications. Applications were originally interactive command-line
tools with a standardized command syntax, but graphical user interfaces have been
developed for all desktop operating systems in use today. FTP is also often used as an

46
application component to automatically transfer files for program internal functions. FTP
can be used with user-based password authentication or with anonymous user access. The
Trivial File Transfer Protocol (TFTP) is a similar, but simplified, not interoperable, and
unauthenticated version of FTP.

Open()

open - open a file

SYNOPSIS

#include <sys/types.h>

#include <sys/stat.h>

#include <fcntl.h>

int open(const char *path, int oflag, ... );

DESCRIPTION

The open() function establishes the connection between a file and a file
descriptor. It creates an open file description that refers to a file and a file descriptor that
refers to that open file description. The file descriptor is used by other I/O functions to
refer to that file. The path argument points to a pathname naming the file.

The open() function will return a file descriptor for the named file that is the
lowest file descriptor not currently open for that process. The open file description is
new, and therefore the file descriptor does not share it with any other process in the
system. The FD_CLOEXEC file descriptor flag associated with the new file descriptor
will be cleared.

The file offset used to mark the current position within the file is set to the
beginning of the file.

The file status flags and file access modes of the open file description will be set
according to the value of oflag.

47
Values for oflag are constructed by a bitwise-inclusive-OR of flags from the
following list, defined in <fcntl.h>. Applications must specify exactly one of the first
three values (file access modes) below in the value of oflag:

O_RDONLY

Open for reading only.

O_WRONLY

Open for writing only.

O_RDWR

Open for reading and writing. The result is undefined if this flag is applied

to a FIFO.

Any combination of the following may be used:

O_APPEND

If set, the file offset will be set to the end of the file prior to each write.

O_CREAT

If the file exists, this flag has no effect except as noted under O_EXCL
below. Otherwise, the file is created; the user ID of the file is set to
the effective user ID of the process; the group ID of the file is set to
the group ID of the file's parent directory or to the effective group ID of the
process; and the access permission bits (see <sys/stat.h>) of the file
mode are set to the value of the third argument taken as type mode_t
modified as follows: a bitwise-AND is performed on the file-mode bits
and the corresponding bits in the complement of the
process' file mode creation mask. Thus, all bits in the file mode whose
corresponding bit in the file mode creation mask is set are cleared. When
bits other than the file permission bits are set, the effect is
unspecified. The third argument does not affect whether the file is
open for reading, writing or for both.

O_DSYNC

Write I/O operations on the file descriptor complete as defined by


synchronised I/O data integrity completion

O_EXCL

48
If O_CREAT and O_EXCL are set, open() will fail if the file exists. The
check for the existence of the file and the creation of the file if it does not exist
will be atomic with respect to other processes executing open() naming the same
filename in the same directory with O_EXCL and O_CREAT set. If O_CREAT is
not set, the effect is undefined.

O_NOCTTY

If set and path identifies a terminal device, open() will not cause the
terminal device to become the controlling terminal for the process.

O_NONBLOCK

When opening a FIFO with O_RDONLY or O_WRONLY set: If


O_NONBLOCK is set:

An open() for reading only will return without delay. An open() for writing only
will return an error if no process currently has the file open for reading.

If O_NONBLOCK is clear:

An open() for reading only will block the calling thread until a thread
opens the file for writing. An open() for writing only will block the calling
thread until a thread opens the file for reading.

When opening a block special or character special file that supports non-blocking
opens:

If O_NONBLOCK is set:

The open() function will return without blocking for the device to be ready
or available. Subsequent behaviour of the device is device-specific.

If O_NONBLOCK is clear:

The open() function will block the calling thread until the device is ready
or available before returning.

Otherwise, the behaviour of O_NONBLOCK is unspecified.

O_RSYNC

Read I/O operations on the file descriptor complete at the same level of
integrity as specified by the O_DSYNC and O_SYNC flags. If both O_DSYNC
and O_RSYNC are set in oflag, all I/O operations on the file descriptor complete
as defined by synchronised I/O data integrity completion. If both O_SYNC and

49
O_RSYNC are set in flags, all I/O operations on the file descriptor complete as
defined by synchronised I/O file integrity completion.

O_SYNC

Write I/O operations on the file descriptor complete as defined by


synchronised I/O file integrity completion.

O_TRUNC

If the file exists and is a regular file, and the file is successfully opened
O_RDWR or O_WRONLY, its length is truncated to 0 and the mode and owner
are unchanged. It will have no effect on FIFO special files or terminal device
files. Its effect on other file types is implementation-dependent. The result of
using O_TRUNC with O_RDONLY is undefined.

If O_CREAT is set and the file did not previously exist, upon successful
completion, open() will mark for update the st_atime, st_ctime and st_mtime fields of the
file and the st_ctime and st_mtime fields of the parent directory.

If O_TRUNC is set and the file did previously exist, upon successful completion,
open() will mark for update the st_ctime and st_mtime fields of the file.

If both the O_SYNC and O_DSYNC flags are set, the effect is as if only the
O_SYNC flag was set.

If path refers to a STREAMS file, oflag may be constructed from


O_NONBLOCK OR-ed with either O_RDONLY, O_WRONLY or O_RDWR. Other
flag values are not applicable to STREAMS devices and have no effect on them. The
value O_NONBLOCK affects the operation of STREAMS drivers and certain functions
applied to file descriptors associated with STREAMS files. For STREAMS drivers, the
implementation of O_NONBLOCK is device-specific.

If path names the master side of a pseudo-terminal device, then it is unspecified


whether open() locks the slave side so that it cannot be opened. Portable applications
must call unlockpt() before opening the slave side.

The largest value that can be represented correctly in an object of type off_t will
be established as the offset maximum in the open file description.

RETURN VALUE

Upon successful completion, the function will open the file and return a non-
negative integer representing the lowest numbered unused file descriptor. Otherwise, -1 is
returned and errno is set to indicate the error. No files will be created or modified if the
function returns -1.

50
ERRORS

The open() function will fail if:

[EACCES]

Search permission is denied on a component of the path prefix, or the file


exists and the permissions specified by oflag are denied, or the file does not exist
and write permission is denied for the parent directory of the file to be created, or
O_TRUNC is specified and write permission is denied.

[EEXIST]

O_CREAT and O_EXCL are set, and the named file exists.

[EINTR]

A signal was caught during open().

[EINVAL]

The implementation does not support synchronised I/O for this file.

[EIO]

The path argument names a STREAMS file and a hangup or error


occurred during the open().

[EISDIR]

The named file is a directory and oflag includes O_WRONLY or


O_RDWR.

[ELOOP]

Too many symbolic links were encountered in resolving path.

[EMFILE]

{OPEN_MAX} file descriptors are currently open in the calling process.

[ENAMETOOLONG]

The length of the path argument exceeds {PATH_MAX} or a pathname


component is longer than {NAME_MAX}.

51
[ENFILE]

The maximum allowable number of files is currently open in the system.

[ENOENT]

O_CREAT is not set and the named file does not exist; or O_CREAT is
set and either the path prefix does not exist or the path argument points to
an empty string.

[ENOSR]

The path argument names a STREAMS-based file and the system is


unable to allocate a STREAM.

[ENOSPC]

The directory or file system that would contain the new file cannot be
expanded, the file does not exist, and O_CREAT is specified.

[ENOTDIR]

A component of the path prefix is not a directory.

[ENXIO]

O_NONBLOCK is set, the named file is a FIFO, O_WRONLY is set and


no process has the file open for reading.

[ENXIO]

The named file is a character special or block special file, and the device
associated with this special file does not exist.

[EOVERFLOW]

The named file is a regular file and the size of the file cannot be
represented correctly in an object of type off_t.

[EROFS]

The named file resides on a read-only file system and either


O_WRONLY, O_RDWR, O_CREAT (if file does not exist) or O_TRUNC is set
in the oflag argument.

The open() function may fail if:

52
[EAGAIN]

The path argument names the slave side of a pseudo-terminal device that
is locked.

[EINVAL]

The value of the oflag argument is not valid.

[ENAMETOOLONG]

Pathname resolution of a symbolic link produced an intermediate result


whose length exceeds {PATH_MAX}.

[ENOMEM]

The path argument names a STREAMS file and the system is unable to
allocate resources.

[ETXTBSY]

The file is a pure procedure (shared text) file that is being executed and
oflag is O_WRONLY or O_RDWR.

Read()

read, readv, pread - read from a file

SYNOPSIS

#include <unistd.h>

ssize_t read(int fildes, void *buf, size_t nbyte);

ssize_t pread(int fildes, void *buf, size_t nbyte, off_t offset);

#include <sys/uio.h>

ssize_t readv(int fildes, const struct iovec *iov, int iovcnt);

DESCRIPTION

The read() function attempts to read nbyte bytes from the file associated with the
open file descriptor, fildes, into the buffer pointed to by buf.

If nbyte is 0, read() will return 0 and have no other results.

53
On files that support seeking (for example, a regular file), the read() starts at a
position in the file given by the file offset associated with fildes. The file offset is
incremented by the number of bytes actually read.

Files that do not support seeking, for example, terminals, always read from the
current position. The value of a file offset associated with such a file is undefined.

No data transfer will occur past the current end-of-file. If the starting position is at
or after the end-of-file, 0 will be returned. If the file refers to a device special file, the
result of subsequent read() requests is implementation-dependent.

If the value of nbyte is greater than {SSIZE_MAX}, the result is implementation-


dependent.

When attempting to read from an empty pipe or FIFO:

• If no process has the pipe open for writing, read() will return 0 to indicate end-of-
file.
• If some process has the pipe open for writing and O_NONBLOCK is set, read()
will return -1 and set errno to [EAGAIN].
• If some process has the pipe open for writing and O_NONBLOCK is clear, read()
will block the calling thread until some data is written or the pipe is closed by all
processes that had the pipe open for writing.

When attempting to read a file (other than a pipe or FIFO) that supports non-
blocking reads and has no data currently available:

• If O_NONBLOCK is set, read() will return a -1 and set errno to [EAGAIN].


• If O_NONBLOCK is clear, read() will block the calling thread until some data
becomes available.
• The use of the O_NONBLOCK flag has no effect if there is some data available.

The read() function reads data previously written to a file. If any portion of a
regular file prior to the end-of-file has not been written, read() returns bytes with value 0.
For example, lseek() allows the file offset to be set beyond the end of existing data in the
file. If data is later written at this point, subsequent reads in the gap between the previous
end of data and the newly written data will return bytes with value 0 until data is written
into the gap.

Upon successful completion, where nbyte is greater than 0, read() will mark for
update the st_atime field of the file, and return the number of bytes read. This number
will never be greater than nbyte. The value returned may be less than nbyte if the number
of bytes left in the file is less than nbyte, if the read() request was interrupted by a signal,
or if the file is a pipe or FIFO or special file and has fewer than nbyte bytes immediately
available for reading. For example, a read() from a file associated with a terminal may
return one typed line of data.

54
If a read() is interrupted by a signal before it reads any data, it will return -1 with
errno set to [EINTR].

If a read() is interrupted by a signal after it has successfully read some data, it will
return the number of bytes read.

A read() from a STREAMS file can read data in three different modes: byte-
stream mode, message-nondiscard mode, and message-discard mode. The default is byte-
stream mode. This can be changed using the I_SRDOPT ioctl() request, and can be tested
with the I_GRDOPT ioctl(). In byte-stream mode, read() retrieves data from the
STREAM until as many bytes as were requested are transferred, or until there is no more
data to be retrieved. Byte-stream mode ignores message boundaries.

In STREAMS message-nondiscard mode, read() retrieves data until as many


bytes as were requested are transferred, or until a message boundary is reached. If read()
does not retrieve all the data in a message, the remaining data is left on the STREAM,
and can be retrieved by the next read() call. Message-discard mode also retrieves data
until as many bytes as were requested are transferred, or a message boundary is reached.
However, unread data remaining in a message after the read() returns is discarded, and is
not available for a subsequent read(), readv() or getmsg() call.

How read() handles zero-byte STREAMS messages is determined by the current


read mode setting. In byte-stream mode, read() accepts data until it has read nbyte bytes,
or until there is no more data to read, or until a zero-byte message block is encountered.
The read() function then returns the number of bytes read, and places the zero-byte
message back on the STREAM to be retrieved by the next read(), readv() or getmsg(). In
message-nondiscard mode or message-discard mode, a zero-byte message returns 0 and
the message is removed from the STREAM. When a zero-byte message is read as the
first message on a STREAM, the message is removed from the STREAM and 0 is
returned, regardless of the read mode.

A read() from a STREAMS file returns the data in the message at the front of the
STREAM head read queue, regardless of the priority band of the message.

By default, STREAMs are in control-normal mode, in which a read() from a


STREAMS file can only process messages that contain a data part but do not contain a
control part. The read() fails if a message containing a control part is encountered at the
STREAM head. This default action can be changed by placing the STREAM in either
control-data mode or control-discard mode with the I_SRDOPT ioctl() command. In
control-data mode, read() converts any control part to data and passes it to the application
before passing any data part originally present in the same message. In control-discard
mode, read() discards message control parts but returns to the process any data part in the
message.

In addition, read() and readv() will fail if the STREAM head had processed an
asynchronous error before the call. In this case, the value of errno does not reflect the

55
result of read() or readv() but reflects the prior error. If a hangup occurs on the STREAM
being read, read() continues to operate normally until the STREAM head read queue is
empty. Thereafter, it returns 0.

The readv() function is equivalent to read(), but places the input data into the
iovcnt buffers specified by the members of the iov array: iov[0], iov[1], ..., iov[iovcnt-1].
The iovcnt argument is valid if greater than 0 and less than or equal to {IOV_MAX}.

Each iovec entry specifies the base address and length of an area in memory
where data should be placed. The readv() function always fills an area completely before
proceeding to the next.

Upon successful completion, readv() marks for update the st_atime field of the
file.

If the Synchronized Input and Output option is supported:

If the O_DSYNC and O_RSYNC bits have been set, read I/O operations on the
file descriptor complete as defined by synchronised I/O data integrity completion. If the
O_SYNC and O_RSYNC bits have been set, read I/O operations on the file descriptor
complete as defined by synchronised I/O file integrity completion.

If the Shared Memory Objects option is supported:

If fildes refers to a shared memory object, the result of the read() function is
unspecified.

For regular files, no data transfer will occur past the offset maximum established
in the open file description associated with fildes.

The pread() function performs the same action as read(), except that it reads from
a given position in the file without changing the file pointer. The first three arguments to
pread() are the same as read() with the addition of a fourth argument offset for the
desired position inside the file. An attempt to perform a pread() on a file that is incapable
of seeking results in an error.

RETURN VALUE

Upon successful completion, read(), pread() and readv() return a non-negative


integer indicating the number of bytes actually read. Otherwise, the functions return -1
and set errno to indicate the error.

ERRORS

The read(), pread() and readv() functions will fail if:

56
[EAGAIN]

The O_NONBLOCK flag is set for the file descriptor and the process
would be delayed.

[EBADF]

The fildes argument is not a valid file descriptor open for reading.

[EBADMSG]

The file is a STREAM file that is set to control-normal mode and the
message waiting to be read includes a control part.

[EINTR]

The read operation was terminated due to the receipt of a signal, and no
data was transferred.

[EINVAL]

The STREAM or multiplexer referenced by fildes is linked (directly or


indirectly) downstream from a multiplexer.

[EIO]

A physical I/O error has occurred.

[EIO]

The process is a member of a background process attempting to read from


its controlling terminal, the process is ignoring or blocking the SIGTTIN signal or
the process group is orphaned. This error may also be generated for
implementation-dependent reasons.

[EISDIR]

The fildes argument refers to a directory and the implementation does not
allow the directory to be read using read(), pread() or readv(). The readdir()
function should be used instead.

[EOVERFLOW]

57
The file is a regular file, nbyte is greater than 0, the starting position is
before the end-of-file and the starting position is greater than or equal to the offset
maximum established in the open file description associated with fildes.

The readv() function will fail if:

[EINVAL]

The sum of the iov_len values in the iov array overflowed an


ssize_t.

The read(), pread() and readv() functions may fail if:

[ENXIO]

A request was made of a non-existent device, or the request was


outside the capabilities of the device.

The readv() function may fail if:

[EINVAL]

The iovcnt argument was less than or equal to 0, or greater than


{IOV_MAX}.

The pread() function will fail, and the file pointer remains unchanged, if:

[EINVAL]

The offset argument is invalid. The value is negative.

[EOVERFLOW]

The file is a regular file and an attempt was made to read or write
at or beyond the offset maximum associated with the file.

[ENXIO]

A request was outside the capabilities of the device.

[ESPIPE]

fildes is associated with a pipe or FIFO

Read()

58
write, writev, pwrite - write on a file

SYNOPSIS
#include <unistd.h>
ssize_t write(int fildes, const void *buf, size_t nbyte);
ssize_t pwrite(int fildes, const void *buf, size_t nbyte,
off_t offset);
#include <sys/uio.h>
ssize_t writev(int fildes, const struct iovec *iov, int iovcnt);

DESCRIPTION
The write() function attempts to write nbyte bytes from the buffer pointed to by
buf to the file associated with the open file descriptor, fildes.

If nbyte is 0, write() will return 0 and have no other results if the file is a regular
file; otherwise, the results are unspecified.

On a regular file or other file capable of seeking, the actual writing of data
proceeds from the position in the file indicated by the file offset associated with fildes.
Before successful return from write(), the file offset is incremented by the number of
bytes actually written. On a regular file, if this incremented file offset is greater than the
length of the file, the length of the file will be set to this file offset.

On a file not capable of seeking, writing always takes place starting at the current
position. The value of a file offset associated with such a device is undefined.

If the O_APPEND flag of the file status flags is set, the file offset will be set to
the end of the file prior to each write and no intervening file modification operation will
occur between changing the file offset and the write operation.

If a write() requests that more bytes be written than there is room for (for
example, the ulimit or the physical end of a medium), only as many bytes as there is room
for will be written. For example, suppose there is space for 20 bytes more in a file before
reaching a limit. A write of 512 bytes will return 20. The next write of a non-zero number
of bytes will give a failure return (except as noted below) and the implementation will
generate a SIGXFSZ signal for the thread.

If write() is interrupted by a signal before it writes any data, it will return -1 with
errno set to [EINTR].

If write() is interrupted by a signal after it successfully writes some data, it will


return the number of bytes written.

If the value of nbyte is greater than {SSIZE_MAX}, the result is implementation-


dependent.

59
After a write() to a regular file has successfully returned:

• Any successful read() from each byte position in the file that was modified by
that write will return the data specified by the write() for that position until such
byte positions are again modified.
• Any subsequent successful write() to the same byte position in the file will
overwrite that file data.

Write requests to a pipe or FIFO will be handled the same as a regular file with
the following exceptions:

• There is no file offset associated with a pipe, hence each write request will append
to the end of the pipe.
• Write requests of {PIPE_BUF} bytes or less will not be interleaved with data
from other processes doing writes on the same pipe. Writes of greater than
{PIPE_BUF} bytes may have data interleaved, on arbitrary boundaries, with
writes by other processes, whether or not the O_NONBLOCK flag of the file
status flags is set.
• If the O_NONBLOCK flag is clear, a write request may cause the thread to block,
but on normal completion it will return nbyte.
• If the O_NONBLOCK flag is set, write() requests will be handled differently, in
the following ways:
o The write() function will not block the thread.
o A write request for {PIPE_BUF} or fewer bytes will have the following
effect: If there is sufficient space available in the pipe, write() will transfer
all the data and return the number of bytes requested. Otherwise, write()
will transfer no data and return -1 with errno set to [EAGAIN].
o A write request for more than {PIPE_BUF} bytes will case one of the
following:
a. When at least one byte can be written, transfer what it can and
return the number of bytes written. When all data previously
written to the pipe is read, it will transfer at least {PIPE_BUF}
bytes.
b. When no data can be written, transfer no data and return -1 with
errno set to [EAGAIN].

When attempting to write to a file descriptor (other than a pipe or FIFO) that
supports non-blocking writes and cannot accept the data immediately:

• If the O_NONBLOCK flag is clear, write() will block the calling thread until the
data can be accepted.
• If the O_NONBLOCK flag is set, write() will not block the process. If some data
can be written without blocking the process, write() will write what it can and
return the number of bytes written. Otherwise, it will return -1 and errno will be
set to [EAGAIN].

60
Upon successful completion, where nbyte is greater than 0, write() will mark for
update the st_ctime and st_mtime fields of the file, and if the file is a regular file, the
S_ISUID and S_ISGID bits of the file mode may be cleared.

If fildes refers to a STREAM, the operation of write() is determined by the values


of the minimum and maximum nbyte range ("packet size") accepted by the STREAM.
These values are determined by the topmost STREAM module. If nbyte falls within the
packet size range, nbyte bytes will be written. If nbyte does not fall within the range and
the minimum packet size value is 0, write() will break the buffer into maximum packet
size segments prior to sending the data downstream (the last segment may contain less
than the maximum packet size). If nbyte does not fall within the range and the minimum
value is non-zero, write() will fail with errno set to [ERANGE]. Writing a zero-length
buffer (nbyte is 0) to a STREAMS device sends 0 bytes with 0 returned. However,
writing a zero-length buffer to a STREAMS-based pipe or FIFO sends no message and 0
is returned. The process may issue I_SWROPT ioctl() to enable zero-length messages to
be sent across the pipe or FIFO.

When writing to a STREAM, data messages are created with a priority band of 0.
When writing to a STREAM that is not a pipe or FIFO:

• If O_NONBLOCK is clear, and the STREAM cannot accept data (the STREAM
write queue is full due to internal flow control conditions), write() will block until
data can be accepted.
• If O_NONBLOCK is set and the STREAM cannot accept data, write() will return
-1 and set errno to [EAGAIN].
• If O_NONBLOCK is set and part of the buffer has been written while a condition
in which the STREAM cannot accept additional data occurs, write() will
terminate and return the number of bytes written.

In addition, write() and writev() will fail if the STREAM head had processed an
asynchronous error before the call. In this case, the value of errno does not reflect the
result of write() or writev() but reflects the prior error.

The writev() function is equivalent to write(), but gathers the output data from the
iovcnt buffers specified by the members of the iov array: iov[0], iov[1], ..., iov[iovcnt-1].
iovcnt is valid if greater than 0 and less than or equal to {IOV_MAX}, defined in
<limits.h>.

Each iovec entry specifies the base address and length of an area in memory from
which data should be written. The writev() function will always write a complete area
before proceeding to the next.

If fildes refers to a regular file and all of the iov_len members in the array pointed
to by iov are 0, writev() will return 0 and have no other effect. For other file types, the
behaviour is unspecified.

61
If the sum of the iov_len values is greater than SSIZE_MAX, the operation fails
and no data is transferred.

If the Synchronized Input and Output option is supported:

If the O_DSYNC bit has been set, write I/O operations on the file descriptor
complete as defined by synchronised I/O data integrity completion.

If the O_SYNC bit has been set, write I/O operations on the file descriptor
complete as defined by synchronised I/O file integrity completion.

If the Shared Memory Objects option is supported:

If fildes refers to a shared memory object, the result of the write() function is
unspecified.

For regular files, no data transfer will occur past the offset maximum established
in the open file description associated with fildes.

The pwrite() function performs the same action as write(), except that it writes
into a given position without changing the file pointer. The first three arguments to
pwrite() are the same as write() with the addition of a fourth argument offset for the
desired position inside the file.

RETURN VALUE
Upon successful completion, write() and pwrite() will return the number of bytes
actually written to the file associated with fildes. This number will never be greater than
nbyte. Otherwise, -1 is returned and errno is set to indicate the error.

Upon successful completion, writev() returns the number of bytes actually written.
Otherwise, it returns a value of -1, the file-pointer remains unchanged, and errno is set to
indicate an error.

ERRORS
The write(), writev() and pwrite() functions will fail if:
[EAGAIN]
The O_NONBLOCK flag is set for the file descriptor and the thread
would be delayed in the write() operation.
[EBADF]
The fildes argument is not a valid file descriptor open for writing.
[EFBIG]
An attempt was made to write a file that exceeds the implementation-
dependent maximum file size or the process' file size limit.
[EFBIG]

62
The file is a regular file, nbyte is greater than 0 and the starting position is
greater than or equal to the offset maximum established in the open file
description associated with fildes.
[EINTR]
The write operation was terminated due to the receipt of a signal, and no
data was transferred.
[EIO]
A physical I/O error has occurred.
[EIO]
The process is a member of a background process group attempting to
write to its controlling terminal, TOSTOP is set, the process is neither ignoring
nor blocking SIGTTOU and the process group of the process is orphaned. This
error may also be returned under implementation-dependent conditions.
[ENOSPC]
There was no free space remaining on the device containing the file.

[EPIPE]
An attempt is made to write to a pipe or FIFO that is not open for reading
by any process, or that only has one end open. A SIGPIPE signal will also be sent
to the thread.
[ERANGE]
The transfer request size was outside the range supported by the
STREAMS file associated with fildes.

The writev() function will fail if:

[EINVAL]
The sum of the iov_len values in the iov array would overflow an ssize_t.

The write(), writev() and pwrite() functions may fail if:

[EINVAL]
The STREAM or multiplexer referenced by fildes is linked (directly or
indirectly) downstream from a multiplexer.
[ENXIO]
A request was made of a non-existent device, or the request was outside
the capabilities of the device.
[ENXIO]
A hangup occurred on the STREAM being written to.

A write to a STREAMS file may fail if an error message has been received at the
STREAM head. In this case, errno is set to the value included in the error message.

The writev() function may fail and set errno to:

63
[EINVAL]
The iovcnt argument was less than or equal to 0, or greater than
{IOV_MAX}.

The pwrite() function fails and the file pointer remains unchanged if:

[EINVAL]
The offset argument is invalid. The value is negative.
[ESPIPE]
fildes is associated with a pipe or FIFO.

Algorithms
Client
• Start the program
• Include necessary header files such as sys/socket.h, sys/types.h, neinet/in.h
• Create socket with the system call socket() for establishing connection and assigned some socket
descriptor.
• Check the socket descriptor value for proper creation.
• Describe the structure with family, port number and IP address.
• Bind the socket and port number with the system call bind()
• Check the socket and port number are properly bound or not.
• Create a new file in write mode for storing the received content from server.
• Write the content in file.
• End the program.

Server
• Start the program
• Include necessary header files such as sys/socket.h, sys/types.h, neinet/in.h
• Create socket with the system call socket() for establishing connection and assigned some socket
descriptor.
• Check the socket descriptor value for proper creation.
• Describe the structure with family, port number and IP address.
• Bind the socket and port number with the system call bind()
• Check the socket and port number are properly bound or not.
• Using the system call listen() for listening request coming from client by server and it will return
some integer value.
• If the returned integer value is -1, then the server is not listening.
• Open a file which is requested by the client in read mode.
• Send the file content as a stream to client.

64
• End the program.

Program
Server
#include<stdio.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
int main()
{
int i_sd,i_bind,i_size,i_acc,i_send,i_lis,fd;
char *buff[100];
FILE *fp;
printf("server program\n");
printf("************************************\n");
struct sockaddr_in server;
struct sockaddr_in client;
i_sd=socket(AF_INET,SOCK_STREAM,0);
if(-1==i_sd)
{
printf(" creation error\n");
printf(" socket descriptor value:%d\n",i_sd);
}
else
printf("socket created successfully\n");
printf("socket descriptor value:%d\n",i_sd);
printf("************************************\n");
server.sin_family=AF_INET;
server.sin_port=htons(2006);
server.sin_addr.s_addr=htonl(INADDR_ANY);
bzero(server.sin_zero,8);
i_bind=bind(i_sd,(struct sockaddr*)&server,sizeof(struct sockaddr_in));
if(-1==i_bind)
{
printf("\n binding error\n");
printf("bind desc:%d\n",i_bind);
}
else
{
printf("successfully binding\n");
printf("bind desc:%d\n",i_bind);
}
printf("IP ADDRESS :%s\n",inet_ntoa(server.sin_addr));
printf("*******************************************\n");
i_lis=listen(i_sd,3);
if(-1==i_lis)
{
printf("\n error\n");
exit(0);
}
else
{
printf("\n processor is in listener mode\n");

65
}
i_size=sizeof(struct sockaddr_in);
i_acc=accept(i_sd,(struct sockaddr*)&client,&(i_size));
if(-1==i_acc)
{
printf("\n error\n");
}
else
{
printf("\n listener is accepted\n");
fd=open("san.txt","O_RDWR");
while(read(fd,buff,100)>0)
{
i_send=send(i_acc,buff,100,0);
if(-1==i_send)
printf("\nerror\n");
}
}
}

Client
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<fcntl.h>
#include<netdb.h>
int main(int argc,char *agrv[])
{
int i_sd,i_bind,i_conn,sadd,i_rec,i_recv,fd;
char *str[100];
FILE *fp;

printf("client program\n");
printf("************************\n");
struct sockaddr_in client;
i_sd=socket(AF_INET,SOCK_STREAM,0);
if(-1==i_sd)
{
printf("creation error\n");
printf("socket descriptor value:%d\n",i_sd);
}
else
{
printf("socket created successfully\n");
printf("socket descriptor value:%d\n",i_sd);
printf("*******************************\n");
client.sin_family=AF_INET;
client.sin_port=htons(3001);
client.sin_addr.s_addr=inet_addr("127.0.0.1");
bzero(client.sin_zero,8);
i_bind=connect(i_sd,(struct sockaddr*)&client,sizeof(struct sockaddr));
if(1==i_bind)
{
printf("binding error\n");

66
}
else
{
printf("connected to server\n");
}
printf("********************************\n");
fd=open("chan.txt",O_RDWR);
while(recv(i_sd,str,100,0))
{
if(-1==i_rec)
{
printf("\nerror\n");
exit(0);
}
else
{
write(fd,str,100);
}
}
}
}

How to Run the Server Program


[root @ root] $ cc server.c
[root @ root] $ ./a.out

Output of the Server Program


Server Program
**************************
Socket created successfully
Socket descriptor value: 3
**************************
Successful Binding
Bind desc : 0
IP Address : 0.0.0.0
*************************
Processor is in Listener Mode
Message is sent
*************************
How to Run the Client Program
[root @ root] $ cc server.c
[root @ root] $ ./a.out

Output of the Client Program


Client program
Socket created
Socket descriptor value:3
Connected to the server

67
Message is received

Lab Session: 6 Domain Name Services (DNS)

Aim:

 To domain name service using UDP protocol.

System and Software Requirements:

 PC with UNIX/ Linux Operating systems.


 C compiler in Linux Environment

Theory

Every host that runs TCP/IP must have a unique IP address that's used when
communicating with other computers in a network. Computers operate easily with IP
addresses, but people don't; users would rather identify systems by a name. To facilitate
effective and efficient communication, users need to be able to refer to computers by
name, and still have their computer use IP addresses transparently.
The Domain Name System (DNS) is a hierarchical naming system for
computers, services, or any resource connected to the Internet or a private network. It
associates various information with domain names assigned to each of the participants.
Most importantly, it translates domain names meaningful to humans into the numerical
(binary) identifiers associated with networking equipment for the purpose of locating and
addressing these devices worldwide. An often used analogy to explain the Domain Name
System is that it serves as the "phone book" for the Internet by translating human-friendly

68
computer hostnames into IP addresses. For example, www.example.com translates to
192.0.32.10.
In the early days of the ARPANET, the forerunner to today's Internet, there were only a
small number of computers attached to the network. The Network Information Center
(NIC), located at Stanford Research Institute (SRI), was responsible for compiling a
single file, HOSTS.TXT, which contained the names and addresses of every computer.
Administrators would email SRI, which would then update the HOSTS.TXT file. Next,
ARPANET users would download the new version of HOSTS.TXT using File Transfer
Protocol (FTP).
As the ARPANET grew, it became obvious that this approach wouldn't scale, for the
following three key reasons:
• The bandwidth consumed in transmitting updated versions of an ARPANET-wide
host file was proportional to the square of the number of hosts in the ARPANET.
With the number of hosts growing at an exponential rate, the long-term impact
was likely to be a load that no one host was going to be able to sustain.
• The static flat host file also meant that no two computers on the ARPANET could
have the same name. As the number of hosts grew, the risk of adding a duplicate
name grew, as did the difficulty of trying to control this centrally.
• The nature of the underlying network was changing—the large, timesharing
computers that had once made up the ARPANET were being superseded by
networks of workstation—seach of which needed to have a unique host name.
This would be difficult, if not impossible, to control centrally.
As the ARPANET continued to grow, it became clear that ARPANET needed a better
solution. Several proposals were generated based on the concept of a distributed naming
service, which was based on a hierarchical name space. RFCs 882 and 883 emerged,
which described the design for a domain name system, based on a distributed database
containing generalized resource information. This design evolved, and RFCs 1034 and
1035 were issued to describe the Domain Name System (DNS) service used in today's
Internet. This design continues to evolve, and a number of proposed updates and
refinements are being discussed as this chapter is being written.

What Is DNS?

The DNS is an IETF-standard name service. The DNS service enables client
computers on your network to register and resolve DNS domain names. These names are
used to find and access resources offered by other computers on your network or other
networks, such as the Internet. The following are the three main components of DNS:
• Domain name space and associated resource records (RRs) A distributed
database of name-related information.
• DNS Name Servers Servers that hold the domain name space and RRs, and that
answer queries from DNS clients.
• DNS Resolvers The facility within a DNS client that contacts DNS name servers
and issues name queries to obtain resource record information.

Key DNS Terms

69
This section describes the key components of the DNS and defines key DNS
terms.

Domain Name Space

The domain name space is a hierarchical, tree-structured name space, starting at


an unnamed root used for all DNS operations. In the DNS name space, each node and
leaf in the domain name space tree represents a named domain. Each domain can have
additional child domains. Figure illustrates the structure of Internet domain name space.

Figure: Domain name space for the Internet.


Domain Names

Each node in the DNS tree, as Figure illustrates, has a separate name, referred to
in RFC 1034 as a label. Each DNS label can be from 1 through 63 characters in length,
with the root domain having a length of zero characters.

A specific node's domain name is the list of the labels in the path from the node
being named to the DNS Tree root. DNS convention is that the labels that compose a
domain name are read left to right—from the most specific to the root (for example,
www.kapoho.com). This full name is also known as the fully qualified domain name
(FQDN).

Domain names can be stored as upper case or lower case, but all domain
comparisons and domain functions are defined, by RFC 1034, to be case insensitive.
Thus, www.kapoho.com is identical to WWW.KAPOHO.COM for domain naming
operations.

Top-Level Domains
A top-level domain is a DNS domain directly below the root. As the above mentioned
figure illustrates, a number of top-level domains have been defined. Additional names (at
least for the Internet) are difficult to create. The following are the three categories of top-
level domains:

• "ARPA" This is a special domain—used today for reverse-name lookups.


• 3-letter domains There are six 3-character, top-level domains noted below.
• 2-letter country-based domain names These country code domains are based on
the International Organization for Standardization (ISO) country name, and are
used principally by companies and organizations outside the US. The exception is

70
the UK, which uses .uk as the top-level domain, even though the ISO country
code is GB.
Table shows the six top-level domains in use today, as defined by RFC 1591.

Table -Character Top-Level Domains in Use in the Internet


3-Character
Domain Name Use
Com Commercial organizations, such as microsoft.com for the Microsoft
Corporation
Edu Educational institutions, now mainly four-year colleges and
universities, such as cmu.edu for Carnegie Mellon University
Gov Agencies of the US Federal Government, such as fbi.gov for the US
Federal Bureau of Investigation
Int Organizations established by international treaties, such as nato.int for
NATO
Mil US military, such as af.mil for the US Air Force
Net Computers of network providers, organizations dedicated to the
Internet, Internet Service Providers (ISPs), and so forth, such as
internic.net for the Internet Network Information Center (InterNIC)
Org A top-level domain for groups that don't fit anywhere else, such as
non-government or non-profit organizations (for example, reiki.org
for information about Reiki)

Note: While these are the only 3-letter domains available today, there is pressure to
expand this number; we may well end up with more in the future.

Resource Records (RR)


A resource record is a record containing information relating to a domain that the
DNS database can hold and that a DNS client can retrieve and use. For example, the host
RR for a specific domain holds the IP address of that domain (host); a DNS client will
use this RR to obtain the IP address for the domain.

Each DNS server contains the RRs relating to those portions of the DNS
namespace for which it's authoritative (or for which it can answer queries sent by a host).
When a DNS server is authoritative for a portion of the DNS name space, those systems'
administrators are responsible for ensuring that the information about that DNS name
space portion is correct. To increase efficiency, a given DNS server can cache the RRs
relating to a domain in any part of the domain tree.
There are numerous RR types defined in RFCs 1035 and 1036, and in later RFCs.
Most of the RR types are no longer needed or used.

71
Table lists the key RRs that might be used in a Windows 2000 network. (For
more detail on the contents of specific RRs, see the "DNS Resource Records" section
later in this chapter.)
Table Key Resource Records as Used by a Windows 2000 Network
Resource
Record
Type Contents Use
A Host Address Used to hold a specific host's IP address.
CNAME Canonical Used to make an alias name for a host.
Name (alias)
MX Mail Provides message routing to a mail server, plus backup
Exchanger server(s) in case the target server isn't active.
NS Name Server Provides a list of authoritative servers for a domain or
indicates authoritative DNS servers for any delegated sub-
domains.
PTR Pointer Used for reverse lookup—resolving an IP address into a
domain name using the IN-ADDR.ARPA domain.
SOA Start of Used to determine the DNS server that's the primary
Authority server for a DNS zone and to store other zone property
information.
SRV Service Provides the ability to find the server providing a specific
Locator service. Active Directory uses SRV records to locate
domain controllers, global catalog servers, and
Lightweight Directory Access Protocol (LDAP) servers.

RRs can be attached to any node in the DNS tree, although RRs won't be provided
in some domains (for example, Pointer (PTR) RRs are found only in domains below the
in-addr.arpa domain). Thus, higher-level domains, such as microsoft.com, can have
individual RRs (for example, Mail Exchange (MX) record for mail to be sent to the
Microsoft Corporation) as well as having sub-domains that also might have individual
RRs (for instance, eu.microsoft.com, which has a host record www.eu.microsoft.com).

Canonical Names

The Canonical Name (CNAME) RR enables the administrator to create an alias to


another domain name. The use of CNAME RRs are recommended for use in the
following scenarios:
• When a host specified in an (A) RR in the same zone needs to be renamed. For
example, if you need to rename kona.kapoho.com to hilo.kapoho.com, you could
create a CNAME entry for kona.kapoho.com to point to hilo.kapoho.com.
• When a generic name for a well-known service, such as ftp or www, needs to
resolve to a group of individual computers (each with an individual (A) RR). For

72
example, you might want www.kapoho.com to be an alias for kona.kapoho.com
and hilo.kapoho.com. A user will access www.kapoho.com and generally won't be
aware of which computer is actually servicing this request.

DNS Query Operation

A DNS client issues a query operation against a DNS server to obtain some or all
of the RR information relating to a specific domain, for instance, to determine which host
(A) record or records are held for the domain named kapoho.com. If the domain exists
and the requested RRs exist, the DNS server will return the requested information in a
query reply message. The query reply message will return both the initial query and a
reply containing the relevant records, assuming the DNS server can obtain the required
RRs.

A DNS query, referred to in RFC 1034 as a standard query, contains a target


domain name, a query type, and a query class. The query will contain a request for the
specific RR(s) that the resolver wished to obtain (or a request to return all RRs relating to
the domain).

DNS Update Operation

A DNS update operation is issued by a DNS client against a DNS server to


update, add, or delete some or all of the RR information relating to a specific domain, for
instance, to update the host record for the computer named kona.kapoho.com to point to
10.10.1.100. The update operation is also referred to as a dynamic update.

DNS Zones

A DNS server that has complete information for part of the DNS name space is
said to be the authority for that part of the name space. This authoritative information is
organized into units called zones, which are the main units of replication in DNS. A zone
contains one or more RRs for one or more related DNS domains.
The following are the three DNS zone types implemented in Windows 2000:

• Standard Primary Holds the master copy of a zone and can replicate it to
secondary zones. All changes to a zone are made on the standard primary.
• Standard Secondary Contains a read-only copy of zone information that can
provide increased performance and resilience. Information in a primary zone is
replicated to the secondary by use of the zone transfer mechanism.
• Active Directory-integrated A Microsoft proprietary zone type, where the zone
information is held in the Windows 2000 Active Directory (AD) and replicated
using AD replication.

Traditionally, the master copy of each zone is held in a primary zone on a single DNS
server. On that server, the zone has a Start Of Authority (SOA) record that specifies it to
be the primary zone. To improve performance and redundancy, a primary zone can be

73
automatically distributed to one or more secondary zones held on other DNS servers.
When changes are made to the zone, for instance, to add an (A) record, the changes are
made to the primary zone and are transferred to the secondary zone. The transfer of zone
information is handled by the zone replication process, which is described later in the
"Zone Transfer" section.

The zone will only hold information about a single DNS domain name, for example,
kapoho.com. After the zone is created, the administrator can then add RRs to the zone, or
can set the domain to be dynamically updated. For example, the administrator could add
(A) records (host records) for hosts in the domain, such as kona.kapoho.com. If dynamic
updates are enabled for the zone, a Windows 2000 computer can then directly update the
A and PTR records on the DNS server (if the DNS client is also a DHCP client, the
administrator can configure a DHCP server to send the updates).
Once the administrator has created the zone, he can add additional sub-domains to the
zone (for example, jh.kapoho.com). These might be added to provide DNS services to a
new building that is managed separately from the parent domain. This sub-domain, which
might reside in a separate zone, would have RRs added (for example, a host record for
jasmine.jh.kapoho.com).

As the following figure illustrates, if other domains are added below the domain
used initially to create the zone, these domains can either be part of the same zone or
belong to another. For example, the sub-domain jh.kapoho.com, which is subordinate to
kapoho.com, could be held in the same zone as kapoho.com, or in a separate zone. This
allows the sub-domain to be managed and included as part of the original zone records, or
to be delegated away to another zone created to support that sub-domain.

Figure: Zones versus domains.

In this example, the domain kapoho.com has a sub-domain of jh.kapoho.com.


Additionally, both domains contain a single host record. In this example, the domains
jh.kapoho.com and kapoho.com are held in separate zones on different DNS servers. The
kapoho.com zone holds one host record for kona.kapoho.com. The jh.kapoho.com
domain holds the host record for the host jasmine.jh.kapoho.com.

Active Directory-Integrated Zones

74
A major new feature in the Windows 2000 DNS service is the ability to store
DNS zones within the AD. An Active Directory-integrated zone is a primary DNS zone
that's held within the AD and replicated to other AD primary zones, using AD replication
(and not traditional zone transfer). Although this method of holding zones is a Microsoft
proprietary approach, it can provide some useful benefits.

The main advantage of AD-integrated zones is that the zones become, in effect,
multi-master, with the capability of updates being made to any DNS server. This can
increase the fault tolerance of the DNS service. In addition, replication of zone
information occurs using AD replication, which can be more efficient across slow links,
because of the way that AD compresses replication data between sites.

Reverse-Lookup Zones

Most queries sent to a DNS server involve a search based on the DNS name of
another computer as stored in an address (A) RR. This type of query expects an IP
address as the resource data for the answered response. This type of query is generally
referred to as a forward query. DNS also provides a reverse-lookup process, which
enables a host to determine another host's name based on its IP address. For example,
"What is the DNS domain name of the host at IP address 10.10.1.100?"

To allow for reverse queries, a special domain, in-addr.arpa, was defined and
reserved in the Internet DNS name space. Sub-domains within the in-addr.arpa domain
are named using the reverse ordering of the numbers in the dotted-decimal notation of IP
addresses. The reverse ordering of the domain name is needed because, unlike DNS
names, IP addresses are read from left to right, but are interpreted in the opposite manner
(that is, the left-most part is more generalized than the right-most part). For this reason,
the order of IP address octets is reversed when building the in-addr.arpa domain tree; for
example, the reverse-lookup zone for the subnet 192.168.100.0 is 100.168.192.in-
addr.arpa.

This approach enables the administration of lower limbs of the DNS in-addr.arpa
tree to be delegated to an organization when it obtains a set of IP addresses from an IP
registry.

The in-addr.arpa domain tree makes use of the PTR RR. The PTR RR is used to
associate the IP address to the owning domain name. This lookup should correspond to
an Address RR for the host in a forward-lookup zone. The success of a PTR RR used in
reverse query depends on the validity of its pointer data, the (A) RR, which must exist.
Note: The in-addr.arpa domain is used only for Internet Protocol version 4 (IPv4)-based
networks. In the Windows 2000 DNS Microsoft Management Console (MMC) snap-in,
the DNS server's New Zone wizard will use this domain when it creates a new reverse-
lookup zone. Internet Protocol version 6 (IPv6)-based reverse-lookup zones are based on
the domain ip6.arpa.

75
Reverse Queries

A reverse query is one in which the DNS server is requested to return the DNS
domain name for a host at a particular IP address. Reverse-Lookup Query messages are,
in effect, standard queries, but relating to the reverse-lookup zone. The reverse-lookup
zone is based on the in-addr.arpa domain name and mainly holds PTR RRs.

Inverse Queries

Inverse queries originally were described in RFC 1032, but now are outdated.
Inverse queries were meant to look up a host name based on its IP address and use a
nonstandard DNS query operation. The use of inverse queries is limited to some of the
earlier versions of NSLOOKUP.EXE, a utility used to test and troubleshoot a DNS
service.

DNS Query Classes

DNS queries fall into one of two classes: recursive queries and iterative queries.
A recursive query is a DNS query sent to a DNS server in which the querying host asks
the DNS server to provide a complete answer to the query, even if that means contacting
other servers to provide the answer. When sent a recursive query, the DNS server will use
separate iterative queries to other DNS servers on behalf of the querying host to obtain an
answer for the query.

An iterative query is a DNS query sent to a DNS server in which the querying
host requests it to return the best answer the DNS server can provide without seeking
further assistance from other DNS servers.

In general, host computers issue recursive queries against DNS servers. The host
assumes that the DNS server either knows the answer to the query, or can find the
answer. On the other hand, a DNS server will generally issue iterative queries against
other DNS servers if it is unable to answer a recursive query from cached information.

System Function Used in Program


Description

The gethostbyname() function returns a structure of type hostent for the given
host name. Here name is either a host name, or an IPv4 address in standard dot notation,
or an IPv6 address in colon (and possibly dot) notation. (See RFC 1884 for the
description of IPv6 addresses.) If name is an IPv4 or IPv6 address, no lookup is
performed and gethostbyname() simply copies name into the h_name field and its struct
in_addr equivalent into the h_addr_list[0] field of the returned hostent structure. If name
doesn't end in a dot and the environment variable HOSTALIASES is set, the alias file
pointed to by HOSTALIASES will first be searched for name (see hostname(7) for the
file format). The current domain and its parents are searched unless name ends in a dot.

76
The gethostbyaddr() function returns a structure of type hostent for the given host address
addr of length len and address type type. Valid address types are AF_INET and
AF_INET6. The host address argument is a pointer to a struct of a type depending on the
address type, for example a struct in_addr * (probably obtained via a call to inet_addr())
for address type AF_INET.

The sethostent() function specifies, if stayopen is true (1), that a connected TCP
socket should be used for the name server queries and that the connection should remain
open during successive queries. Otherwise, name server queries will use UDP datagrams.
The endhostent() function ends the use of a TCP connection for name server queries.
The (obsolete) herror() function prints the error message associated with the current value
of h_errno on stderr.
The (obsolete) hstrerror() function takes an error number (typically h_errno) and
returns the corresponding message string.

The domain name queries carried out by gethostbyname() and gethostbyaddr() use
a combination of any or all of the name server named(8), a broken out line from
/etc/hosts, and the Network Information Service (NIS or YP), depending upon the
contents of the order line in /etc/host.conf. The default action is to query named(8),
followed by /etc/hosts.

The hostent structure is defined in <netdb.h> as follows:

struct hostent {
char
*h_name;
/* official name of host */
char
**h_aliases;
/* alias list */
int
h_addrtype;
/* host address type */
int
h_length;
/* length of address */
char
**h_addr_list;
/* list of addresses */
}
#define h_addr
h_addr_list[0]
/* for backward compatibility */
The members of the hostent structure are:
h_name
The official name of the host.

77
h_aliases
An array of alternative names for the host, terminated by a NULL pointer.
h_addrtype
The type of address; always AF_INET or AF_INET6 at present.
h_length
The length of the address in bytes.
h_addr_list
An array of pointers to network addresses for the host (in network byte order), terminated
by a NULL pointer.
h_addr
The first address in h_addr_list for backward
compatibility.
Return Value

The gethostbyname() and gethostbyaddr() functions return the hostent structure or


a NULL pointer if an error occurs. On error, the h_errno variable holds an error number.
When non-NULL, the return value may point at static data, see the notes below.

Errors
The variable h_errno can have the following values:
HOST_NOT_FOUND
The specified host is unknown.
NO_ADDRESS or NO_DATA
The requested name is valid but does not have an IP address.
NO_RECOVERY
A non-recoverable name server error occurred.
TRY_AGAIN
A temporary error occurred on an authoritative name server. Try again later.
Files
/etc/host.conf
resolver configuration file
/etc/hosts
host database file
/etc/nsswitch.conf
name service switch configuration

Algorithms
• Start the program
• Include necessary header files such as sys/socket.h, sys/types.h, neinet/in.h
• Create the variable for predefined structure hostent
• Get the members of the structure as Name, Address, Address type, Alias and address list with the
help of the structure variable.
• Print all the output
• End the program.

Program

78
#include<stdio.h>
#include<netdb.h>
#include<sys/socket.h>
#include<netinet/in.h>
int main(int argc,char *argv[])
{
struct hostent *h;
h=gethostbyname(argv[1]);
if(h==NULL)
{
herror("ERROR\n");
}
else
{
printf("\n Name :%s ",h->h_name);
printf("\n Address:%s ",inet_ntoa((struct in_addr*)h->h_addr));
printf("\n Addresstype is %d",h->h_addrtype);
printf("\n Alias:%s",h->h_aliases[0]);
printf("\n Address list:%s\n",inet_ntoa((struct in_addr *)h-
>h_addr_list[0]));
}
return 0;
}

How to Run the Server Program


[root @ root] $ cc dns.c
[root @ root] $ ./a.out local host

Output of the Program


Name : local host. local domain
Address: 16.151.4.8
Addresstype is 2
Alias : 1108550716.
Address list: 32.151.4.8

79
Lab Session: 7 Getting MAC Address
7.a Mapping Logical Addressing to Physical Addressing

Aim:

 To map Logical Addressing (IP Addressing) to Physical Addressing


(MAC Address/Hardware Address)..

System and Software Requirements:

 PC with Windows XX Operating systems.


 JAVA Interpretter

Theory

The address resolution protocol (arp) is a protocol used by the Internet Protocol
(IP) [RFC826], specifically IPv4, to map IP network addresses to the hardware addresses
used by a data link protocol. The protocol operates below the network layer as a part of
the interface between the OSI network and OSI link layer. It is used when IPv4 is used
over Ethernet.

The term address resolution refers to the process of finding an address of a


computer in a network. The address is "resolved" using a protocol in which a piece of
information is sent by a client process executing on the local computer to a server process
executing on a remote computer. The information received by the server allows the server
to uniquely identify the network system for which the address was required and therefore
to provide the required address. The address resolution procedure is completed when the
client receives a response from the server containing the required address.

An Ethernet network uses two hardware addresses which identify the source and
destination of each frame sent by the Ethernet. The destination address (all 1's) may also
identify a broadcast packet (to be sent to all connected computers). The hardware address

80
is also known as the Medium Access Control (MAC) address, in reference to the
standards which define Ethernet. Each computer network interface card is allocated a
globally unique 6 byte link address when the factory manufactures the card (stored in a
PROM). This is the normal link source address used by an interface. A computer sends
all packets which it creates with its own hardware source link address, and receives all
packets which match the same hardware address in the destination field or one (or more)
pre-selected broadcast/multicast addresses.

The Ethernet address is a link layer address and is dependent on the interface card
which is used. IP operates at the network layer and is not concerned with the link
addresses of individual nodes which are to be used.The address resolution protocol (arp)
is therefore used to translate between the two types of address. The arp client and server
processes operate on all computers using IP over Ethernet. The processes are normally
implemented as part of the software driver that drives the network interface card.

There are four types of arp messages that may be sent by the arp protocol. These are
identified by four values in the "operation" field of an arp message. The types of message
are:

1. ARP request
2. ARP reply
3. RARP request
4. RARP reply

The format of an arp message is shown below:

Format of an arp message used to resolve the remote MAC Hardware Address (HA)

To reduce the number of address resolution requests, a client normally caches


resolved addresses for a (short) period of time. The arp cache is of a finite size, and
would become full of incomplete and obsolete entries for computers that are not in use if
it was allowed to grow without check. The arp cache is therefore periodically flushed of
all entries. This deletes unused entries and frees space in the cache. It also removes any
unsuccessful attempts to contact computers which are not currently running.

If a host changes the MAC address it is using, this can be detected by other hosts
when the cache entry is deleted and a fresh arp message is sent to establish the new
association. The use of gratuitous arp (e.g. triggered when the new NIC interface is
enabled with an IP address) provides a more rapid update of this information.

81
Example of use of the Address Resolution Protocol (arp)

The figure below shows the use of arp when a computer tries to contact a remote
computer on the same LAN (known as "sysa") using the "ping" program. It is assumed
that no previous IP datagrams have been received form this computer, and therefore arp
must first be used to identify the MAC address of the remote computer.

The arp request message ("who is X.X.X.X tell Y.Y.Y.Y", where X.X.X.X and
Y.Y.Y.Y are IP addresses) is sent using the Ethernet broadcast address, and an Ethernet
protocol type of value 0x806. Since it is broadcast, it is received by all systems in the
same collision domain (LAN). This is ensures that is the target of the query is connected
to the network, it will receive a copy of the query. Only this system responds. The other
systems discard the packet silently.

The target system forms an arp response ("X.X.X.X is hh:hh:hh:hh:hh:hh", where


hh:hh:hh:hh:hh:hh is the Ethernet source address of the computer with the IP address of
X.X.X.X). This packet is unicast to the address of the computer sending the query (in this
case Y.Y.Y.Y). Since the original request also included the hardware address (Ethernet
source address) of the requesting computer, this is already known, and doesn't require
another arp message to find this out.

82
Gratuitous ARP

Gratuitous ARP is used when a node (end system) has selected an IP address and
then wishes to defend its chosen address on the local area network (i.e. to check no other
node is using the same IP address). It can also be used to force a common view of the
node's IP address (e.g. after the IP address has changed).

Use of this is common when an interface is first configured, as the node attempts
to clear out any stale caches that might be present on other hosts. The node simply sends
an arp request for itself.

Proxy ARP

Proxy ARP is the name given when a node responds to an arp request on behalf of
another node. This is commonly used to redirect traffic sent to one IP address to another
system.

Proxy ARP can also be used to subvert traffic away from the intended recipient.
By responding instead of the intended recipient, a node can pretend to be a different node
in a network, and therefore force traffic directed to the node to be redirected to itself. The
node can then view the traffic (e.g. before forwarding this to the originally intended node)
or could modify the traffic. Improper use of Proxy ARP is therefore a significant security
vulnerability and some networks therefore implement systems to detect this. Gratuitous
ARP can also help defend the correct IP to MAC bindings.

83
Classes and Methods Used in Java
Class -Process
java.lang.Object
java.lang.Process

public abstract class Process


extends Object

The Runtime.exec methods create a native process and return an instance of a


subclass of Process that can be used to control the process and obtain information about
it. The class Process provides methods for performing input from the process,
performing output to the process, waiting for the process to complete, checking the exit
status of the process, and destroying (killing) the process.

The Runtime.exec methods may not work well for special processes on certain
native platforms, such as native windowing processes, daemon processes, Win16/DOS
processes on Microsoft Windows, or shell scripts. The created subprocess does not have
its own terminal or console. All its standard io (i.e. stdin, stdout, stderr) operations will be
redirected to the parent process through three streams (Process.getOutputStream(),
Process.getInputStream(), Process.getErrorStream()). The parent process uses
these streams to feed input to and get output from the subprocess. Because some native
platforms only provide limited buffer size for standard input and output streams, failure
to promptly write the input stream or read the output stream of the subprocess may cause
the subprocess to block, and even deadlock.

The subprocess is not killed when there are no more references to the Process
object, but rather the subprocess continues executing asynchronously.

There is no requirement that a process represented by a Process object execute


asynchronously or concurrently with respect to the Java process that owns the Process
object.

Class-BufferedReader
java.lang.Object
java.io.Reader
java.io.BufferedReader
Direct Known Subclasses:
LineNumberReader

public class BufferedReader


extends Reader

Read text from a character-input stream, buffering characters so as to provide for


the efficient reading of characters, arrays, and lines.

84
The buffer size may be specified, or the default size may be used. The default is
large enough for most purposes.

In general, each read request made of a Reader causes a corresponding read


request to be made of the underlying character or byte stream. It is therefore advisable to
wrap a BufferedReader around any Reader whose read() operations may be costly, such
as FileReaders and InputStreamReaders. For example,

BufferedReader in
= new BufferedReader(new FileReader("foo.in"));

will buffer the input from the specified file. Without buffering, each invocation of read()
or readLine() could cause bytes to be read from the file, converted into characters, and
then returned, which can be very inefficient.

Programs that use DataInputStreams for textual input can be localized by


replacing each DataInputStream with an appropriate BufferedReader.

Class- InputStreamReader
java.lang.Object
java.io.Reader
java.io.InputStreamReader
Direct Known Subclasses:
FileReader
public class InputStreamReader
extends Reader

An InputStreamReader is a bridge from byte streams to character streams: It reads


bytes and decodes them into characters using a specified charset. The charset that it
uses may be specified by name or may be given explicitly, or the platform's default
charset may be accepted.

Each invocation of one of an InputStreamReader's read() methods may cause one


or more bytes to be read from the underlying byte-input stream. To enable the efficient
conversion of bytes to characters, more bytes may be read ahead from the underlying
stream than are necessary to satisfy the current read operation.

For top efficiency, consider wrapping an InputStreamReader within a


BufferedReader. For example:

BufferedReader in
= new BufferedReader(new InputStreamReader(System.in));

java.util
Class StringTokenizer
java.lang.Object
java.util.StringTokenizer

85
All Implemented Interfaces:
Enumeration
public class StringTokenizer
extends Object
implements Enumeration

The string tokenizer class allows an application to break a string into tokens. The
tokenization method is much simpler than the one used by the StreamTokenizer class.
The StringTokenizer methods do not distinguish among identifiers, numbers, and
quoted strings, nor do they recognize and skip comments.

The set of delimiters (the characters that separate tokens) may be specified either
at creation time or on a per-token basis.

An instance of StringTokenizer behaves in one of two ways, depending on whether


it was created with the returnDelims flag having the value true or false:

• If the flag is false, delimiter characters serve to separate tokens. A token is a


maximal sequence of consecutive characters that are not delimiters.
• If the flag is true, delimiter characters are themselves considered to be tokens. A
token is thus either one delimiter character, or a maximal sequence of consecutive
characters that are not delimiters.

A StringTokenizer object internally maintains a current position within the string to


be tokenized. Some operations advance this current position past the characters
processed.

A token is returned by taking a substring of the string that was used to create the
StringTokenizer object.

The following is one example of the use of the tokenizer. The code:

StringTokenizer st = new StringTokenizer("this is a test");


while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}

prints the following output:

this
is
a
test

86
StringTokenizer is a legacy class that is retained for compatibility reasons
although its use is discouraged in new code. It is recommended that anyone seeking this
functionality use the split method of String or the java.util.regex package instead.

The following example illustrates how the String.split method can be used to
break up a string into its basic tokens:

String[] result = "this is a test".split("\\s");


for (int x=0; x<result.length; x++)
System.out.println(result[x]);

prints the following output:

this
is
a
test

Algorithms

• Start the program


• Include necessary packages such as java.net.*, java.io.*, java.lan.Object,
java.util.*
• Create a process for running the command arp –a.
• Get the system arp table
• Print all the output
• End the program.

Program
import java.net.*;
import java.io.*;
import java.lang.Object;
import java.util.*;
class arp
{
public static void main(String args[])
{
boolean b=false;
try
{
Process p=Runtime.getRuntime().exec("arp -a");
BufferedReader br=new BufferedReader(new InputStreamReader(p.getInputStream()));
String str,str1="",st1,st2;
while((str=br.readLine())!=null)
str1+=str+"\n";
StringTokenizer st=new StringTokenizer(str1,"\n");

87
BufferedReader br1=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the IP ADDRESS");
st2=br1.readLine();
while(st.hasMoreTokens())
{
st1=st.nextToken();
if(st1.indexOf(st2)!=-1)
{
b=true; System.out.println(st1);
}
}
if(b==false)
System.out.println("Given Ip informations are not available in the ARP
Table...\n Ping that Ip and Check.....");
}
catch(Exception E)
{
E.printStackTrace();
}

}
}
How to Run the Server Program
E:\j2sdk1.4.0\bin\hema>javac arp.java

E:\j2sdk1.4.0\bin\hema>java arp
Output of the Program
Enter the IP ADDRESS
172.16.6.145
172.16.6.145 00-50-fc-40-7a-82 dynamic
E:\j2sdk1.4.0\bin\hema>

Lab Session: 7 Getting MAC Address


7.b Mapping Physical Addressing to Logical Addressing

Aim:

 To map Physical Addressing (MAC / Hardware Addressing) to Logical


Addressing (IP Address)..

88
System and Software Requirements:

 PC with Windows XX Operating systems.


 JAVA Interpretter

Theory

The Reverse Address Resolution Protocol (RARP) is a computer networking


protocol used by a host computer to request its Internet Protocol (IPv4) address from an
administrative host, when it has available its Link Layer or hardware address, such as a
MAC address.

RARP is described in Internet Engineering Task Force (IETF) publication RFC


[1]
903. It has been rendered obsolete by the Bootstrap Protocol (BOOTP) and the modern
Dynamic Host Configuration Protocol (DHCP), which both support a much greater
feature set than RARP.

RARP requires one or more server hosts to maintain a database of mappings of


Link Layer addresses to their respective protocol addresses. Media Access Control
(MAC) addresses needed to be individually configured on the servers by an
administrator. RARP was limited to serving only IP addresses.

Reverse ARP differs from the Inverse Address Resolution Protocol (InARP)
described in RFC 2390, which is designed to obtain the IP address associated with
another host's MAC address. InARP is the complement of the Address Resolution
Protocol used for the reverse lookup.

Algorithms

• Start the program


• Include necessary packages such as java.net.*, java.io.*, java.lan.Object,
java.util.*
• Create a process for running the command arp –a.
• Get the system arp table
• Write the arp table Lookup process for obtaining MAC address to IP Address
• Print all the output
• End the program.

Program
import java.net.*;
import java.io.*;
import java.lang.Object;
import java.util.*;
class rarp
{

89
public static void main(String args[])
{
try
{
Process p=Runtime.getRuntime().exec("arp -a");
BufferedReader br=new BufferedReader(new
InputStreamReader(p.getInputStream()));
String str,str1="",st1,st2;
while((str=br.readLine())!=null)
str1+=str+"\n";
StringTokenizer st=new StringTokenizer(str1,"\n");
BufferedReader br1=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the physical 48-bit ADDRESS");
st2=br1.readLine();
while(st.hasMoreTokens())
{
st1=st.nextToken();
if(st1.indexOf(st2)!=-1)
System.out.println(st1);
}
}
catch(Exception E)
{
E.printStackTrace();
}

}
}
How to Run the Server Program
E:\j2sdk1.4.0\bin\hema>javac rarp.java
E:\j2sdk1.4.0\bin\hema>java rarp
Output of the Program
Enter the physical ADDRESS
00-50-fc-40-7a-82
172.16.6.145 00-50-fc-40-7a-82 dynamic
E:\j2sdk1.4.0\bin\hema>
Lab Session: 7 Getting MAC Address
7.c To retrieve LocalHost details using java program

Aim:

 To get local host name and local host address

System and Software Requirements:

90
 PC with Windows XX Operating systems.
 JAVA Interpretter

Theory
java.net
Class InetAddress
java.lang.Object
java.net.InetAddress
All Implemented Interfaces:
Serializable
Direct Known Subclasses:
Inet4Address, Inet6Address

public class InetAddress


extends Object
implements Serializable
This class represents an Internet Protocol (IP) address.

An IP address is either a 32-bit or 128-bit unsigned number used by IP, a lower-


level protocol on which protocols like UDP and TCP are built. The IP address
architecture is defined by RFC 790: Assigned Numbers, RFC 1918: Address Allocation
for Private Internets, RFC 2365: Administratively Scoped IP Multicast, and RFC 2373:
IP Version 6 Addressing Architecture. An instance of an InetAddress consists of an IP
address and possibly its corresponding host name (depending on whether it is constructed
with a host name or whether it has already done reverse host name resolution).
Address types

u An identifier for a single interface. A packet sent to a unicast address is


nicast delivered to the interface identified by that address.
The Unspecified Address -- Also called anylocal or wildcard address. It
must never be assigned to any node. It indicates the absence of an address. One
example of its use is as the target of bind, which allows a server to accept a
client connection on any interface, in case the server host has multiple
interfaces.
The unspecified address must not be used as the destination address of
an IP packet.
The Loopback Addresses -- This is the address assigned to the loopback
interface. Anything sent to this IP address loops around and becomes IP input
on the local host. This address is often used when testing a client.
m An identifier for a set of interfaces (typically belonging to different
ulticast nodes). A packet sent to a multicast address is delivered to all interfaces
identified by that address.

IP address scope

91
Link-local addresses are designed to be used for addressing on a single link for
purposes such as auto-address configuration, neighbor discovery, or when no routers are
present.
Site-local addresses are designed to be used for addressing inside of a site without
the need for a global prefix.
Global addresses are unique across the internet.

Textual representation of IP addresses

The textual representation of an IP address is address family specific.

For IPv4 address format, please refer to Inet4Address#format; For IPv6 address
format, please refer to Inet6Address#format.

Host Name Resolution

Host name-to-IP address resolution is accomplished through the use of a


combination of local machine configuration information and network naming services
such as the Domain Name System (DNS) and Network Information Service(NIS). The
particular naming services(s) being used is by default the local machine configured one.
For any host name, its corresponding IP address is returned.

Reverse name resolution means that for any IP address, the host associated with
the IP address is returned.

The InetAddress class provides methods to resolve host names to their IP


addresses and vise versa.

InetAddress Caching

The InetAddress class has a cache to store successful as well as unsuccessful host
name resolutions. The positive caching is there to guard against DNS spoofing attacks;
while the negative caching is used to improve performance.

By default, the result of positive host name resolutions are cached forever,
because there is no general rule to decide when it is safe to remove cache entries. The
result of unsuccessful host name resolution is cached for a very short period of time (10
seconds) to improve performance.

Under certain circumstances where it can be determined that DNS spoofing


attacks are not possible, a Java security property can be set to a different Time-to-live
(TTL) value for positive caching. Likewise, a system admin can configure a different
negative caching TTL value when needed.
Two Java security properties control the TTL values used for positive and
negative host name resolution caching:

92
networkaddress.cache.ttl (default: -1)

Indicates the caching policy for successful name lookups from the name service.
The value is specified as as integer to indicate the number of seconds to cache the
successful lookup.

A value of -1 indicates "cache forever".

networkaddress.cache.negative.ttl (default: 10)

Indicates the caching policy for un-successful name lookups from the name
service. The value is specified as as integer to indicate the number of seconds to cache
the failure for un-successful lookups.

A value of 0 indicates "never cache". A value of -1 indicates "cache forever".

Method Summary
boolean equals(Object obj)
Compares this object against the specified object.
byte[] getAddress()
Returns the raw IP address of this InetAddress object.
static InetA getAllByName(String host)
ddress[] Given the name of a host, returns an array of its IP addresses,
based on the configured name service on the system.
static InetA getByAddress(byte[] addr)
ddress Returns an InetAddress object given the raw IP address .
static InetA getByAddress(String host, byte[] addr)
ddress Create an InetAddress based on the provided host name and IP
address No name service is checked for the validity of the address.
static InetA getByName(String host)
ddress Determines the IP address of a host, given the host's name.
String getCanonicalHostName()
Gets the fully qualified domain name for this IP address.
String getHostAddress()
Returns the IP address string in textual presentation.
String getHostName()
Gets the host name for this IP address.
static InetA getLocalHost()
ddress Returns the local host.
Int hashCode()

93
Returns a hashcode for this IP address.
boolean isAnyLocalAddress()
Utility routine to check if the InetAddress in a wildcard
address.
boolean isLinkLocalAddress()
Utility routine to check if the InetAddress is an link local
address.
boolean isLoopbackAddress()
Utility routine to check if the InetAddress is a loopback
address.
boolean isMCGlobal()
Utility routine to check if the multicast address has global
scope.
boolean isMCLinkLocal()
Utility routine to check if the multicast address has link scope.
boolean isMCNodeLocal()
Utility routine to check if the multicast address has node scope.
boolean isMCOrgLocal()
Utility routine to check if the multicast address has
organization scope.
boolean isMCSiteLocal()
Utility routine to check if the multicast address has site scope.
boolean isMulticastAddress()
Utility routine to check if the InetAddress is an IP multicast
address.
boolean isSiteLocalAddress()
Utility routine to check if the InetAddress is a site local
address.
String toString()
Converts this IP address to a String.

Algorithms

• Start the program


• Include necessary packages such as java.net.*, java.io.*, java.lan.Object,
java.util.*
• Create a object for InetAddress Class.
• Get the system name and address by gerHostName() and getHostAddress()

94
• Print all the output
• End the program.

Program
import java.net.*;
class localhost
{
public static void main(String arg[])
{
try
{
InetAddress add=InetAddress.getLocalHost();
System.out.println("The hostaddress is"+add);
System.out.println("The hostname is"+add.getHostName());
System.out.println("The hostaddress is"+add.getHostAddress());
}
catch(UnknownHostException e)
{
System.out.println(e+"exception catched");
}
}
}
How to Run the Server Program
C:\jdk1.4\bin>java localhost
The hostaddress isint07/172.16.6.147
The hostname isint07

The hostaddress is172.16.6.147

Lab Session: 7 Getting MAC Address


7.d Port scanning using java program

Aim:

 To get all the system ports and check its status.

System and Software Requirements:

 PC with Windows XX Operating systems.


 JAVA Interpretter

Theory

95
Refer chapter- 2
Algorithms

• Start the program


• Include necessary packages such as java.net.*, java.io.*, java.lan.Object,
java.util.*
• Create a object for ServerSocket Class.
• Check the status of each port form port number 0 to 65000.
• Print all the output
• End the program.

Program
import java.net.*;
class port
{
public static void main(String arg[])
{
for(int i=0;i<65000;i++)
{
try
{
ServerSocket socket=new ServerSocket(i);
}
catch(Exception e)
{
System.out.println("The port "+i+" cann't be registered");
}
}
}
}

How to Run the Server Program


C:\jdk1.4\bin>java port
The port 23 cann't be registered
The port 135 cann't be registered
The port 139 cann't be registered
The port 445 cann't be registered
The port 1033 cann't be registered
The port 1043 cann't be registered
The port 1070 cann't be registered
The port 1072 cann't be registered
The port 1076 cann't be registered
The port 1080 cann't be registered
The port 1082 cann't be registered
The port 1084 cann't be registered

96
The port 1191 cann't be registered
The port 1193 cann't be registered
The port 1195 cann't be registered
The port 1201 cann't be registered
The port 1203 cann't be registered
The port 1205 cann't be registered
The port 1207 cann't be registered

Lab Session: 8 HTTP Download


8a. Web page Content download
Aim:

 To download the web page content using java.

System and Software Requirements:

 PC with Windows XX Operating systems.


 JAVA Interpretter

Theory
1. Working with URLs

97
• URL is a reference (an address) to a resource on the Internet. URLs are the
doorway to Internet and the World Wide Web
• In Java, we have URL class from java.net. Once created, we can use its methods
to find out its host name, filename, and other information
• All URL has two components:
The protocol identifier
The resource name
• For example: http://www.akce.ac.in
• http is the protocol (Hypertext Transfer Protocol)
The resource name contains one or more of the following components:
1. Host name - the name of the machine the resource lives on
2. Filename - the pathname to the file on the machine
3. Port number - the port number connected to (Optional)
4. Reference - A reference to a named anchor within a resource (Optional)
• For example:
http://www.openloop.com:80/index.html#bottom

2 Creating a URL

• Can be created from String


• Human string will be http://www.openloop.com

In Java:
URL myObj = new URL("http://www.openloop.com/");
// the / at the end has a default of /index.html

• This is an absolute URL - contains all of the information necessary to reach the
resource in question
• A relative URL contains only enough information to reach the resource relative to
(or in the context of) another URL
• In Java, we can create relative URL object as well

URL myObj = new URL("http://www.openloop.com/");


URL otherObj = new URL(myObj, "index2.html"); // index2.html is on site openloop

• Two constructor of the URL class:

URL(String) // Absolute URL object


URL(URL, String) // relatvie URL object

The general forms are:

• URL(String absoluteURL)
• URL(URL baseURL, String relativeURL)

3. Other URL Constructors

98
• These constructor are useful when working with hostname, filename, port number
and references

URL myObj = new URL("http", "www.openloop.com", "/index.htm");

• The above is equivalent to


URL("http://www.openloop.com/index.htm");
• The final constructor will take a port as well:
URL myObj = new URL("http", "www.openloop.com", 80, "/index.htm");

4. MalformedURLException

Each of the four URL constructors will throws a MailformedURLException if


there is a null argument or unknown protocol

// Catch and handle this exception by embedding your URL constructor


try
{
URL myURL = new URL(...)
}
catch
{
...
// exception handler code here
...
} // We will talk about exception handling in detail later on

5. Parsing a URL

• URL class methods:


o getProtocol()
o getHost()
o getPort()
o getFile() - Returns the filename component of the URL
o getRef - Returns the reference component of the URL

Example:
import java.net.*
import java.io.*

try
{
aURL = new URL("http://java.sun.com/");
System.out.println("protocol = " + aURL.getProtocol());
}
catch (MalformedURLException e)

99
{
System.out.println("MalformedURLException:" + e);
}

6. Reading Directly from a URL

• Use the openStream method to get a stream from the content of the URL
• openStream returns a java.io.InputStream
• Use the openConnection method to initiate the connection to the URL

Example:
// This part of the java application reads the content from the input stream
// and then echo out the contents to the display
try
{
URL myObj = new URL("http://www.openloop.com/");
BufferedReader dis = new BufferedReader(new
InputStreamReader(myObj.openStream()));
String inputLine;
while ((inputLine = dis.readLine()) != null)
{
System.out.println(inputLine);
}
dis.close();
}
catch (MalformedURLException me)
{
System.out.println("MalformedURLException: " + me);
}
catch (IOException ioe)
{
System.out.println("IOException: " + ioe);
}
Algorithms

• Start the program


• Include necessary packages such as java.net.*, java.io.*, java.lan.Object,
java.util.*
• Create a object for URL class.
• Read all content from the web page.
• Print all the output
• End the program.

Program
import java.net.*;
import java.io.*;

100
import java.util.*;

class UCDemo
{
public static void main(String args[]) throws Exception
{
int c;
URL url=new URL("http://www.yahoo.com");
URLConnection ucon = url.openConnection();
System.out.println("Date" + new Date(ucon.getDate()));
System.out.println("Content Type" + ucon.getContentType());
int len=ucon.getContentLength();
if(len > 0)
{
System.out.println(".....Content.....");
InputStream ip=ucon.getInputStream();
int i=len;
while(((c=ip.read())!=-1) && --i>0)
{
System.out.print((char)c);
}
ip.close();
}
else
System.out.println("No content, Page is empty");
}
}
How to Run the Server Program
E:\j2sdk1.4.0\bin\ >javac UCDemo.java
E:\j2sdk1.4.0\bin\java -Dhttp.proxyHost=172.16.0.2 -Dhttp.proxyPort=3128 UCDemo

Lab Session: 8 HTTP Download


8b. Implementation of File Transfer Protocol
Aim:

 To create file transfer protocol for transferring file form one location to
another.

System and Software Requirements:

 PC with Windows XX Operating systems.


 JAVA Interpretter

Theory

101
File Transfer Protocol (FTP), a standard Internet protocol, is the simplest way to
exchange files between computers on the Internet. Like the Hypertext Transfer Protocol
(HTTP), which transfers displayable Web pages and related files, and the Simple Mail
Transfer Protocol (SMTP), which transfers e-mail, FTP is an application protocol that
uses the Internet's TCP/IP protocols. FTP is commonly used to transfer Web page files
from their creator to the computer that acts as their server for everyone on the Internet.
It's also commonly used to download programs and other files to your computer from
other servers.

As a user, you can use FTP with a simple command line interface (for example,
from the Windows MS-DOS Prompt window) or with a commercial program that offers a
graphical user interface. Your Web browser can also make FTP requests to download
programs you select from a Web page. Using FTP, you can also update (delete, rename,
move, and copy) files at a server. You need to logon to an FTP server. However, publicly
available files are easily accessed using anonymous FTP.

Basic FTP support is usually provided as part of a suite of programs that come
with TCP/IP. However, any FTP client program with a graphical user interface usually
must be downloaded from the company that makes it.

Algorithms
Client:

• Start the program


• Include necessary packages such as java.net.*, java.io.*, java.lan.Object,
java.util.*
• Create a client socket
• Get the local host address.
• Create the file in write mode
• Read content from the network pipe.
• Write the content to the opened file.
• End the program.

Server:

• Start the program


• Include necessary packages such as java.net.*, java.io.*, java.lan.Object,
java.util.*
• Create a Server socket
• Get the local host address.
• Create the file in Read mode
• Write the content to the network pipe.
• Sent to the Client.

102
• End the program.

Program
FTP Client
import java.io.*;
import java.net.*;
public class ftpclient
{
public static void main(String args[]) throws Exception
{
Socket s=new Socket(InetAddress.getLocalHost(),8000);
FileOutputStream fout= new FileOutputStream(args[0]);
InputStreamReader sin=new InputStreamReader(s.getInputStream());
int i;
while(true)
{
i=sin.read();
if(i==-1|| i==63)
break;
fout.write(i);
}
s.close();
fout.close();
System.out.println("File received successful");
}
}
FTP Server
import java.io.*;
import java.net.*;
public class ftpserver
{
public static void main(String args[]) throws Exception
{
ServerSocket ss=new ServerSocket(8000);
Socket s=ss.accept();
FileInputStream fin= new FileInputStream(args[0]);
OutputStreamWriter out=new OutputStreamWriter(s.getOutputStream());
int i;
while(true)
{
i=fin.read();
out.write(i);
out.flush();
if(i==-1)
break;
}

103
s.close();
fin.close();
System.out.println("File sent successful");
}
}
How to Run the Server Program
E:\j2sdk1.4.0\bin\ >javac FTPServer.java
E:\j2sdk1.4.0\bin\ >javac FTPCleint.java
E:\j2sdk1.4.0\bin\ >java FTPServer
E:\j2sdk1.4.0\bin\ >java FTPClient

References:

1. http://www.opengroup.org/onlinepubs/000095399/functions/htonl.html

2. www.mkssoftware.com/docs

104