Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
• Dr.S.Radhakrishnan., HoD/CSE
• Mr.M.Gomathy Nayagam
• Ms.D.Kavitha
• Mr.B.Barnidharan
• Ms.M.Chitra
Introduction
• While entering the Lab, the students should sign in the student login register.
• Use the allotted system and login as per the instruction only.
• While leaving the lab arrange the chairs you were sittings in the proper way.
2
• Don’t use other’s logins.
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:
4
directory
cd dirname
Connects to the directory named dirname.
5
mv file(1) file(2)... file(n) directory
mv olddir newdir
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.
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.
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}
SYNTAX
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:
EXAMPLES
netstat - displays generic net statistics of the host you are currently connected to.
2. ping
9
ABOUT PING
SYNTAX
ping -s [-d] [-l] [-L] [-n] [-r] [-R] [-v] [ -i interface_address ] [-I interval] [-t ttl] host
[packetsize] [count]
EXAMPLES
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
SYNTAX
telnet [-8] [-E] [-L] [-c] [-d] [-r] [ -e escape_char ] [ -l user ] [-n file ] [ host [ port ] ]
11
EXAMPLES
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
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
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]
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
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
Aim:
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.
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.
• 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.
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”);
}
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”);
}
}
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:
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.
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.
EFAULT - name is an invalid pointer or the namelen parameter is too small (less than the size of a struct
sockaddr).
ENETDOWN - The Windows sockets implementation has detected that the network subsystem has failed.
ENOBUFS - Not enough buffers are available; there are too many connections.
Algorithms
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:
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);
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:
[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.
[EACCES] - The calling process does not have the appropriate privileges.
[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:
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.
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 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.
The socket in use may require the process to have appropriate privileges to
use the listen() function.
RETURN VALUE
ERRORS
[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().
[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()).
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.
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
[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.
[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.
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.
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
[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.
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()
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
[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.
[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.
These functions shall convert 16-bit and 32-bit quantities between network byte
order and host byte order.
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;
}
45
Output of the Client Program
Client program
Socket created
Socket descriptor value:3
Connected to the server
Message is received
Aim:
To Transfer the file between client and server using Transmission Control
Protocol.
Theory
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()
SYNOPSIS
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
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
O_WRONLY
O_RDWR
Open for reading and writing. The result is undefined if this flag is applied
to a FIFO.
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
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
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.
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
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.
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
[EACCES]
[EEXIST]
O_CREAT and O_EXCL are set, and the named file exists.
[EINTR]
[EINVAL]
The implementation does not support synchronised I/O for this file.
[EIO]
[EISDIR]
[ELOOP]
[EMFILE]
[ENAMETOOLONG]
51
[ENFILE]
[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]
[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]
[ENXIO]
[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]
52
[EAGAIN]
The path argument names the slave side of a pseudo-terminal device that
is locked.
[EINVAL]
[ENAMETOOLONG]
[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()
SYNOPSIS
#include <unistd.h>
#include <sys/uio.h>
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.
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 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:
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.
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.
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 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 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
ERRORS
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]
[EIO]
[EIO]
[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.
[EINVAL]
[ENXIO]
[EINVAL]
The pread() function will fail, and the file pointer remains unchanged, if:
[EINVAL]
[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]
[ESPIPE]
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].
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.
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 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 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.
[EINVAL]
The sum of the iov_len values in the iov array would overflow an ssize_t.
[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.
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);
}
}
}
}
67
Message is received
Aim:
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.
69
This section describes the key components of the DNS and defines key DNS
terms.
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:
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.
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.
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
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.
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.
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.
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 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.
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.
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
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;
}
79
Lab Session: 7 Getting MAC Address
7.a Mapping Logical Addressing to Physical Addressing
Aim:
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.
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
Format of an arp message used to resolve the remote MAC Hardware Address (HA)
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.
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
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.
Class-BufferedReader
java.lang.Object
java.io.Reader
java.io.BufferedReader
Direct Known Subclasses:
LineNumberReader
84
The buffer size may be specified, or the default size may be used. The default is
large enough for most purposes.
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.
Class- InputStreamReader
java.lang.Object
java.io.Reader
java.io.InputStreamReader
Direct Known Subclasses:
FileReader
public class InputStreamReader
extends Reader
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.
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:
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:
this
is
a
test
Algorithms
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>
Aim:
88
System and Software Requirements:
Theory
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
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:
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
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.
For IPv4 address format, please refer to Inet4Address#format; For IPv6 address
format, please refer to Inet6Address#format.
Reverse name resolution means that for any IP address, the host associated with
the IP address is returned.
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.
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.
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.
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
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
Aim:
Theory
95
Refer chapter- 2
Algorithms
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");
}
}
}
}
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
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
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(String absoluteURL)
• URL(URL baseURL, String relativeURL)
98
• These constructor are useful when working with hostname, filename, port number
and references
4. MalformedURLException
5. Parsing a 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);
}
• 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
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
To create file transfer protocol for transferring file form one location to
another.
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:
Server:
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