You are on page 1of 125

1.

Understanding and using the Following Commands


ARP COMMAND:
arp - manipulate the system ARP cache
arp [-evn] [-H type] [-i if] -a [hostname]
arp [-v] [-i if] -d hostname [pub]
arp [-v] [-H type] [-i if] -s hostname hw_addr [temp]
arp [-v] [-H type] [-i if] -s hostname hw_addr [netmask nm] pub
arp [-v] [-H type] [-i if] -Ds hostname ifa [netmask nm] pub
arp [-vnD] [-H type] [-i if] -f [filename]

DESCRIPTION
Arp manipulates the kernel’s ARP cache in various ways. The primary options are
clearing an address mapping entry and manually setting up one. For debugging purposes,
the arp program also allows a complete dump of the ARP cache.
OPTIONS:
-v, --verbose
Tell the user what is going on by being verbose.
-n, --numeric
Shows numerical addresses instead of trying to determine symbolic host, port or
user names.
-H type, --hw-type type, -t type
When setting or reading the ARP cache, this optional parameter tells arp which
class of entries it should check for. The default value of this parameter is ether (i.e.
hardware code 0x01 for IEEE 802.3 10Mbps Ethernet). Other values might include
network technologies such as ARCnet (arc net) , PROnet (pronet) , AX.25 (ax25) and
NET/ROM(netrom).
-a [hostname], --display [hostname]
Shows the entries of the specified hosts. If the hostname parameter is not used,
all entries will be displayed. The entries will be displayed in alternate (BSD) style.
-d hostname, --delete hostname

1
Remove any entry for the specified host. This can be used if the indicated host is brought
down, for example:
-D, --use-device
Use the interface ifa's hardware address.
-e Shows the entries in default (Linux) style.
-i If, --device If
Select an interface. When dumping the ARP cache only entries matching the
specified interface will be printed. When setting a permanent or temp ARP entry
this interface will be associated with the entry; if this option is not used, the kernel will
guess based on the routing table. For pub entries the specified interface is the interface on
which ARP requests will be answered.
NOTE: This has to be different from the interface to which the IP datagrams will be
routed.
-s hostname hw_addr, --set hostname
Manually create an ARP address mapping entry for host hostname with hardware
address set to hw_addr class, but for most classes one can assume that the usual
presentation can be used. For the Ethernet class, this is 6 bytes in hexadecimal,
separated by colons. When adding proxy arp entries (that is those with the publish flag
set a netmask may be specified to proxy arp for entire subnets. This is not good
practice, but is supported by older kernels because it can be useful. If the temp flag is not
supplied entries will be permanent stored into the ARP cache.
NOTE: As of kernel 2.2.0 it is no longer possible to set an ARP entry for an entire
subnet. Linux instead does automatic proxy arp when a route exists and it is
forwarding.
-f filename, --file filename
Similar to the -s option, only this time the address info is taken from file filename
set up. The name of the data file is very often /etc/ethers, but this is not official. If no
filename is specified /etc/ethers is used as default.
The format of the file is simple; it only contains ASCII text lines with a hostname, and a
hardware address separated by white space. Additionally the pub, temp and net mask

2
flags can be used. In all places where a hostname is expected, one can also enter an IP
address in dotted-decimal notation.

As a special case for compatibility the order of the hostname and the hardware address
can be exchanged.Each complete entry in the ARP cache will be marked with the C
flag. Permanent entries are marked with M and published entries have the P flag.
TELNET:
telnet - user interface to the TELNET protocol
telnet [-8EFKLacdfrx] [-X authtype] [-b hostalias] [-e escapechar]
[-k realm] [-l user] [-n tracefile] [host [port]]
DESCRIPTION:
The telnet command is used to communicate with another host using the TELNET
protocol. If telnet is invoked without the host argument, it enters command mode,
indicated by its prompt (telnet>). In this mode, it accepts and executes the commands
listed below. If it is invoked with arguments, it performs an open command with those
arguments.
OPTIONS:
-8 Specifies an 8-bit data path. This causes an attempt to negoti¡
ate the TELNET BINARY option on both input and output.
-E Stops any character from being recognized as an escape character.
-F If Kerberos V5 authentication is being used, the -F option allows
the local credentials to be forwarded to the remote system,including any credentials that
have already been forwarded into the local environment.
-K Specifies no automatic login to the remote system.
-L Specifies an 8-bit data path on output. This causes the BINARY
option to be negotiated on output.
-X atype
Disables the atype type of authentication.
-a Attempt automatic login. Currently, this sends the user name via
the USER variable of the ENVIRON option if supported by the remote system. The
name used is that of the current user as returned by getlogin(2) if it agrees with the
current user ID, otherwise it is the name associated with the user ID.

3
-b hostalias
Uses bind(2) on the local socket to bind it to an aliased address (see ifconfig(8) and the
``alias'' specifier) or to the address of another interface than the one naturally chosen by
connect(2).
This can be useful when connecting to services which use IP addresses for authentication
and reconfiguration of the server is undesirable (or impossible).
-c Disables the reading of the user's .telnetrc file.
-d Sets the initial value of the debug toggle to TRUE.
-e escapechar
Sets the initial telnet escape character to escape char. If escape char is omitted,
then there will be no escape character.
-f If Kerberos V5 authentication is being used, the -f option allows
the local credentials to be forwarded to the remote system.
-k realm
If Kerberos authentication is being used, the -k option requests
that telnet obtain tickets for the remote host in realm instead of the remote host's realm, as
determined by krb_realmofhost(3).
FTP
ftp - Internet file transfer program
ftp [-pinegvd] [host]
pftp [-inegvd] [host]

DESCRIPTION:-
Ftp is the user interface to the Internet standard File Transfer Protocol. The program
allows a user to transfer files to and from a remote network site.options may be specified
at the command line, or to the command interpreter.
OPTIONS:
-p Use passive mode for data transfers. Allows use of ftp in environments where a
firewall prevents connections from the outside world back to the client machine. Requires
that the ftp server support the PASV command. This is the default now for all clients (ftp

4
and pftp) due to security concerns using the PORT transfer mode. The flag is kept for
compatibility only and has no effect anymore.
-i turn off interactive prompting during multiple file transfers.
-n Restrains ftp from attempting ``auto-login'' upon initial connection. If auto-login
is enabled, ftp will check the .netrc (see netrc(5)) file in the user's home directory for an
entry describing an account on the remote machine. If no entry exists, ftp will prompt for
the remote machine login name (default is the user identity on the local machine), and, if
necessary, prompt for a password and an account with which to login.
-e Disables command editing and history support, if it was compiled into the ftp
executable. Otherwise, does nothing.
-g Disables file name globbing.
-v Verbose option forces ftp to show all responses from the remote
server, as well as report on data transfer statistics.
-d Enables debugging.
The client host with which ftp is to communicate may be specified on the command
line. If this is done, ftp will immediately attempt to establish a connection to an FTP
server on that host; otherwise, ftp will enter its command interpreter and await
instructions from the user. When ftp is awaiting commands from the user the prompt
`ftp>' is provided to the user. The following commands are recognized by ftp:
[Command [args]]
Invoke an interactive shell on the local machine. If there are arguments, the first is taken
to be a command to execute directly, with the rest of the arguments as its arguments.

$ macro-name [args]
Execute the macro macro-name that was defined with the macdef command. arguments
are passed to the macro un globbed.
account [passwd]
Supply a supplemental password required by a remote system for access to resources
once a login has been successfully completed. If no argument is included, the user will
be prompted for an account password in a non-echoing input mode.
append local-file [remote-file]

5
Append a local file to a file on the remote machine.If remote-file is left unspecified, the
local file name is used in naming the remote file after being altered by any ntrans or
nmap setting. File transfer uses the current settings for type, format, mode, and structure
NETSAT:
netstat command netstat displays the contents of various network-related data structures
in various formats, depending on the options you select.
The first form of the command displays a list of active sockets for each protocol. The
second form selects one from among various other network data structures. The third
form shows the state of the interfaces. The fourth form displays the routing table, the fifth
form displays the multicast routing table, and the sixth form displays the state of DHCP
on one or all interfaces.
SYNOPSIS
Shows network status.
SYNTAX:-
netstat [-a] [-n] [-v]
netstat [-g | -m | -p | -s | -f address_family ] [-n] [-P protocol]
netstat [ -i ] [ -I interface ] [ interval ]
netstat -r [-a] [-n] [-v ]
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.

6
-p Show the address resolution (ARP) tables.
-s Show per-protocol statistics. When used with the -M option, show
multicast routing statistics instead.
-i Show the state of the interfaces that are used for TCP/IP traffic.
-r Show the routing tables.
-M Show the multicast routing tables. When used with the -s option,
show multicast routing statistics instead.
-d Show the state of all interfaces that are under Dynamic Host
Configuration Protocol (DHCP) control.
-D Show the status of DHCP configured interfaces.
-f address_family imit statistics or address control block reports to those of the
specified address_family, which can be one of:
inet For the AF_INET address family
unix For the AF_UNIX address family
-P protocol Limit display of statistics or state of all sockets to those applicable
to protocol.
- I interface Show the state of a particular interface. interface can be any valid
interface such as ie0 or
le0.
Ping: ping6- send ICMP ECHO_REQUEST to network hosts

SYNOPSIS

ping [-LRUbdfnqrvVaAB] [-c count] [-m mark] [-i interval] [-l preload]

[-p pattern] [-s packetsize] [-t ttl] [-w deadline] [-F flowlabel] [-I

interface] [-M hint] [-N nioption] [-Q tos] [-S sndbuf] [-T timestamp

option] [-W timeout] [hop ...] destination

DESCRIPTION

ping uses the ICMP protocol's mandatory ECHO_REQUEST datagram to elicit

7
an ICMP ECHO_RESPONSE from a host or gateway. ECHO_REQUEST
datagrams (``pings'') have an IP and ICMP header, followed by a struct timeval
and then an arbitrary number of ``pad'' bytes used to fill out the packet.
ping6 can also send Node Information Queries (RFC4620).

OPTIONS

-a Audible ping.

-A Adaptive ping. Interpacket interval adapts to round-trip time, so that


effectively not more than one (or more, if preload is set) unanswered probes present in
the network. Minimal interval is 200msec for not super-user. On networks with low rtt
this mode is essentially equivalent to flood mode.

-b Allow pinging a broadcast address.

-B Do not allow ping to change source address of probes. The address is


bound to one selected when ping starts.

-m mark

use mark to tag the packets going out. This is useful for variety of reasons
within the kernel such as using policy routing to select specific outbound processing.

-c count

Stop after sending count ECHO_REQUEST packets. With deadline


option, ping waits for count ECHO_REPLY packets, until the timeout
expires.

-d Set the SO_DEBUG option on the socket being used. Essentially,


this socket option is not used by Linux kernel.

-F flow label
Allocate and set 20 bit flow label on echo request packets.
(Only ping6). If value is zero, kernel allocates random flow
label.

-f Flood ping. For every ECHO_REQUEST sent a period ``.'' is printed, while
for ever ECHO_REPLY received a backspace isp printed. This provides a rapid
display of how many packets are being dropped. If interval is not given, it sets interval
to zero and outputs  packets as fast as they come back or one hundred times per
second, whichever is more. Only the super-user may use this option with zero interval.

8
-i interval
Wait interval seconds between sending each packet. The default is to wait for
one second between each packet normally, or not to wait in flood mode. Only super-user
may set interval to values less 0.2 seconds.

-I interface address
Set source address to specified interface address. Argument may be numeric IP
address or name of device. When pinging IPv6 link-local address this option is required.

-l preload

If preload is specified, ping sends that many packets not waiting for reply.
Only the super-user may select preload more than 3.

-L Suppress loopback of multicast packets. This flag only applies

if the ping destination is a multicast address.

When using ping for fault isolation, it should first be run on the local host, to verify
that the local network interface is up and running. Then, hosts and gateways further and
further away should be ``pinged''. Round-trip times and packet loss statistics are
computed. If duplicate packets are received, they are not included in the packet loss
calculation, although the round trip time of these packets is used
In calculating the minimum/average/maximum round-trip time numbers.

When the specified number of packets have been sent (and received) or if the program is
terminated with a SIGINT, a brief summary is displayed. Shorter current statistics can be
obtained without termination of process with signal SIGQUIT.

If ping does not receive any reply packets at all it will exit with code 1. If a packet
count and deadline are both specified, and fewer than count packets are received by
the time the deadline has arrived, it will also exit with code 1. On other error it exits
with code 2. Otherwise it exits with code 0. This makes it possible to use the exit code
to see if a host is alive or not. This program is intended for use in network testing,
measurement and management. Because of the load it can impose on the network, it is
unwise to use ping during normal operations or from automated scripts.

ICMP PACKET DETAILS

9
An IP header without options is 20 bytes. An ICMP ECHO_REQUEST packet
contains an additional 8 bytes worth of ICMP header followed by an arbitrary amount
of data. When a packetsize is given, this indicated the size of this extra piece of data
(the default is 56). Thus the amount of data received inside of an IP packet of type ICMP
ECHO_REPLY will always be 8 bytes more than the requested data space (the ICMP
header).

If the data space is at least of size of struct timeval ping uses the beginning bytes of this
space to include a timestamp which it uses in the computation of round trip times. If the
data space is shorter, no round trip times are given.

ifconfig - configure a network interface


SYNOPSIS
ifconfig [-v] [-a] [-s] [interface]
ifconfig [-v] interface [aftype] options | address ...
DESCRIPTION
Ifconfig is used to configure the kernel-resident network interfaces. It is
used at boot time to set up interfaces as necessary. After that, it is usually only
needed when debugging or when system tuning is needed. If no arguments are
given, ifconfig displays the status of the currently active interfaces. If a single
interface argument is given, it displays the status of the given interface only; if a
single -a argument is given, it displays the status of all interfaces, even those that
are down. Otherwise, it configures an interface.

Address Families

If the first argument after the interface name is recognized as the name of a supported
address family, that address family is used

for decoding and displaying all protocol addresses. Currently supported address
families include inet (TCP/IP, default), inet6

(IPv6), ax25 (AMPR Packet Radio), ddp (Appletalk Phase 2), ipx (Novell IPX) and
netrom (AMPR Packet radio).

OPTIONS

10
-a display all interfaces which are currently available, even if down

-s display a short list (like netstat -i)

-v be more verbose for some error conditions

interface

The name of the interface. This is usually a driver name followed by a unit
number, for example eth0 for the first Ethernet interface. If your kernel supports alias
interfaces, you can specify them with eth0:0 for the first alias of eth0. You can use them
to assign a second address. To delete an alias interface use ifconfig eth0:0 down. Note:
for every scope (i.e. same net with address/netmask combination) all aliases are deleted,
if you delete the first (primary).

Up This flag causes the interface to be activated. It is implicitly specified if an


address is assigned to the interface.

Down This flag causes the driver for this interface to be shut down.

[-]arp Enable or disable the use of the ARP protocol on this interface.

[-] promisc

Enable or disable the promiscuous mode of the interface. If selected, all


packets on the network will be received by the interface.

[-] allmulti

Enable or disable all-multicast mode. If selected, all multicast packets on the


network will be received by the interface.

netmask addr

Set the IP network mask for this interface. This value defaults to the usual class
A, B or C network mask (as derived from the interface IP address), but it can be set to
any value.

add addr/prefixlen
Add an IPv6 address to an interface.

Del addr/prefixlen
Remove an IPv6 address from an interface.

io_addr addr

11
Set the start address in I/O space for this device.

mem_start addr
Set the start address for shared memory used by this device. Only a few devices
need this.

media type
Set the physical port or medium type to be used by the device. Not all devices
can change this setting, and those that can

Vary in what values they support. Typical values for type are 10base2 (thin
Ethernet), 10baseT (twisted-pair 10Mbps Ether net), AUI (external transceiver) and so
on. The special medium type of auto can be used to tell the driver to auto-sense the
media. Again, not all drivers can do this.

[-]broadcast [addr]

If the address argument is given, set the protocol broadcast address for this
interface. Otherwise, set (or clear) the IFF_BROADCAST flag for the interface.

[-]pointopoint [addr]

This keyword enables the point-to-point mode of an interface, meaning that it is


a direct link between two machines with nobody else listening on it.

If the address argument is also given, set the protocol address of the other side of
the link, just like the obsolete dstaddr

Keyword does. Otherwise, set or clear the IFF_POINTOPOINT flag for the
interface.

hw class address

Set the hardware address of this interface, if the device driver supports this
operation. The keyword must be followed by the name of the hardware class and the
printable ASCII equivalent of the hardware address. Hardware classes currently
supported include ether (Ethernet), ax25 (AMPR AX.25), ARCnet and netrom (AMPR
NET/ROM).

multicast

Set the multicast flag on the interface. This should not normally be needed as the
drivers set the flag correctly themselves.

address

12
The IP address to be assigned to this interface.

txqueuelen length

Set the length of the transmit queue of the device. It is useful to set this to small
values for slower devices with a high

latency (modem links, ISDN) to prevent fast bulk transfers from disturbing
interactive traffic like telnet too much.

NS LOOKUP
nslookup, which stands for "name server lookup", is a useful tool for finding out inform-
ation about a named domain.
By default, nslookup will translate a domain name to an IP address (or vice versa).
nslookup syntax

nslookup [-option] [name | -] [server]

nslookup microsoft.com

Server: 8.8.8.8

Address: 8.8.8.8#53

Non-authoritative answer:

Name: microsoft.com

Address: 134.170.185.46

Name: microsoft.com

Address: 134.170.188.221

13
Here, 8.8.8.8 is the address of our system's Domain Name Server. This is the server our
system is configured to use to translate domain names into IP addresses. "#53" indicates
that we are communicating with it on port 53, which is the standard port number domain
name servers use to accept queries.
Below this, we have our lookup information for microsoft.com. Our name server re-
turned two entries, 134.170.185.46 and 134.170.188.221. This indicates that microsoft.-
com uses a round robin setup to distribute server load. When you access micrsoft.com,
you may be directed to either of these servers and your packets will be routed to the cor-
rect destination.

Dig (Command)

dig (domain information groper) is a network administration command-line tool for


querying Domain Name System (DNS) servers.
dig is useful for network troubleshooting and for educational purposes. dig can operate in
interactive command line mode or in batch mode by reading requests from an operating
system file. When a specific name server is not specified in the command invocation, it
will use the operating systems default resolver, usually configured via
the resolv.conf file. Without any arguments it queries the DNS root zone.
dig supports Internationalized Domain Name (IDN) queries.
dig is part of the BIND domain name server software suite. dig was initially planned to
supersede older tools such as nslookup and the host program; however, it instead became
a complementary tool.
root@balaji ~]# dig google.com

; <<>> DiG 9.9.4-RedHat-9.9.4-29.el7_2.3 <<>> google.com


;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 32702
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; MBZ: 0005 , udp: 4000
;; QUESTION SECTION:
;google.com. IN A

;; ANSWER SECTION:
google.com. 5 IN A 216.58.220.110

14
;; Query time: 27 msec
;; SERVER: 192.168.220.2#53(192.168.220.2)
;; WHEN: Tue Sep 06 09:13:28 AEST 2016
;; MSG SIZE rcvd: 55

2. Study of Network Simulator NS2/NS3.

15
ns (from network simulator) is a name for a series of discrete event network simulators,
specifically ns-1, ns-2 and ns-3. All of them are discrete-event computer network
simulators, primarily used in research[4] and teaching. ns-3 is free software, publicly
available under the GNU GPLv2 license for research, development, and use.
The goal of the ns-3 project is to create an open simulation environment for computer
networking research that will be preferred inside the research community. It should be
aligned with the simulation needs of modern networking research.

 It should encourage community contribution, peer review, and validation of the


software.

Since the process of creation of a network simulator that contains a sufficient number of
high-quality validated, tested and actively maintained models requires a lot of work, ns-3
project spreads this workload over a large community of users and developers.
History
ns-1
The first version of ns, known as ns-1, was developed at Lawrence Berkeley National
Laboratory (LBNL) in the 1995-97 timeframe by Steve McCanne, Sally Floyd, Kevin
Fall, and other contributors. This was known as the LBNL Network Simulator, and
derived from an earlier simulator known as REAL by S. Keshav.
ns-2
Ns began as a variant of the REAL network simulator in 1989 and has evolved
substantially over the past few years. In 1995 ns development was supported by DARPA
through the VINT project at LBL, Xerox PARC, UCB, and USC/ISI. Currently ns
development is support through DARPA with SAMAN and through NSF with CONSER,
both in collaboration with other researchers including ACIRI. Ns has always included
substantial contributionswireless code from the UCB Daedelus and CMU Monarch
projects and Sun Microsystems. For documentation on recent changes, see the version 2
change log.
ns-3
A team led by Tom Henderson, George Riley, Sally Floyd, and Sumit Roy, applied for
and received funding from the U.S. National Science Foundation (NSF) to build a
replacement for ns-2, called ns-3. This team collaborated with the Planete project
of INRIA at Sophia Antipolis, with Mathieu Lacage as the software lead, and formed a
new open source project.
In the process of developing ns-3, it was decided to completely abandon backward-
compatibility with ns-2. The new simulator would be written from scratch, using the C+
+ programming language. Development of ns-3 began in July 2006.
The first release, ns-3.1 was made in June 2008, and afterwards the project continued
making quarterly software releases, and more recently has moved to three releases per
year. ns-3 made its twenty first release (ns-3.21) in September 2014.
Current status of the three versions is:

16
 ns-1 is no longer developed nor maintained,
 ns-2 is not actively maintained (active development stopped in 2010 and is not
accepted for publications anymore)
 ns-3 is actively developed (but not compatible for work done on ns-2).

Design

ns-3 is built using C++ and Python with scripting capability. The ns-3 library is wrapped


by Python thanks to the pybindgen library which delegates the parsing of the ns-3 C++
headers to gccxml and pygccxml to automatically generate the corresponding C++
binding glue. These automatically-generated C++ files are finally compiled into the ns-3
Python module to allow users to interact with the C++ ns-3 models and core through
Python scripts. The ns-3 simulator features an integrated attribute-based system to
manage default and per-instance values for simulation parameters.

Simulation workflow

The general process of creating a simulation can be divided into several steps:

1. Topology definition: To ease the creation of basic facilities and define their inter-
relationships, ns-3 has a system of containers and helpers that facilitates this
process.
2. Model development: Models are added to simulation (for example, UDP, IPv4,
point-to-point devices and links, applications); most of the time this is done using
helpers.
3. Node and link configuration: models set their default values (for example, the size
of packets sent by an application or MTU of a point-to-point link); most of the
time this is done using the attribute system.
4. Execution: Simulation facilities generate events, data requested by the user is
logged.
5. Performance analysis: After the simulation is finished and data is available as a
time-stamped event trace. This data can then be statistically analysed with tools
like R to draw conclusions.
6. Graphical Visualization: Raw or processed data collected in a simulation can be
graphed using tools like Gnuplot, matplotlib or XGRAPH.

17
18
Inter process communication using Sockets:
A socket is one end of an inter process communication channel, the two processes each
can establish their own socket.
The following steps are involved in establishing a socket on the server side is as follows:
1. Create a socket with socket () system call.
2. Bind the socket to an address using bind () system call. For a server socket on the
internet an address consists of a port number on the host machine.
3. Listen for connection with the listen () system call.
4. Accept a connection with the accept () system call. This call typically blocks until
a client connects with the server.
5. Send and receive data.

The following steps are involved in establishing a socket on the client side is as follows:
1. Create a socket with socket () system call.
2. Connect the socket to the address of the server using the connect () system
call.
3. Send and receive data. There are number of ways to do this, but the simplest is
to use the read () and write () system call.
In the client – server design, server is considered as echo server, is the program that
reads a character string sent by a client program and returns the same to the client. There
are 2 ways to implement the above they are:

1. Connection –oriented (TCP) concurrent server and iterative server.


2. Connection less (UDP) concurrent server and iterative server.

SOCKET SYSTEM CALLS:


#includes<stdio.h>:
This header file contains declaration used in most input and output functions and is
typically included in all c programs.

19
#includes<sys/types.h>:
This header file contains definitions of a number of data types used in system calls .these
types are used in the next two include files.

#includes<sys/socket.h>:
This header file includes a number of definitions of structures needed for sockets.

#includes<netinet/in.h>:
This header file contains constants and structures needed for internet domain address
SOCKET: socket - create an endpoint for communication
#include <sys/types.h>
#include <sys/socket.h>

int socket (int family, int type, int protocol);

DESCRIPTION:
Socket creates an endpoint for communication and returns a descriptor. The domain
parameter specifies a communication domain; this selects the protocol family which
will be used for communication. These families are defined in <sys/socket.h>. The
currently understood formats include:
Name Purpose
PF_UNIX, PF_LOCAL Unix domain protocols
PF_INET IPv4 Internet protocols
PF_INET6 IPv6 Internet protocols
PF_IPX IPX - Novell protocols
PF_ROUTE Routing sockets
PF_KEY Key sockets

The socket has the indicated type, which specifies the communication semantics.
Currently defined types are:

20
SOCK_STREAM:
Provides sequenced, reliable, two-way, connection- based byte streams. An out-of-band
data transmission mechanism may be supported.
SOCK_DGRAM:
Supports data grams (connectionless, unreliable messages of a fixed maximum length).
SOCK_SEQPACKET:
Provides a sequenced, reliable, two-way connection- based data transmission path for
data grams of fixed maximum length; a consumer is required to read an entire packet
with each read system call.
SOCK_RAW:
Provides raw network protocol access.
SOCK_RDM:
Provides a reliable datagram layer that does not guarantee ordering.
SOCK_PACKET:
Obsolete and should not be used in new programs; Some socket types may not be
implemented by all protocol families; for example, SOCK_SEQPACKET is not
implemented for AF_INET.
The protocol specifies a particular protocol to be used with the socket. Normally only
a single protocol exists to support a particular socket type within a given protocol
family. However, it is possible that many protocols may exist, in which case a
particular protocol must be in this manner. The protocol number to use is specific to the
"communication domain" in which communication is to take place.
Sockets of type SOCK_STREAM are full-duplex byte streams,

Similar to pipes. They do not preserve record boundaries. A stream socket must be in a
connected state before any data may be sent or received on it. A connection to
Another socket is created with a connect call. Once connected, data may be transferred
using read and write calls or some variant of the send and recv calls.

When a session has been completed a close may be performed. Out-of-band data may
also be transmitted as described in send and received as described in recv.

21
The communications protocols which implement a SOCK_STREAM ensure that data is
not lost or duplicated. If a piece of data for which the peer protocol has buffer space
cannot be successfully transmitted within a reasonable length of time, then the
connection is considered to be dead. When SO_KEEPALIVE is enabled on the socket
the protocol checks in a protocol-specific manner if the other end is still alive.
A SIGPIPE signal is raised if a process sends or receives on a broken stream; this
causes naive processes, which do not handle the signal, to exit. SOCK_SEQPACKET
sockets employ the same system calls as SOCK_STREAM sockets. The only
difference is that read calls will return only the amount of data requested, and any
remaining in the arriving packet will be discarded. Also all message boundaries in
incoming data grams are preserved.

SOCK_DGRAM and SOCK_RAW sockets allow sending of data grams to


correspondents named in send calls. Data grams are generally received with recvfrom,
which returns the next datagram with its return address.
SOCK_PACKET is an obsolete socket type to receive raw packets directly from the
device driver. Use packet instead.
When the network signals an error condition to the protocol
module (e.g. using a ICMP message for IP) the pending error flag is set for the socket.
The next operation on this socket will return the error code of the pending error. For
some protocols it is possible to enable a per-socket error queue to retrieve detailed
information about the error; see IP_RECVERR in ip.
The operation of sockets is controlled by socket level options. These options are
defined in <sys/socket.h>.Setsockopt and getsockopt are used to set and getoptions,
respectively.

RETURN VALUE
-1 is returned if an error occurs; otherwise the return value is a descriptor referencing
the socket.

22
RECV:
#include <sys/types.h>
#include <sys/socket.h>

int recv(int sockfd, void *buf, size_t len, int flags);

DESCRIPTION:-
The recv function is used to receive messages (similar to read) from a socket, whether
or not it is connection-oriented. If from is not NULL, and the socket is not connection-
oriented, the source address of the message is filled in the argument from len is a
value-result parameter, initialized to the size of the buffer associated with from, and
modified on return to indicate the actual size of the address stored there.
The recv call is normally used only on a connected socket .All three routines return the
length of the message on successful completion. If a message is too long to fit in the
supplied buffer, excess bytes may be discarded depending on the type of socket the
message is received from socket when more data arrives.
The flags argument to a recv call is formed by OR'ing one or more of the following
values:
RETURN VALUE
The call returns the number of bytes received, or -1 if an error occurred.

SEND: sends a message from a socket


#include <sys/types.h>
#include <sys/socket.h>

int send(int s, const void *msg, size_t len, int flags);

DESCRIPTION:
Send is used to transmit a message to another socket. Send may be used only when the
socket is in a connected state, the address of the target is given by to with tolen
specifying its size. The length of the message is given by len. If the message is

23
too long to pass atomically through the underlying protocol, the error EMSGSIZE is
returned, and the message is not transmitted. No indication of failure to deliver is
implicit in a send. Locally detected errors are indicated by a return value of-1.
When the message does not fit into the send buffer of the socket, send normally blocks,
unless the socket has been placed in non-blocking I/O mode. In non-blocking mode it
would return EAGAIN in this case. The select call may be used to determine when
it is possible to send more data.
RETURN VALUE:
The call returns the number of characters sent, or -1 if an error occurred.

CONNECT:
connect - initiate a connection on a socket
#include <sys/types.h>
#include <sys/socket.h>

int connect(int sockfd, const struct sockaddr *serv_addr,socklen_t addrlen);

DESCRIPTION:
The file descriptor sockfd must refer to a socket. If the socket is of type
SOCK_DGRAM then the serv_addr address isthe address to which datagrams are sent
by default, and the only address from which datagrams are received. If the socket is
of type SOCK_STREAM or SOCK_SEQPACKET, this call attempts to make a
connection to another socket. The other socket is specified by serv_addr, which is
an address (of length addrlen) in the communications space of the socket. Each
communications space interprets the serv_addr parameter in its own way.
Generally, connection-based protocol sockets may successfully connect only once;
connectionless protocol sockets may use connect multiple times to change their
association. Connectionless sockets may dissolve the association by connecting to an
address with the sa_family member of sockaddr set to AF_UNSPEC.

24
RETURN VALUE:
If the connection or binding succeeds, zero is returned.On error, -1 is returned, and
errno is set appropriately.

ERRORS
The following are general socket errors only. There may be other domain-specific
error codes.
EBADF --The file descriptor is not a valid index in the descriptor table.
EFAULT-- The socket structure address is outside the user's address space.

ACCEPT:
accept - accept a connection on a socket
#include <sys/types.h>
#include <sys/socket.h>

int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);

DESCRIPTION:-
The accept function is used with connection-based socket types (SOCK_STREAM,
SOCK_SEQPACKET and SOCK_RDM). It extracts the first connection request on
the queue of pending connections, creates a new connected socket with mostly the
same properties as sockfd, and allocates a new file descriptor for the socket, which is
returned. The newly created socket is no longer in the listening state. The original
socket s is unaffected by this call. Note that any per file descriptor flags (everything that
can be set with the F_SETFL fcntl, like non blocking or async state) are not inherited
across an accept.
The argument addr is a pointer to a sockaddr structure. This structure is filled in with
the address of the connecting entity, as known to the communications layer. The exact
format of the address passed in the addr parameters determined by the socket's family
The addrlen argument is a value-result parameter: it should initially contain the size of

25
the structure pointed to by addr, on return it will contain the actual length (in bytes) of
the address returned. When addr is NULL nothing is filled in.
If no pending connections are present on the queue, and the socket is not
marked as non-blocking, accept blocks the caller until a connection is present. If the
socket is marked non-blocking and no pending connections are present on the queue,
accept returns EAGAIN.In order to be notified of incoming connections on a socket,
you can use select. A readable event will be delivered when a new connection is
attempted and you may then call accept to get a socket for that connection.
Alternatively, you can set the socket to deliver SIGIO when activity occurs on a
socket;There may not always be a connection waiting after a SIGIO is delivered or
select or poll return a readability event because the connection might have been
removed by an asynchronous network error or another thread before accept is called. If
this happens then the call will block waiting for the next connection to arrive. To
ensure that accept never blocks, the passed socket s needs to have the O_NONBLOCK
flag set.

RETURN VALUE
The call returns -1 on error. If it succeeds, it returns a non-negative integer that is a
descriptor for the accepted socket.

BIND: Bind will bind a name to socket


#include <sys/socket.h>

int bind(int sockfd,const struct sockaddr *myaddr,socklen_t addrlen);

it gives the socket sockfd, the local address myaddr, myaddr is addrlen bytes long.
Traditionally, this is called assigning a name to a socket. When a socket is created with
socket () it exists in a name space but has no name assigned.It is normally necessary to
assign local address using bind before sock_stream socket may receive connection.

26
RETURN VALUE:
On sucess0 is return, on error –1 is returned and errno is set to appropriately.

LISTEN:
listen - listen for connections on a socket

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

DESCRIPTION
To accept connections, a socket is first created with socket, a willingness to accept
incoming connections and a queue limit for incoming connections are specified with
listen, and then the connections are accepted with accept. The listen call applies only
to sockets of type SOCK_STREAM or SOCK_SEQPACKET.
The backlog parameter defines the maximum length the queue of pending connections
may grow to. If a connection request arrives with the queue full the client may receive
an error with an indication of ECONNREFUSED or, if the underlying protocol supports
retransmission, the request may be ignored so that retries succeed.

RETURN VALUE:-
On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

ERRORS:-
EADDRINUSE
Another socket is already listening on the same port.
EBADF: The argument s is not a valid descriptor.
ENOTSOCK: The argument s is not a socket.
EOPNOTSUPP: The socket is not of a type that supports the listen operation.

27
SENDTO and RECVFROM : similar to the standard read and write functions with 3
additional arguments .these system calls are used in UDP ,for data transfer between
server and client.
1. ssize_t sendto(int sockfd, const void *buff ,size_t nbytes,int flags, struct
sockaddr *from, socklen_t *addrelen);

2.ssize_t recvfrom(int sockfd, void *buff ,size_t nbytes,int flags,


struct sockaddr *to, socklen_t *addrelen);

3. Implementation of Iterative and Concurrent Echo Server Using


Connection Oriented Protocol (TCP)
3.1 AIM: Program for connection-oriented (TCP) service with server as concurrent
server
REQUIREMENTS:
HARDWARE : Pentium –II (233 Hz)/32MB RAM /3.2 GB HDD
SOFTWARE : Red Hat Linux server v.7.0,c
THEORY:
A connection oriented service requires that the two application programs to establish a
logical connection with each other before communication can take place. This is also
called as virtual circuit because it appears to the application programs that they have
dedicated circuit between them, even though the actual data flow usually takes place on a
switched network. A connection oriented exchange involves:
a) Connection establishment.
b) Data transfer.
c) Connection termination.
The following diagram show a time line of the typical scenario that takes place for
connection oriented transfer, first the server is started, then client is started that connects
to the server.

28
SERVER CLIENT

socket ()

socket ()
bind ()

bind ()

listen ()

connect ()
accept ()

read () write ()

write () read ()

Close()
Close()

Client connects to the server is 2 ways: 1) iterative server 2) concurrent server.


Iterative server: handles each client at a time (i.e) one client at a time.
Concurrent server: handles multiple clients at a time,we use fork() system call to create
a child process for each client .the parent runs the fork system call and creates a child

29
process and assigns each client to it .parent process waits for another connection from the
client .when 2 connection comes from the client another child is created and it is also
assigned a client.

Byte ordering functions:-


Consider a 16 bit integer that is made up of 2 bytes, we can store the 2 bytes in memory
in two types:
1) Lower order byte at the starting address known as little- endian byte order
2) Higher order byte at the starting address known as big-endian byte order.
Increasing memory
addresses

High order byte low order byte


Little-endian byte order

MSB 16 bit value


LSB

Increasing memory
addresses

High order byte low order byte


big-endian byte order

computer network are big endian ,this means that when little endian are going to pass
integers over network(IP address for example) they need to convert them to network byte
order .like wise when the receive integer values over the network they need to convert
them back to their own native representation.

#include<netinet/in.h>:-
a) uint16_t htons(uint16_t host16bitvalue);

30
b) uint32_t htonl(uint32_t host32bitvalue);
Both return: value in network byte order
3. uint16_t ntohs(uint16_t net16bitvalues);
4. uint32_t ntohl(uint32_t net32bitvalues);
Both return: value in host byte order
Byte manipulation functions:
#include< strring.h>
1. void bzero(void *dest , size_t nbytes); sets the specified number of bytes to 0
in destination(often used to initialize socket address structure to 0)
2. void bcopy(const void *src , void *dest ,size_t nbytes); moves the specified
number of bytes from source to the destination .
3. int bcmp(const void *ptr1 ,const void *ptr2 ,size_t nbytes); compares two
arbitrary byte strings are identical or not.

Address conversion function:- they convert internet address between ASCII


strings (human understanding) and network byte binary values .
#include<arpa/inet.h>
1. int inet_aton(const char *strptr,struct in_addr *addrptr );
2. in_addr_t inet _addr(const char * strptr);
3. char *inet_ntoa(struct in_addr inaddr);
all the above convert an IPv4 address from a dotted decimal string(e.g:-
“206.168.112.96”) to its 32 bit network byte ordered binary value .

4. const char *inet_ntop(int family , const void *addrptr , char *strptr , size_t len);
Converts the numeric(addrptr) to presentation (strptr)

SOURCE CODE:
/* server program */
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>

31
#include<strings.h>
#include<netinet/in.h>
#define MAX 1024
main()
{
int sockfd,newsockfd, chilen,childpid,n;
char buff1[MAX];

/*sockaddr_in is predefined structure*/


struct sockaddr_in cli_addr, serv_addr;

/*creating a connection oriented server socket */

if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0)
{
perror("server: cant open stream socket");
}
bzero((char *)&serv_addr,sizeof(serv_addr));
/*initializing the socket with family, port number, ipaddress*/
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=inet_addr ("135.135.4.4");
serv_addr.sin_port=htons (7613);

/*Binding the structure to the server socket*/


if(bind(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr))<0)
{
perror("server:cant bind local address");
exit(1);
}

/*Listen to indicate that it is ready to receive connections*/

32
listen (sockfd,5);
for (;;)
{
chilen=sizeof(cli_addr);
printf("\n server is waiting for connection requests\n");
fflush(stdout);

/*accept takes the first connection request*/

newsockfd=accept(sockfd,(struct sockaddr *)&cli_addr,&chilen);

if(newsockfd<0)
{
perror("\n server accept error\n");
exit(1);
}
printf("\n connection established and communicating with client...");
fflush(stdout);

if((childpid=fork())<0)
{
perror("server: fork error\n");
exit(1);
}

if(childpid==0)
{
close(sockfd);
while(1)
{

33
/*reading a message from client*/

n=read (newsockfd, buff1, MAX);


buff1[n]='\0';
printf("\n server received from client is %s",buff1);
fflush(stdout);

/*sending a message to client */

write(newsockfd,buff1,strlen(buff1));
if(bcmp(buff1,"exit",4))
{
exit(0);
}
}
}
}
close(newsockfd);
}

OUTPUT:

Server:
$ cc tcpser.c
$ ./a.out
Server is waiting for connection requests….
Connection established and communicating with client……..

Message received from client is Hello World.

Message sent to client is Hello World.

34
/* client side program*/
#include<sys/socket.h>
#include<sys/types.h>
#include<strings.h>
#include<stdio.h>
#include<netinet/in.h>

#define MAX 1024

main()
{
int sockfd,n;
char buff1[MAX],buff2[MAX];
/*sockaddr_in is predefined structure*/
struct sockaddr_in serv_addr;
bzero((char *)&serv_addr,sizeof(serv_addr));

/*Initializing the socket with family, port number, ipaddress*/

serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=inet_addr ("135.135.4.4");
serv_addr.sin_port=htons (7613);
/*Creating a connection-oriented client socket*/

if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0)
{
perror("client: socket error \n");
}
/*connect system call to establish a connection with a server*/

35
if(connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr))<0)
{
perror("client: can’t connect to server\n");
exit(1);
}
printf("\n enter the message to be sent\n");
fflush(stdout);

/*Reading a message from Keyboard to buff1*/

if((n=read(0,buff1,MAX+1))<0)
{
perror("error in client ....\n");
exit(1);
}
buff1[n]='\0';
printf("\n message sent to the server: %s",buff1);

/*Sending a message to Server*/

if((n=write(sockfd,buff1,n))<0)
{
perror("error in client……");
}
if((bcmp("exit",buff1,4))==0)
{
printf("\a\a client is exiting.....\n");
exit(1);
}

/*receiving a message from Server*/

36
if((n=read(sockfd,buff2,MAX))<0)
{
perror("error in client.........\n");
exit(1);
}
buff2[n]='\0';
printf("\n received from server \n");
fflush(stdout);
/*Displaying the message on monitor*/

if(write(1,buff2,n)<0)
{
perror("client: written by client on the screen\n");
}
/*Closing the socket*/
close(sockfd);
exit(0);
}
OUTPUT:

Client 1 :
$ cc- tcpcli1.c
$ ./a.out

Enter the message to be sent: Hello World


Message sent to the server: Hello World
Message received from the server: Hello World

Client 2 :
$ cc tcpcli2.c

37
$ ./a.out

Enter the message to be sent: Bye World


Message sent to the server: Bye World
Message received from the server: Bye World

38
3.2 AIM: Program for connection-oriented (TCP) service with server as iterative
server
REQUIREMENTS:
HARDWARE : Pentium –II (233 Hz)/32MB RAM /3.2 GB HDD
SOFTWARE : Red Hat Linux server v.7.0,c

SOURCE CODE:
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
main()
{
int sockfd,newsockfd,n,len;
char buff[512];
/*sockaddr_in is predefined structure*/
struct sockaddr_in ser_addr,cli_addr;

/*Creating a connection-Oriented server socket*/


if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0)
{
perror("socket error\n");
exit(1);
}
/*initializing the socket with family, port number, ipaddress*/
ser_addr.sin_family=AF_INET;
ser_addr.sin_port=htons(8810);
ser_addr.sin_addr.s_addr=htonl(INADDR_ANY);
/*Binding the structure to the server socket*/

39
if(bind(sockfd,(struct sockaddr*)&ser_addr,sizeof(ser_addr))<0)
{
perror("bind error");
exit(1);
}
/*Listen to indicate that it is ready to receive connections*/
listen(sockfd,5);
len=sizeof(cli_addr);
printf("server is waiting for connection ............................\n");
/*accept takes the first connection request*/
if((newsockfd=accept(sockfd,(struct sockaddr*)&cli_addr,&len))<0)
{
perror("accept error");
exit(1);
}
fflush(stdout);
//printf("IP addresss of client %s",inet_ntoa(cli_addr.sin_addr));
//printf("port no. of server is %d", ntohs(ser_addr.sin_port));
printf("server is connected to the client......\n");
fflush(stdout);
/*Reading a message from Client*/
n=read(newsockfd,buff,sizeof(buff));
printf("\n message received from the client :\t %s",buff);
fflush(stdout);
if(bcmp(buff,"exit",4)==0)
{
printf("\n server is closing the connection ………..\n");
exit(1);
}
/*Sending a message to Client*/
write(newsockfd,buff,n);

40
/*Closing the socket*/
close(sockfd);
}

OUTPUT:
Server:
$ cc server.c
$ ./a.out
Server is waiting for connection….
IP address of Client 135.135.4.4
Port No of Server is 8033
Server is connected to the client….
Message received from the client: Hello World

/* client side program*/


#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
main()
{
int sockfd,n;
char buff1[512],buff2[512];
/*sockaddr_in is predefined structure*/
struct sockaddr_in serv_addr;
/*Creating a connection-Oriented client socket*/
if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0)
{
perror("socket error\n");
exit(1);
}

41
/*Initializing the server socket with family, port number,ipaddress*/
serv_addr.sin_family=AF_INET;
serv_addr.sin_port=htons(8810);
serv_addr.sin_addr.s_addr=inet_addr ("135.135.4.4");;
/*connect system call to establish a connection with a server*/
if(connect(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr))<0)
{
perror("connect error");
exit(1);
}
printf("enter the message to be sent \n");
fflush(stdout);
printf("IP addresss of server is %s",inet_ntoa (serv_addr.sin_addr));
/*Reading a message from Keyboard to buff1*/
n=read(0,buff1,sizeof(buff1));
printf("\n message sent to the server :\t %s",buff1);
fflush(stdout);
/*Sending a message to Server*/
write(sockfd,buff1,n);
if(bcmp(buff1,"exit",4)==0)
{
printf("\n client is existing... .\n");
exit(1);
}
/*Receiving a message from Server*/
read(sockfd,buff2,n);
printf("message received from the server\n");
fflush(stdout);
/*Displaying the message on monitor*/
write(1,buff2,n);
/*Closing the socket*/

42
close(sockfd);
}
OUTPUT:
Client:
$ cc client.c
$ ./a.out
IP address of Server 135.135.4.4
Enter the message to be sent: Hello World
Message sent to the server: Hello World
Message received from the server: Hello World

43
4. Implementation of Iterative and Concurrrent echo server using

connection less protocol (UDP).


4.1 AIM: Program for connection-less (UDP) service with server as iterative server
REQUIREMENTS:
HARDWARE : Pentium –II (233 Hz)/32MB RAM /3.2 GB HDD
SOFTWARE : Red Hat Linux server v.7.0,c
THEORY:
In connection less service the client does not establish connection with the server. Instead
the client just sends a datagram to the server using sendto() function, similarly the server
does not accept connection from a client ,uses recvfrom() function which waits until data
arrives from some client.
UDP CLIENT UDP SERVER

socket ()

bind ()
socket ()

recvfrom
()
sendto ()
Data(request)
Blocks until datagram received
From client

Process request

Data(reply) sendto ()

recvfrom
()
44
close ()
1. ssize_t sendto(int sockfd, const void *buff ,size_t nbytes,int flags, struct
sockaddr *from,socklen_t *addrelen);

2.ssize_t recvfrom(int sockfd, void *buff ,size_t nbytes,int flags,


struct sockaddr *to, socklen_t *addrelen);
SOURCE CODE:
/* server side program*/

#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#define MAX 1024
main()
{
int sockfd,n,len;
char buff[MAX];
/*sockaddr_in is predefined structure*/
struct sockaddr_in serv_addr, cli_addr;
bzero ((struct sockaddr*)&serv_addr, sizeof(serv_addr));
/*Creating a connection-less server socket*/
if((sockfd=socket(AF_INET,SOCK_DGRAM,0))<0)
{
perror("socket error");
exit(1);
}
/*Initializing the server socket with family, port number, ipaddress*/
serv_addr.sin_family=AF_INET;
serv_addr.sin_port=htons(8110);
serv_addr.sin_addr.s_addr=htonl(INADDR_ANY);

45
/*Binding the structure to the server socket*/
if(bind(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr))<0)
{
perror("bind error");
exit(1);
}
len=sizeof(clie_addr);
/*Receiving a message from Client*/
n=recvfrom(sockfd,buff,MAX,0,(struct sockaddr* )&clie_addr,&len);
write(1,buff,n);
/*Sending a message to Client*/

sendto(sockfd,buff,n,0,(struct sockaddr*)&clie_addr,sizeof(clie_addr));
/*Closing the socket*/
close(sockfd);
}

OUTPUT:

Server:
$ cc server.c
$ ./a.out
Hello World

/* client side program*/

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

46
#include<arpa/inet.h>
main()
{
int sockfd, n, len ;
char buff1[512],buff2[512];
/*sockaddr_in is predefined structure*/
struct sockaddr_in serv_addr,cli_addr;
/* creating a connectionless server socket*/
if((sockfd=socket(AF_INET,SOCK_DGRAM,0))<0)
{
perror("client: socket error\n");
}
/*Initializing the socket with server family, port number, ipaddress*/

serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=inet_addr("135.135.4.4");
serv_addr.sin_port=htons(7641);
bzero((char *)&cli_addr,sizeof(cli_addr));

/*Initializing the socket with client family, port number, ipaddress*/


cli_addr.sin_addr.s_addr=inet_addr(“135.135.4.4);
cli_addr.sin_port=htons(0);
/*Binding the structure to the client socket*/
bind(sockfd,(struct sockaddr *)&cli_addr,sizeof(cli_addr));

/*reading a message from Keyboard to buff1 */


n= read(0,buff1,sizeof(buff1));

/*sending message to server */


sendto (sockfd,buff1,n,0,(struct sockaddr *)&serv_addr,sizeof(serv_addr));
len = sizeof(serv_addr);

47
/*Receiving a message from Server*/
n = recvfrom (sockfd,buff2,sizeof(buff2),0,(struct sockaddr *)
&serv_addr, &len);
write(1,buff2,n);
}
/*Closing the socket*/
close(sockfd);
exit(0);
}

OUTPUT:

Client 1 :
$ cc udpcli.c
$ ./a.out
Client starts
Enter a message : Hello World

Client 2 :
$ ./cc udpcli2.c
$./a.out
Client starts
Enter a message : Bye World

48
4.2 AIM: Program for connection-Less (UDP) service with server as concurrent
server
REQUIREMENTS:
HARDWARE : Pentium –II (233 Hz)/32MB RAM /3.2 GB HDD
SOFTWARE : Red Hat Linux server v.7.0,c

SOURCE CODE:
/* server side program*/
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
main()
{
int i,sockfd,newsockfd,pid,cli_addr_len,n;
char buff1[80];
/*sockaddr_in is predefined structure*/
struct sockaddr_in cli_addr,serv_addr;
/*Creating a concurrent connection-less socket*/
if((sockfd=socket(AF_INET,SOCK_DGRAM,0))<0)
{
perror("server: cant open stream socket");
}
bzero((char *)&serv_addr,sizeof(serv_addr));
/*Initializing the server socket with family, port number, ipaddress*/
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=htonl(INADDR_ANY);
serv_addr.sin_port=htons(7641);
/*Binding the structure to the server socket*/
if(bind(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr))<0)

49
{

perror("server:cant bind local address");


exit(1);
}
cli_addr_len=sizeof(cli_addr);
for(i=0;i<5;i++)
{
/*Receiving a message from Client*/
n=recvfrom(sockfd,buff1,80,0,(struct sockaddr *)&cli_addr, &cli_addr_len);
/*Create a child process*/
pid=fork();
if(pid= =0)
{
write(1,"server has received:",21,0);
write(1,buff1,n,0);
/*Sending a message to Client Socket*/
sendto(sockfd,buff1,n,0,(struct sockaddr *)&cli_addr, cli_addr_len);
exit(0);
}
}
/*Closing the socket*/
close(sockfd);
}
OUTPUT:
Server:
$ cc udpser.c
$ ./a.out
Server has received: hi
Server has received: hello

50
/* client side program*/
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>
main()
{
int sockfd,n,serv_addr_len,cli_addr_len,i,num;
char buff1[80],buff2[80],a[ ]=”135.135.4.4”;
/*sockaddr_in is predefined structure*/
struct sockaddr_in serv_addr,cli_addr;
bzero((char *)&serv_addr,sizeof(serv_addr));
/*Initializing the server socket with family, port number ,ipaddress*/
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=inet_addr(a);
serv_addr.sin_port=htons(7641);
if((sockfd=socket(AF_INET,SOCK_DGRAM,0))<0)
{
perror("client: socket error\n");
}
bzero((char *)&cli_addr,sizeof(cli_addr));
/*Initializing the client socket with family, port number, ipaddress*/

cli_addr.sin_family=AF_INET;
cli_addr.sin_addr.s_addr=htonl(INADDR_ANY);
cli_addr.sin_port=htons(0);
/*Binding the structure to the server socket*/
bind(sockfd,(struct sockaddr *)&cli_addr,sizeof(cli_addr));
write(1,"client starts:",15);
for(i=0;i<5;i++)
{

51
write(1,"enter a message",16,0);
fflush(0);
n=read(0,buff1,80);
serv_addr_len=sizeof(serv_addr);
/*Sending a message to Server*/
sendto(sockfd,buff1,n,0,(struct sockaddr *)&serv_addr,serv_addr_len);
/*Receiving a message from Server*/
num=recvfrom(sockfd,buff2,80,0,(struct sockaddr *)&serv_addr,&serv_addr_len);
write(1,"client has received",20,0);
write(1,buff2,num);
}
/*Closing the socket*/
close(sockfd);
exit(0);
}
OUTPUT:
Client 1 :
$ cc udpcli.c
$ ./a.out
Client starts
Enter a message : Hi
Client 2 :
$ ./cc udpcli2.c
$./a.out
Client starts
Enter a message : welcome

52
5. Build a concurrent Multithreaded File Transfer server. Use
separate Threads to allow the server to handle multiple clients
concurrently.
AIM: Program for concurrent multithreaded file transfer server.
REQUIREMENTS:
HARDWARE : Pentium –II (233 Hz)/32MB RAM /3.2 GB HDD
SOFTWARE : Red Hat Linux server v.7.0,c

FTPServer.c

#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<string.h>
#include<netinet/in.h>
#include<fcntl.h>
#define MAX 2048
main()
{
int sockfd,newsockfd,chilen,childpid,n,fd1,fd2;
char filename[1024],buff2[MAX],option[4];
struct sockaddr_in ser_addr,cli_addr;

if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0)
{
perror("solcket error");
exit(1);
}

ser_addr.sin_family=AF_INET;
ser_addr.sin_port=htons(8122);
ser_addr.sin_addr.s_addr=inet_addr("135.135.4.4");

if(bind(sockfd,(struct sockaddr *)&ser_addr,sizeof(ser_addr))<0)


{
perror("Bind error: ");
exit(1);
}

listen(sockfd,5);
for( ; ;)

53
{
chilen=sizeof(cli_addr);
if((newsockfd=accept(sockfd,(struct sockaddr *)&cli_addr,&chilen))<0)
{
perror("accept error");
exit(1);
}

if((childpid=fork())<0)
{
perror("server:fork error");
exit(1);
}

if(childpid==0)
{
close(sockfd);
while(1)
{

n=read(newsockfd,option,3);
option[n]='\0';
if(bcmp(option,"get",3)==0) {

n=read(newsockfd,filename,sizeof(filename));

filename[n]='\0';
fd1 = open(filename,0);
n=read(fd1,buff2,MAX);
buff2[n]='\0';
write(newsockfd,buff2,strlen(buff2));

close(fd1);

}
else if(bcmp(option,"put",3)==0){
n=read(newsockfd,filename,sizeof(filename));
write(1,filename,strlen(filename));
creat(filename,S_IRWXU);
fd2=open(filename,O_WRONLY);

n=read(newsockfd,buff2,sizeof(buff2));
write(fd2,buff2,strlen(buff2));
close(fd2);
}

54
else
break;
}
}
}
close(sockfd);
}
FTPClient.c

#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<string.h>
#include<netinet/in.h>
#include<fcntl.h>
#define MAX 2048
main(int argc, char* argv[])
{
int sockfd,n,ch,fd1,fd2;
char filename[1024],buff2[MAX];
struct sockaddr_in ser_addr,cli_addr;

if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0)
{
perror("solcket error");
exit(1);
}

ser_addr.sin_family=AF_INET;
ser_addr.sin_port=htons(8122);
ser_addr.sin_addr.s_addr=inet_addr("135.135.4.4");

if(connect(sockfd,(struct sockaddr *)&ser_addr,sizeof(ser_addr))<0)


{
perror("connect error");
exit(1);
}

while(1){
printf("MENU\n1. GET\n2. PUT\n3. EXIT\nEnter your choice:");
fflush(stdout);
scanf("%d",&ch);

switch(ch){
case 1:

55
write(sockfd,"get",3);
write(1,"Enter File name: ",17);
n=read(0,filename,15);
filename[n-1]='\0';
write(sockfd,filename,strlen(filename));
creat(filename,S_IRWXU);
fd1=open(filename,O_WRONLY);
read(sockfd,buff2,MAX);
write(fd1,buff2,strlen(buff2));
close(fd1);
break;
case 2:
write(sockfd,"put",3);
write(1,"Enter File name: ",17);
n=read(0,filename,15);
filename[n-1]='\0';
write(sockfd,filename,strlen(filename));
fflush(stdout);
fd2=open(filename,0);
read(fd2,buff2,MAX);
write(sockfd,buff2,strlen(buff2));
close(fd2);
break;
case 3: exit(1);

}}

close(sockfd);
exit(0);
}

56
Output:

57
6. Programs to demonstrate the usage of Advanced Socket System
calls like Getsockopt(), Setsockopt(), Select(),Readv(),Writev(),
getpeername(), Getsockname().

6.1 AIM: Advance socket system calls: program for readv () and writev ()

REQUIREMENTS:
HARDWARE : Pentium –II (233 Hz)/32MB RAM /3.2 GB HDD
SOFTWARE : Red Hat Linux server v.7.0,c
THEORY:
The readv () function reads count blocks from the file associated with the file descriptor
fields into the multiple buffers described by vector.

The writev () function writes at most count blocks described by vector to the file
associated with the file descriptor fields

The pointer vector points to a struct iovec defined in <sys/uio.h> as follows:

struct iovec {
void *iov_base; /* starting base address*/
size_t iov_len; /* number of bytes*/
};

Buffers are processed in the order “ vector[0]”, “vector[1]”,……..”vector[count]”.

int readv (int fd ,struct iovec iov[] , int iovcount);

int writev (int fd ,struct iovec iov[] , int iovcount);

58
SOURCE CODE:
/*server side program */
#include<stdio.h>
#include<sys/socket.h>
#include<errno.h>
#include<netinet/in.h>
#include<string.h>
#include<stdlib.h>
#include<sys/uio.h>

short myport;
main(int argc , char *argv[ ])
{
int sockfd , newfd ,nbyte;
struct sockaddr_in myaddr;
struct iovec i [3];
char buff[512] , buff1[7], buff2[6], buff3[7];
/* set up the base address*/
i[0].iovec_base=buff1;
i[0].iovec_len =7;
i[0].iovec_base=buff2;
i[0].iovec_len =6;
i[0].iovec_base=buff3;
i[0].iovec_len =7;
if(argc != 2)
{
perror(“INVALID NO OF ARGS”);
exit(1);
}
if ((sockfd = socket(AF_INET,SOCK_STREAM,0)) = = -1)
{

59
perror(“UNABLE TO CREATE SOCKET”);
exit(1);
}
myport = atoi(argv[1]);
myaddr.sin_family = AF_INET;
myaddr.sin_addr.s_addr = INADDR_ANY
myaddr.sin_port=htons(myport);
bzero(&(myaddr.sin_zero),8);
if((bind(sockfd,(struct sockaddr*)& myaddr, sizeof(myaddr))) = = -1)
{
perror(“BIND ERROR”);
exit(1);
}
if(listen (sockfd , 0) = = -1)
{
perror(“listen error”);
exit(1);
}
for(;;)
{
if((newfd = accept(sockfd , 0 , 0)) = = -1)
{
perror(“accept error”);
exit(1);
if((nbyte = readv(newfd , i ,3))<0)
{
perror(“read error”);
exit(1);
}
if(writev (newfd , i , 3))<0)
{

60
perror(“write error”);
exit(1);
}
}
}
OUTPUT:
$ cc server.c
$./a.out Any port no
e.g:- ./a.out 8180

/*client side program */


#include<stdio.h>
#include<sys/socket.h>
#include<errno.h>
#include<netinet/in.h>
#include<string.h>
#include<stdlib.h>
#include<sys/uio.h>
short destport;
main(int argc , char *argv[ ])
{
int sockfd , n ,bytes ,nb;
struct sockaddr_in servaddr;
struct iovec i [3], j[3];
char buff[512] = “ENTER THE TEXT”, buff1[7], buff2[6], buff3[7], buff4[7], buff5[6],
buff6[7];

i[0].iovec_base=buff1;
i[0].iovec_len =7;
i[0].iovec_base=buff2;
i[0].iovec_len =6;

61
i[0].iovec_base=buff3;
i[0].iovec_len =7;
i[0].iovec_base=buff4;
i[0].iovec_len =7;
i[0].iovec_base=buff5;
i[0].iovec_len =7;
i[0].iovec_base=buff6;
i[0].iovec_len =7;
if(argc != 3)
{
perror(“INVALID ARGS”);
if ((sockfd = socket(AF_INET,SOCK_STREAM,0)) = = -1)
{
perror(“UNABLE TO CREATE SOCKET”);
exit(1);
}
destport = atoi(argv[1]);
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr(argv[2]);
servaddr.sin_port=htons(destport);
bzero(&(servaddr.sin_zero),8);
if((connect (sockfd,(struct sockaddr*)&servaddr, sizeof(serv_addr))) = = -1)
{
perror(“CONNECT ERROR”);
exit(1);
}
write(1,buff,sizeof(buff));
read(0,buff1,sizeof(buff1));
write(1,buff,sizeof(buff));
read(0,buff1,sizeof(buff2));
write(1,buff,sizeof(buff));

62
read(0,buff1,sizeof(buff3));
if((writev (sockfd, i ,3 ))<0)
{
perror(“WRITE ERROR”);
exit(1);
}
if((readv (sockfd , j, 3)) <0)
{
perror(“ READ ERROR”);
exit(1);
}
write(1, buff4 , sizeof(buff4));
write(1, buff5 , sizeof(buff5));
write(1, buff6 , sizeof(buff6));
return 0;
}

OUTPUT:
$ cc client.c
$./a.out Any port no (same as in the server program) ipaddress of server
e.g:- ./a.out 8180 135.135.4.4
Enter the message to be sent to the server:
Enter the text
Hi
Enter the text
Hello
Enter the text
Welcome
Same message returns from the server.

63
6.2 AIM: Advance socket system calls: program for select ()
REQUIREMENTS:
HARDWARE : Pentium –II (233 Hz)/32MB RAM /3.2 GB HDD
SOFTWARE : Red Hat Linux server v.7.0,c
THEORY:
#include<sys/types.h>
#include<sys/time.h>

int select (int maxfdpl , fd_set *readfds , fd_set *writefds , fd_set *exceptfds , struct
timeval *timeout);

FD_ZERO (fd_set *fdset) ; //clear all the bits in fdset


FD_SET (int fd , fd_set *fdset) ; //turn the bit for fd on in fdset
FD_CLR (int fd , fd_set *fdset) ; //turn the bit for fd off in fdset
FD_ISSET (int fd , fd_set *fdset) ; //test the bit for fd in fdset

The structure pointed to by the timeout argument is defined in <sys/time.h> as


struct timeval{
long tv_sec; //seconds
long tv_usec; // micro seconds
};

Ex:- 1. FD_ZERO(&fdvar); // initialize the set-all bits off


2. FD_SET(1, &fdvar); //turn on bit for fd 1

SOURCE CODE:
#include<stdio.h>
#include<sys/time.h>
#include<sys/types.h>
#include<unistd.h>
int main(void)
{

64
fd_set rfds;
struct timeval tv;
int retval;
/*watch stdin (fd 0) to see when it has input*/
FD_ZERO(&rfds);
FD_SET(0,&rfds);
/*wait up to five seconds*/
tv.tv_sec=5;
tv.tv_usec=0;
retval=select(l, &rfds, NULL, NULL, &tv);
/*Don’t rely on the value of tv now!*/
if(retval==-1)
perror(“select( )”);
else if(retval>( ))
printf(“Data is available now.\n”);
/*FD ISSET(0,&rfds)will be true*/
else
printf(“No data within five seconds\n”);
return 0;
}

OUTPUT:
$ cc sel.c
$./a.out aaa
Data available now

65
6.3 AIM: Advance socket system calls: program for getsockname ()
REQUIREMENTS:
HARDWARE : Pentium –II (233 Hz)/32MB RAM /3.2 GB HDD
SOFTWARE : Red Hat Linux server v.7.0,c
THEORY:
Getsockname – get the socket name , included in sys/socket.h file

int getsockname (int socket , struct sockaddr *address , socklen _t


*address_len);

The getsockname () function retrieves the locally bound name of the specified
socket ,stores address in the sockaddr structure pointed to by the address argument and
stores the length of this address in the object pointed to by the address_len argument.

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

If the socket has not been bound to a local name the value stored in the object pointed to
by address is unspecified. upon successful completion ,0 is returned the address argument
points to the address of the socket and the address_len argument points to the length of
the address.otherwise,-1 is returned and errno is set to indicate the error.
SOURCE CODE:
/* server side program*/
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<stdio.h>
int main()
{
int server_sockfd , client_sockfd ;

66
int server_len , client_len;
struct sockaddr_in server_address , client_address;

server_sockfd = socket (AF_INET , SOCK_STREAM , 0);

server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = inet_addr(“135.135.4.4”);
server_address.sin_port=7991;

server_len = sizeof ( server_address);

bind(server_sockfd , (struct sockaddr*)&server_address , server_len);

if((getsockname ( server_sockfd, (struct sockaddr*)&server_address, ,&server_len))<0)


printf(“error”);

printf(“\n socket has port %d \n”, ntohs(server_address.sin_port));

listen (server_sockfd , 5 );
while(1)
{
char ch;
printf(“server is waiting \n”);
client_len = sizeof(client_address);
client_sockfd =accept( server_sockfd , (struct sockaddr*)&client_address, &client_len);
printf(“\n %s \n”,inet_ntoa(client_address.sin_addr));
printf(“\n %u \n”, client_address.sin_port);
read(client_sockfd, &ch , 1);
prinf(“ I AM THE SERVER PROGRAM just received a character from the client…..it is %c \n”,
ch);

67
printf(“ I AM THE SERVER PROGRAM I am giving back the same character back to the
client….\n\n\n”);
write(client_sockfd , &ch , 1);
close(client_sockfd);
}
}

OUTPUT:

I AM SERVER PROGRAM just received a character from the client……. it is A.

I AM SERVER PROGRAM I am giving back the same character back to the client…….

/* client side program*/


#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<stdio.h>
int main()
{
int sockfd , len , na;
char str[80];
struct sockaddr_in address , name;
int result;
char sent = ‘A’;
char received;

sockfd = socket (AF_INET ,SOCK_STREAM , 0);

68
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr(“135.135.4.4”);
address.sin_port=7991;

len = sizeof(address);

result = connect(sockfd , (struct sockaddr*)&address , len);


if(result = = -1)
{
perror(“client”);
exit(1);
}
na = sizeof(name);
printf(“ \n output of connect system call is %d \n\n “, result);
write(sockfd, &sent , 1);
read(sockfd , ,&received , 1);
printf(“char from server = %c \n”, received);

getpeername(sockfd,(struct sockaddr*)&name , &na);


inet_ntop(AF_INET, &name.sin_addr.s_addr, str, sizeof(str));
printf(“ the port is %d \n”, htons(name.sin_port));
printf(“ the peername is %s \n”,str);
close(sockfd);
exit(0);
}

OUTPUT:

Char form server A


The port no is 7991
The peername is 135.135.4.4

69
6.4 AIM: Advance socket system calls: program for getpeername ()
REQUIREMENTS:
HARDWARE : Pentium –II (233 Hz)/32MB RAM /3.2 GB HDD
SOFTWARE : Red Hat Linux server v.7.0,c
THEORY:
This function will tell you who is at all other end of a connected stream socket. this is
define din #include<sys/socket.h>.

int gerpeername ( int sockfd , struct sockaddr *addr, int * addrlen);

SOURCE CODE:
/* server side program*/
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<stdio.h>
int main()
{
int server_sockfd , client_sockfd ;
int server_len , client_len;
struct sockaddr_in server_address , client_address;
server_sockfd = socket (AF_INET , SOCK_STREAM , 0);
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = inet_addr(“135.135.4.4”);
server_address.sin_port=7058;

server_len = sizeof ( server_address);

70
bind(server_sockfd , (struct sockaddr*)&server_address , server_len);
listen (server_sockfd , 5 );
while(1)
{
char ch;
printf(“server is waiting \n”);
client_len = sizeof(client_address);
client_sockfd =accept( server_sockfd , (struct sockaddr*)&client_address, &client_len);
read(client_sockfd, &ch , 1);
prinf(“ I AM THE SERVER PROGRAM just received a character from the client…..it is
%c \n”, ch);
printf(“ I AM THE SERVER PROGRAM I am giving back the same character back to
the client….\n\n\n”);
write(client_sockfd , &ch , 1);
close(client_sockfd);
}
}

OUTPUT:
Server is waiting
I AM SERVER PROGRAM just received a character from the client……. it is A.

I AM SERVER PROGRAM I am giving back the same character back to the client……

. /* client side program*/


#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>

71
int main()
{
int sockfd , len , na;
char str[80];
struct sockaddr_in address , name;
int result;
char sent = ‘A’;
char received;

sockfd = socket (AF_INET ,SOCK_STREAM , 0);

address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr(“135.135.4.4”);
address.sin_port=7058;

len = sizeof(address);

result = connect(sockfd , (struct sockaddr*)&address , len);


if(result = = -1)
{
perror(“client”);
exit(1);
}
na = sizeof(name);
printf(“ \n output of connect system call is %d \n\n “, result);
write(sockfd, &sent , 1);
read(sockfd , ,&received , 1);
printf(“char from server = %c \n”, received);

getpeername(sockfd,(struct sockaddr*)&name , &na);


inet_ntop(AF_INET, &name.sin_addr.s_addr, str, sizeof(str));

72
printf(“ the port is %d \n”, htons(name.sin_port));
printf(“ the peername is %s \n”,str);
close(sockfd);
exit(0);
}

OUTPUT:

Char form server A


The port no is 7991
The peername is 135.135.4.4

6.5 AIM: Advance socket system calls: program for setsockopt (), getsockopt ()
REQUIREMENTS:
HARDWARE : Pentium –II (233 Hz)/32MB RAM /3.2 GB HDD
SOFTWARE : Red Hat Linux server v.7.0,c
THEORY:
a) int getsockopt ( int s , int level , int optname , void *optval , socklen_t
*optlen);
b) int setsockopt ( int s , int level ,int optname , const void *optval , socklen_t
optlen);
getsockpot and setsockopt manipulate the options associated with a socket.options may
exit at multiple protocol levels; they are always present at the uppermost socket level.
When manipulating socket options the level at which the options reside and the name of
the options must be specified .to manipulate the options at the socket level, level is
specified as SOL_SOCKET. To manipulate at any other level the protocol number of the
appropriate protocol controlling the options is supplied. for example ,to indicate that an
option is to be interpreted by the TCP protocol ,level should be set to the protocol number
of TCP: see getprotoent(3).

73
The parameters optval and optlen are used to access option values for setsockopt. For
getsockopt they identify a buffer the value for the requested options(s) are to be returned.
For getsockopt ,optlen is a value result parameter ,initially containing the size of the
buffer pointed to by optval and modified on return to indicate the actual size of the value
returned .if no option value is to be supplied or returned ,optval may be NULL.

optname and any specified options are passed interpreted to the appropriate protocol
module for interpretation. The include file <sys/socket.h> contains definitions for socket
level options.

Most socket level options unitize an int parameter for optval.for setsockpot, the parameter
should be non zero to enable a Boolean option,or zero if the option is to be disabled .
For a description of the available socket options see socket(7) and the appropriate
protocol man pages.

Return value: on success zero is returned. on error,-1 is returned and errno is set
appropriately.

SOURCE CODE:
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<sys/uio.h>
#include<netinet/tcp.h>
main()
{
int sfd,cl,sendbuff,maxseg;
sfd=socket(AF_INET,SOCK_STREAM,0);
if(sfd<0)

74
{
perror(“Socket error”);
exit(1);
}
cl=sizeof(maxseg);
if(getsockopt(sfd, IPPROTO_TCP,TCP_MAXSEG,(char *)&maxseg, &cl)<0)
{
perror("getsockopt error");
exit(1);
}
printf("TCP maxseg=%d\n",maxseg);
sendbuff=1045;

if(setsockopt(sfd,SOL_SOCKET,SO_SNDBUF,(char*)&sendbuff,sizeof(sendbuff))<0)
{
perror("setsockopt error");
exit(1);
}
cl=sizeof(sendbuff);
if(getsockopt(sfd,SOL_SOCKET,SO_SNDBUF,(char *)&sendbuff,&cl)<0)
{
perror("getsockopt error");
exit(1);
}
printf("send buffer size=%d\n",sendbuff);
}
OUTPUT:
$ cc sockopt.c
$ ./a.out
TCP maxseg=536
send buffer size=2090

75
6.6 AIM: Advance socket system calls: program for gethostname ()
REQUIREMENTS:
HARDWARE : Pentium –II (233 Hz)/32MB RAM /3.2 GB HDD
SOFTWARE : Red Hat Linux server v.7.0,c
THEORY:
gethostname ()-------------- who am I?
defined in #include<unistd.h> .

int gethostname( char *hostname , size_t size);

hostname is a pointer to an array pf chars that will contain the hostname upon function
return and size is the length in bytes of the hostname array.
Hostent:
The hostent structure is used by function to store information about a given host, such as
host name ipaddress and so forth. An application should never attempt to modify this
structure or to free any of its components .furthermore ,only one copy of the hostent
structure is allocated per thread, and an application should therefore copy any
information that it needs before issuing any other windows sockets API calls.

typedef struct hostent{


char FAR *h_name;
char FAR FAR **h_aliases;
short h_addrtype;
short h_lenght;
char FAR FAR **h_addr_list;
}hostent;

Members:
h_name : official name of the host(PC) .if using the DNS or similar resolution system, it
is fully qualification domain name(FQDN) that caused the server to return a reply .if
using a local hosts file,it is the first entry after the IP address.

76
h_aliases: null terminated array of alternate names.
h_length: length of each address, in bytes.
h_addr_list: null terminated list of address for the host . addresses are returned in the
network byte order. The macro h_addr is defined to be h_addr_list[0[ for compatibility
with older software.

SOURCE CODE:
/*gethostname*/
#include<sys/socket.h>
#include<stdlib.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<stdio.h>
int main( void )
{
Char host_name[50] = {0};
int ccode;
if((ccode = gethostname(host_name, sizeof ( host_name)))! = 0)
{
Printf(“get host name failed ccode = %d \n”, ccode);
Return EXIT_FAILURE;
}
Printf(“host name &s \n”,host_name);
Return EXIT_SUCCESS;
}

OUTPUT:
$ cc hst.c
$ ./a.out host name : linuxstuserver.

77
/* gethostbyname*/
#include<sys/socket.h>
#include<stdlib.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<stdio.h>
#include<errno.h>
#include<netdb.h>
#include<sys/types.h>
int main( int argc , char *argv[] )
{
struct hostent *h;
if (argc!= 2) // error check the command line
{
fprintf(stderr, “usage: getip address \n”);
exit(1);
}
if((h = gethostbyname(argv[1] = = NULL)
{
herror(“gethostbyname”);
exit(1);
}
printf(“Host name : %s \n “, h -> name);
printf(“IP address : %s \n”, inet_ntoa(*((struct in_addr*) h->addr)));
return 0;
}
OUTPUT:
$ cc hstby.c
$ ./a.out linux stuserver
Host name: linux stuserver
IP address: 127.0.0.1

78
7. Implement A Concurrent Chart Server That Allows Currently
Logged In Users To Communicate With One Another. Use socket
system calls.

AIM: Program for concurrent chart server with multiple users communicating with each
other
REQUIREMENTS:
HARDWARE : Pentium –II (233 Hz)/32MB RAM /3.2 GB HDD
SOFTWARE : Red Hat Linux server v.7.0,c

SOURCE CODE:
/* server side program*/
#include<sys/socket.h>
#include<netinet/in.h>
#include<string.h>
#include<errno.h>
#include<stdlib.h>
short myport;
main(int argc,char *argv[])
{
int sockfd , newfd , nbyte , n , p;
struct sockaddr_in myaddr , claddr;
char buff[512] , buff1[512];
if(argc!=2)
{
perror(“invalid no of arguments”);
exit(1);
}
if((sockfd=socket(AF_INET,SOCK_DGRAM,0))= = -1)
{
perror(“unable to create socket “);

79
exit (1);
}
myport=atoi(argv[1]);
myaddr.sin_family=AF_INET;
myaddr.sin_port=htons(myport);
myaddr.sin_addr.s_addr=INADDR_ANY;
bzero(&(myaddr.sin_zero),8);
if((bind(sockfd,(struct sockaddr *)&myaddr,sizeof(myaddr)))== -1)
{
perror(“bind error”);
exit(1);
}
write(1,”\n waiting for Client”,sizeof(“\n Wait for Client”));
newfd=sizeof(claddr);
if((n=recvfrom(sockfd,buff1,sizeof(uff1),0,(struct sockaddr *)&claddr,&newfd)))==-1)
{
perror(“RECEIVE ERROR”);
exit(1);
}
printf(“\n CLIENT CONNECTED……..”);
write(1,”\n Client : ”,10) ;
write(1,buff1,n);
// for(;;)
if(p=fork())<0)
{
perror(“CHILD CANNOT BE CREATED……….”);
exit(1);
}
if(p<0)
{
for(;;)

80
{
write(1,”\n Server : ”,10);
n=read(0,buff,512);
if((sendto(sockfd,buff,n,0,(struct sockaddr *)&claddr,newfd))==-1)
{
perror(“SEND ERROR”);
exit(1);
}
}
}
else
{
for(;;)
{
n=recvfrom(sockfd,buff1,sizeof(buff1),0,(struct sockaddr *)&claddr,&newfd);
write(1,”\rClient :”,10);
write(1,buff1,n);
write(1,”\nServer : ”,sizeof(‘\nServer:”));
}
}
}

OUTPUT:

$cc chatserver.c
$./a.out 7756

/* client side program*/


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

81
#include<string.h>
#include<errno.h>
#include<stdlib.h>
short myport,destport;
main(int argc,char *argv[])
{
int sockfd , newfd , nbyte , n ,na, p;
struct sockaddr_in myaddr , servaddr;
char buff[512] , buff1[512];
if(argc!=4)
{
perror(“invalid no of arguments”);
exit(1);
}
if((sockfd=socket(AF_INET,SOCK_DGRAM,0))= = -1)
{
perror(“unable to create socket “);
exit (1);
}
myport=atoi(argv[1]);
myaddr.sin_family=AF_INET;
myaddr.sin_port=htons(myport);
myaddr.sin_addr.s_addr=INADDR_ANY;

bzero(&(myaddr.sin_zero),8);

destport=atoi(argv[2]);
servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(destport);
servaddr.sin_addr.s_addr=inet_addr(argv[3]);
bzero(&(myaddr.sin_zero),8);

82
if(bind(sockfd,(struct sockaddr *)&myaddr,sizeof(myaddr)))==-1)
{
perror(“bind error”);
exit(1);
}
newfd=sizeof(servaddr);
write(1,”\n ENTER MESSAGE TO CONNECT TO THE SERVER……….. : ”,57) ;
for(;;)
if(p=fork())<0)
{
perror(“CHILD CANNOT BE CREATED……….”);
exit(1);
}
if(p<0)
{
for(;;)
{
write(1,”\n Client : ”,sizeof(“\nClient : ”));
na=read(0,buff,512);
if((sendto(sockfd,buff,na,0,(struct sockaddr *)&servaddr,newfd))==-1)
{
perror(“SEND ERROR”);
exit(1);
}
}
}
else
{
for(;;)
{
If((n=recvfrom(sockfd,buff1,sizeof(buff1),0,(struct sockaddr*)&servaddr,&newfd)))==-1);

83
{
perror(“RECEIVE ERROR”);
exit(1);
}
write(1,”\rServer :”,10);
write(1,buff1,n);
write(1,”\nClient : ”,10);
}
}
}

OUTPUT:

84
8. Program to demonstrate Remote Procedure Call (RPC).
8.1 AIM: Program to display date using Remote Procedure Call (RPC)
REQUIREMENTS:
HARDWARE : Pentium –II (233 Hz)/32MB RAM /3.2 GB HDD
SOFTWARE : Red Hat Linux server v.7.0,c
THEORY:
RPC is to call the process which resides in another machine, the process do no share the
address space, the called remote procedure executes within the environment of the server
process.

Sun micro system specific form of RPC SUNRPC has wide acceptance and many
applications like NFS. Defines the format of messages and arguments. The protocol used
is TCP (or) UDP.

Data representation is done in the form of XDR. Uses structures instead of multiple
arguments. At most one remote procedure in a remote program can be invoked at a give
time  automatic mutual exclusion.

A compiler tool helps programmers to build distributed programs automatically


RPCGEN.

The application programmer writes the interface definition file and generates the stubs
using rpcgen. The application programmer manually writes the client program and the
server program for the application. The client program is compiled to get client object
file, server program file is compiled to get the server object file. Client stub file and the
XDR filters are compiled to get client stub object file. Server stub file and the XDR
filters are compiled to get server stub object file.

Client object file, client stub object file and client side runtime library are linked together
to get the client’s executable file.

85
Server object file, server stub object file and client side runtime library are linked
together to get the server’s executable file.
e.g:- program SAMPLE_PROG {
Version SAMPLE_VERS {
Long SAMPLE_FN (long amt) = 1;
} =1;
} = 0x31234567;

Procedure identification:
Each procedure is identified by: hostname (IP address), program identifier (32 bit
integer), procedure identifier (32 bit integer), and program version identifier.

Program identifier; each remote program has a unique ID, SUN divided up the ID’s:
0x00000000 - 0x1fffffff
0x20000000- 0x3fffffff sun sys admin transient reserved
0x40000000- 0x5fffffff
0x60000000-0xffffffff

Procedure identifier and program version identifier:


Procedure identifiers usually start at 1 and are numbered sequentially. Version numbers
typically start at 1 and are numbered sequentially.
The input to rpcgen is the protocol definition (.X file) in the form of remote procedures
and parameter types.

86
RPCGEN

Input file

rpcgen

Client stubs XDR filters Header file Server skeleton

SOURCE CODE:
RPC program to find server time and date
/* date.x*/

Program dateprg
{
Version datever
{
String date (void) = 1; /* procedure number = 1*/
} =1; /* version number = 1 */
} = 0x9876544; /* program number = 0x9876544 */
/*Server.c*/
#include”date.h”
#include<time.h>

87
Char **date_1_svc(void *argp,struct svc_req *rqstp)
{
static char *result;
char msg[500];
time_tt = time(NULL);
// is used to convert result into a text string
snprintf(msg , 500 , “%s”, ctime(&t));
/* formatted output conversion*/
result = msg;
return &result;
}

/* client.c*/

#include “date.h”

Void dateprg_1(char *host)


{
CLIENT *clnt;
Char **result_1;
/* create the client handle*/
clnt = clnt_create(host , dateprg , datever , “UDP”);

if(clnt = = NULL)
{
clnt_pcreateerror(host);
exit(1);
}

88
result_1 = date_1(NULL, clnt);

if (result_1 = (char**) NULL)


{
clnt_perror(clnt , “call failed”);
}
Printf(“\n the message is %s” , *result_1);
}

int main(int argc,char *argv[])


{
char *host;
if(argc<2)
{
printf(“usage %s server_host \n”, argv[0]);
exit(1);
}
host = argv[1];
dateprg_1(host);
exit(0);
}

Steps to execute RPC program:


a) write your own RPC specification file “date.x”
$ ls
Client.c server.c date.x
b) use RPC gen to generate the files you need(i.e date.h , date_svc, and date_clnt.c
$ rpgen date.x
$ls
Client.c date_clnt.c date.h date_svc.c date.x server.c

89
c) Use cc to compile your server program
$ cc date_clnt.c date_svc.c server.c – lrpcsvc – o s
d) Use cc to compile your client program
$ cc date_clnt.c client.c – lrpcsvc – o c
e) Run your server program
$./ s
or put server to run in the background
$ ./s&
f) Run your client program
$./c <ipaddress>
$./c 135.135.4.4

OUTPUT:
The message is sat dec 29 17:53:42 2012

8.2 AIM: Program using Remote Procedure Call (RPC) (DNS)


REQUIREMENTS:
HARDWARE : Pentium –II (233 Hz)/32MB RAM /3.2 GB HDD
SOFTWARE : Red Hat Linux server v.7.0,c
SOURCE CODE:
/* sample.x*/
Program SAM_PROG
{
Version SAM_VERS
{
long SAM_FN(long amt) = 1
} =1;
} = 0x31234567;

90
/*sample_Server.c*/
#include “sam.h”

long *sam_fn_1_svc(void *argp, struct svc_req *rqstp)


{
static long result;
/* insert server code here*/
result = *result +1;
return &result;
}
/*sample_client.c*/
#include “sam.h”
Void sam_prog_1(char *host , long n)
{
CLIENT *clnt;
long *result_1;
long sam_fn_1_arg = n;
#ifndef DEBUG
clnt = clnt_create ( host , SAM_PROG , SAM_VERS , “udp”);
if(clnt = = NULL){
clnt _pcreateerror(host);
exit(1);
}
#endif /*DEBUG*/
result_1 = sam_fn_1(&sam_fn_1_arg , clnt);
if(result_1 = = (long *)NULL) {
clnt_perror(clnt , “call failed”);
}
Printf(“result &ld”, *result_1);
#ifndef DEBUG

91
Clnt_destory(clnt);
#ebdif /*DEBUG*/
}
int main( int argc , char *argv[ ])
{
char *host;
if(argc<3){
printf(“Usage :%s server_host number \n”,argv[0]);
exit(1);
}
host = argv[1];
sam_prog_1(host , atoll(argv[2]);
exit(0);
}

Steps to execute RPC program:


1. Write your own RPC specification file “sample.x”
$ ls
Client.c server.c date.x
2. Use RPC gen to generate the files you need (i.e sample.h , sample_svc.c, and
sample_clnt.c
$ rpgen sample.x
3. Use rpcgen to generate sample server program
$ rpcgen –Ss sample.x >sample_server.c
4. Use rpcgen to generate sample client program
$ rpcgen –Sc sample.x >sample_client.c
5. Use cc to compile your server program (sample_server.c)
$ cc –o sample_server sample_server.c sample_svc.c - lnsl
6. Use cc to compile your client program (sample_client.c)
$ cc –o sample_client sample_client.c sample_clnt.c - lnsl
g) Run your server program

92
$./ sample_server
or put server to run in the background
$ ./sample_server&
h) Run your client program
$./sample_client <ipaddress> <amount>

8.3 AIM: Program using Remote Procedure Call (RPC) (GCD)


REQUIREMENTS:
HARDWARE : Pentium –II (233 Hz)/32MB RAM /3.2 GB HDD
SOFTWARE : Red Hat Linux server v.7.0,c
SOURCE CODE:
/* gcd.x*/
struct num
{ long a;
long b;
};
program gcd_prog
{
version gcd_vers
{
long gcd_fn(num) = 1
} =1;
} = 0x30000001;

/*gcd_Server.c*/
#include “gcd.h”
int gcd(int a ,int b)
{
if(b= = 0)
return a;
return gcd(b,a % b)

93
}
long *gcd_fn_1_svc(num *argp, struct svc_req *rqstp)
{
static long result;

/* insert server code here*/


result = gcd((*argp).a , (*argp).b);
return &result;
}
/*gcd_client.c*/
#include “gcd.h”
Void gcd_prog_1(char *host , num number)
{
CLIENT *clnt;
long *result_1;
num gcd_fn_1_arg ;
gcd_fn_1_arg.a = number.a;
gcd_fn_1_arg.b = number.b ;
#ifndef DEBUG
clnt = clnt_create ( host , GCD_PROG , GCD_VERS , “udp”);
if(clnt = = NULL){
clnt _pcreateerror(host);
exit(1);
}
#endif /*DEBUG*/
result_1 = gcd_fn_1(&gcd_fn_1_arg , clnt);
if(result_1 = = (long *)NULL) {
clnt_perror(clnt , “call failed”);
}
Printf(“gcd is %d”, *result_1);

94
#ifndef DEBUG
clnt_destory(clnt);
#ebdif /*DEBUG*/
}
int main( int argc , char *argv[ ])
{
char *host;
num n;
if(argc<4){
printf(“Usage :%s server_host num1 num2 \n”,argv[0]);
exit(1);
}
n.a =atoll( argv[2]);
n.b =atoll( argv[3]);
host = argv[1];
gcd_prog_1(host , n);
exit(0);
}
Steps to execute RPC program:
1. Write your own RPC specification file “gcd.x”
$ ls
Client.c server.c date.x
2. Use RPC gen to generate the files you need (i.e gcd.h , gcd_svc.c,gcd_xdr.c and
gcd_clnt.c
$ rpgen gcd.x
3. Use rpcgen to generate sample server program
$ rpcgen –Ss gcd.x >gcd_server.c
4. Use rpcgen to generate sample client program
$ rpcgen –Sc gcd.x >gcd_client.c
5. Use cc to compile your server program (gcd_server.c)
$ cc –o gcd_server gcd_server.c gcd_svc.c gcd.xdr.c - lnsl

95
6. Use cc to compile your client program (sample_client.c)
$ cc –o gcd_client gcd_client.c gcd_clnt.c gcd_xdr.c - lnsl
i) Run your server program
$./ gcd_server
or put server to run in the background
$ ./gcd_server&
j) Run your client program
$./gcd_client <ipaddress> <number1 > <number 2>

8.4 AIM: Program for Remote files access using RPC


REQUIREMENTS:
HARDWARE : Pentium –II (233 Hz)/32MB RAM /3.2 GB HDD
SOFTWARE : Red Hat Linux server v.7.0,c

SOURCE CODE:
struct num
{ char *a;
// long b;
};
program rfa_prog
{
version rfa_vers
{
long rfa_fn(num) = 1
} =1;
} = 0x30000001;

/*rfa_Server.c*/
#include “rfa.h”
char* rfa(char *f)

96
{
//if(b= = 0)
// return a;
int id,n ;
char buff[100];
id=open(f,0);
n=read(id,buff,sizeof(buff));
return buff;

// return rfa(b,a % b)
}
long *rfa_fn_1_svc(num *argp, struct svc_req *rqstp)
{
static char *result;
/* insert server code here*/
result = rfa((*argp).a );
return &result; // return result;
}
/*rfa_client.c*/
#include “rfa.h”
Void rfa_prog_1(char *host , num number)
{
CLIENT *clnt;
char *result_1;
num rfa_fn_1_arg ;
rfa_fn_1_arg.a = number.a;
// rfa_fn_1_arg.b = number.b ;
#ifndef DEBUG
clnt = clnt_create ( host , RFA_PROG , RFA_VERS , “udp”);
if(clnt = = NULL){

97
clnt _pcreateerror(host);
exit(1);
}
#endif /*DEBUG*/
result_1 = rfa_fn_1(&rfa_fn_1_arg , clnt);
if(result_1 = = (char *)NULL) {
clnt_perror(clnt , “call failed”);
}
Printf(“rfa is %s”, *result_1);
#ifndef DEBUG
clnt_destory(clnt);
#ebdif /*DEBUG*/
}
int main( int argc , char *argv[ ])
{
char *host;
num n;
if(argc<4){
printf(“Usage :%s server_host num1 num2 \n”,argv[0]);
exit(1);
}
n.a = argv[2];
host = argv[1];
rfa_prog_1(host , n);
exit(0);
}
Steps to execute RPC program:
1. Write your own RPC specification file “rfa.x”
$ ls
Client.c server.c date.x

98
2. Use RPC gen to generate the files you need (i.e rfa.h , rfa_svc.c,rfa_xdr.c and
rfa_clnt.c
$ rpgen rfa.x
3. Use rpcgen to generate sample server program
$ rpcgen –Ss rfa.x >rfa_server.c
4. Use rpcgen to generate sample client program
$ rpcgen –Sc rfa.x >rfa_client.c
5. Use cc to compile your server program (rfa_server.c)
$ cc –o rfa_server server.c rfa_svc.c rfa.xdr.c - lnsl
6. Use cc to compile your client program (sample_client.c)
$ cc –o rfa_client client.c rfa_clnt.c rfa_xdr.c - lnsl
7. Run your server program
$./ rfa_server
or put server to run in the background
$ ./rfa_server&
8 .Run your client program
$./rfa_client <ipaddress> <filename>

99
9. Program to perform encryption and decryption using the
following algorithms
a) Caeser cipher.
b) Substitution cipher.
c) Transposition cipher.
9.1 AIM: Program to encrypt and decrypt using Caeser cipher

Source code:

#include <stdio.h>
#include <ctype.h>

#define MAXSIZE 1024

void encrypt(char*);
void decrypt(char*);

int main(void)
{

char s[MAXSIZE];

puts("Input text to encrypt->");


scanf("%s",s);
encrypt(s);
printf("\nMessage After decryption ");

decrypt(s);
printf("\n");

return 0;
}

void encrypt(char*str)
{
int n=0;
char *p=str,
q[MAXSIZE];

100
while(*p)
{
if(islower(*p))
{
if((*p>='a')&&(*p<'x'))
q[n]=toupper(*p + (char)3);
else if(*p=='x')
q[n]='A';
else if(*p=='y')
q[n]='B';
else
q[n]='C';
}
else
{
q[n]=*p;
}
n++; p++;
}
q[n++]='\0';
printf("\nMessageAfter encryption %s \n",q);
}

void decrypt(char*str)
{
int n=0;
char *p=str,
q[MAXSIZE];

while(*p)
{
if(isupper(*p))
{
if((*p>='D')&&(*p<='Z'))
q[n]=tolower(*p - (char)3);
else if(*p=='A')
q[n]='x';
else if(*p=='B')
q[n]='y';
else
q[n]='z';
}
else
{
q[n]=*p;

101
}
n++; p++;
}
q[n++]='\0';
puts(q);
}

Output:

9.2 AIM: Program to encrypt and decrypt using substitution cipher

Source code:

#include<stdio.h>
void main()
{
char message[100],emessage[100],dmessage[100];

int i,j=0,k,key,temp;

printf("\nEnter the key\n");

scanf("%d",&key);

key=key%26;

102
printf("\nEnter message\n");

scanf("%s",message);

for (i=0;message[i]!=0;i++)

message[i]=tolower(message[i]);

for (i=0;message[i]!=0;i++)
{

if(message[i]==' ')
emessage[j++]=message[i];

else
{
if(message[i]>=48 && message[i]<=57)
{
temp=message[i]+key;
if(temp>57)
emessage[j++]=48+(temp-58);
else

emessage[j++]=temp;
}

else {

if(message[i]>=97 && message[i]<=123)


{

temp=message[i]+key;

if(temp>122)

emessage[j++]=97+(temp-123);
else

emessage[j++]=temp;

}
else

emessage[j++]=message[i];

103
}

}
} emessage[j]='\0';

printf("\n Encrypted message is %s",emessage);

for (i=0,j=0;emessage[i]!=0;i++)
{

if(emessage[i]==' ')
dmessage[j++]=emessage[i];

else
{

if(emessage[i]>=48 && emessage[i]<=57)


{

temp=emessage[i]-key;

if(temp<48)

dmessage[j++]=58-(48-temp);
else

dmessage[j++]=temp;

else

if(emessage[i]>=97 && emessage[i]<=123)


{
temp=emessage[i]-key;

if(temp<97)

104
dmessage[j++]=123-(97-temp);

else

dmessage[j++]=temp;
}

else
dmessage[j++]=emessage[i];
}
}

dmessage[j]=0;

printf("\n\n decrypted message is %s", dmessage);


}

Output:

105
9.3 AIM: Program to encrypt and decrypt using transposition cipher.

Source code:

#include<stdio.h>
#include<string.h>

void cipher(int i,int c);


int findMin();
void makeArray(int,int);

char arr[22][22],darr[22][22],emessage[111],retmessage[111],key[55];
char temp[55],temp2[55];
int k=0;

int main()
{
char message[80],dmessage[80];

int i,j,klen,emlen,flag=0;
int r,c,index,min,rows;

printf("Enetr the key\n");


scanf("%s",key);

printf("\nEnter message to be ciphered\n");


scanf("%s",message);

strcpy(temp,key);
klen=strlen(key);

k=0;
for(i=0; ;i++)
{
if(flag==1)
break;

for(j=0;key[j]!=0;j++)
{
if(message[k]==0)
{
flag=1;
arr[i][j]='-';

106
}
else
{
arr[i][j]=message[k++];
}
}
}
r=i;
c=j;

for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%c ",arr[i][j]);
}
printf("\n");
}

k=0;

for(i=0;i<klen;i++)
{
index=findMin();
cipher(index,r);
}

emessage[k]='\0';
printf("\nEncrypted message is\n");
for(i=0;emessage[i]!=0;i++)
printf("%c",emessage[i]);

printf("\n\n");
//deciphering

emlen=strlen(emessage);
//emlen is length of encrypted message

strcpy(temp,key);

rows=emlen/klen;
//rows is no of row of the array to made from ciphered message
rows;
j=0;

107
for(i=0,k=1;emessage[i]!=0;i++,k++)
{
//printf("\nEmlen=%d",emlen);
temp2[j++]=emessage[i];
if((k%rows)==0)
{
temp2[j]='\0';
index=findMin();
makeArray(index,rows);
j=0;
}
}

printf("\nArray Retrieved is\n");

k=0;
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%c ",darr[i][j]);
//retrieving message
retmessage[k++]=darr[i][j];

}
printf("\n");
}
retmessage[k]='\0';

printf("\nMessage retrieved is\n");

for(i=0;retmessage[i]!=0;i++)
printf("%c",retmessage[i]);

return(0);
}

void cipher(int i,int r)


{
int j;
for(j=0;j<r;j++)
{
{
emessage[k++]=arr[j][i];
}

108
}
// emessage[k]='\0';
}

void makeArray(int col,int row)


{
int i,j;

for(i=0;i<row;i++)
{
darr[i][col]=temp2[i];
}
}

int findMin()
{
int i,j,min,index;

min=temp[0];
index=0;
for(j=0;temp[j]!=0;j++)
{
if(temp[j]<min)
{
min=temp[j];
index=j;
}
}

temp[index]=123;
return(index);
}

Output:

109
10.Implementation of establishing a shared key: The Diffie-Hallman
key exchange.

The purpose of the algorithm is to enable two users to securely exchange a keythat can
then be used for subsequent encryption of messages. The algorithm itself is limited to the
exchange of secret values.

Source code:

#include<stdio.h>
long long int power(int a,int b,int mod)
{
long long int t;
if(b==1)
return a;
t=power(a,b/2,mod);
if(b%2==0)
return (t*t)%mod;
else
110
return (((t*t)%mod)*a)%mod;
}

long long int calculateKey(int a,int x,int n)


{
return power(a,x,n);
}

int main()
{
int n,g,x,a,y,b;

printf("Enter the value of n and g : ");


scanf("%d%d",&n,&g);

printf("Enter the value of x for the first person : ");


scanf("%d",&x);
a=power(g,x,n);

printf("Enter the value of y for the second person : ");


scanf("%d",&y);
b=power(g,y,n);

printf("key for the first person is : %lld\n",power(b,x,n));


printf("key for the second person is : %lld\n",power(a,y,n));
return 1;
}

111
Output:

112
11.Implement the encryption and decryption of 8-bit data using
simplified Data Encryption Standard (DES) algorithm in C.

The S-DES encryption algorithm takes an 8-bit block of plaintext (example: 10111101)
and a 10-bit key as input and produces an 8-bit block of ciphertext as output. The
S-DES decryption algorithm takes an 8-bit block of ciphertext and the same 10-bit key
used to produce that ciphertext as input and produces the original 8-bit block of plaintext.

113
114
115
116
Source code:

#include <stdio.h>
intip[]={2,6,3,1,4,8,5,7}, ipinv[]={4,1,3,5,7,2,8,6},
ep[]={4,1,2,3,2,3,4,1}, p4[]={2,4,3,1};
void keygen(int [], int [], int []);
void encrypt(int [], int [], int [], int []);
void decrypt(int [], int [], int [], int []);
void sbox(int, int[], int[]);
void fk(int [],int [],int []);
void leftshift(int [], int []);
void main()
{
int pt[8],ct[8],key[10],k1[8],k2[8],plain[8],i;
printf("Enter 8-bit plain text: ");
for(i=0; i<8; i++)
scanf("%d", &pt[i]);
printf("Enter 10-bit key: ");
for(i=0; i<10; i++)
scanf("%d", &key[i]);
keygen(key,k1,k2);
printf("k1: ");
for(i=0; i<8; i++)
printf("%d", k1[i]);
printf("\nk2: ");
for(i=0; i<8; i++)
printf("%d", k2[i]);
encrypt(pt, k1,k2, ct);
printf("\nCipher Text: ");
for(i=0; i<8; i++)
printf("%d", ct[i]);
decrypt(ct, k1,k2, plain);
printf("\nPlain Text: ");
for(i=0; i<8; i++)
printf("%d", plain[i]);
getch();
}

/* Generates two 8-bit keys from 10-bit key */


void keygen(int k[], int k1[], int k2[])
{
int p10[10]={3,5,2,7,4,10,1,9,8,6};
int l1[5],l2[5],t[10],a[8],p8[8]={6,3,7,4,8,5,10,9};

117
inti,j;
for(i=0; i<10; i++)
t[i]=k[i];
for(i=0; i<10; i++)
k[i]=t[ p10[i]-1 ];
for(i=0; i<5; i++)
{
l1[i]=k[i];
l2[i]=k[i+5];
}
leftshift(l1,l2);
for(i=0; i<5; i++)
{
t[i]=l1[i];
t[i+5]=l2[i];
}
for(i=0; i<8; i++)
k1[i] = t[p8[i]-1];
leftshift(l1,l2);
leftshift(l1,l2);
for(i=0; i<5; i++)
{
t[i]=l1[i];
t[i+5]=l2[i];
}
for(i=0; i<8; i++)
k2[i] = t[p8[i]-1];
}

/* encrypts plain text into cipher text */


void encrypt(int pt[],int k1[],int k2[],int ct[])
{
inti,ppt[8],left[4],right[4],t[4],t1[8];
/*initial permutation*/
for(i=0;i<8; i++)
ppt[i]=pt[ip[i]-1];
for(i=0; i<4; i++)
{
left[i]=ppt[i];
right[i]=ppt[i+4];
}
fk(left,right,k1);
for(i=0; i<4; i++)

118
{
t[i]=left[i];
left[i]=right[i];
right[i]=t[i];
}
fk(left,right,k2);
for(i=0; i<4; i++)
{
t1[i]=left[i];
t1[i+4]=right[i];
}
/*inverse permutation*/
for(i=0;i<8; i++)
ct[i]=t1[ipinv[i]-1];
}
void fk(int l[], int r[],int k[])
{
int i,t1[2],t2[2],t[4],expr[8],tp[4],m[4],n[4];
/*Expansion right*/
for(i=0; i<8; i++)
expr[i]= r[ep[i]-1];
/*xor with key */
for(i=0; i<4; i++)
{
m[i]= expr[i] ^ k[i];
n[i]=expr[i+4] ^ k[i+4];
}
sbox(0,m,t1);
sbox(1,n,t2);
for(i=0; i<2; i++)
{
t[i]=t1[i];
t[i+2]=t2[i];
}
/* p4 permutation */
for(i=0; i<4; i++)
tp[i]=t[p4[i]-1];
for(i=0; i<4; i++)
l[i]= l[i] ^ tp[i];
}

119
void sbox(intboxno, int a[], int t[])
{
introw,col,i,x;
int s0[4][4]={ 1,0,3,2,3,2,1,0,0,2,1,3,3,1,3,2},
s1[4][4]={0,1,2,3,2,0,1,3,3,0,1,0,2,1,0,3};
row=a[0]*2+a[3];
col=a[1]*2+a[2];
if (boxno==0)
x=s0[row][col];
else
x =s1[row][col];
for(i=1; i>=0; i--)
{
t[i]= x%2;
x = x/2;
}
}
/* decrypts cipher text into plain text */
void decrypt(int ct[],int k1[],int k2[],int pt[])
{
inti,ppt[8],left[4],right[4],t[4],t1[8];
/*initial permutation*/
for(i=0;i<8; i++)
ppt[i]=ct[ip[i]-1];
for(i=0; i<4; i++)
{
left[i]=ppt[i];
right[i]=ppt[i+4];
}
fk(left,right,k2);
for(i=0; i<4; i++)
{
t[i]=left[i];
left[i]=right[i];
right[i]=t[i];
}
fk(left,right,k1);
for(i=0; i<4; i++)
{
t1[i]=left[i];
t1[i+4]=right[i];
}

120
/*inverse permutation*/
for(i=0;i<8; i++)
pt[i]=t1[ipinv[i]-1];
}
void leftshift(int t1[], int t2[])
{
inti,m,n;
m=t1[0]; n=t2[0];
for( i=0; i<4; i++)
{
t1[i] = t1[i+1];
t2[i]= t2[i+1];
}
t1[4]=m; t2[4]=n;
}

Output:
Enter 8-bit plain text: 1 0 1 0 1 0 1 0
Enter 10-bit key: 1 1 1 1 1 1 1 1 1 1
K1: 1 1 1 1 1 1 1 1
K2: 1 1 1 1 1 1 1 1
Cipher text: 0 0 0 0 0 1 0 0
Plain text: 1 0 1 0 1 0 1 0

121
12.Implement RSA algorithm for Encryption and Decryption in C.

RSA is an algorithm for public-key cryptography that is based on the presumed difficulty


of factoring large integers, the factoring problem. RSA stands for Ron Rivest, Adi
Shamir and Leonard Adleman,
The RSA algorithm involves three steps: key generation, encryption and decryption.
RSA involves a public key and a private key. The public key can be known to everyone
and is used for encrypting messages. Messages encrypted with the public key can only be
decrypted using the private key. The keys for the RSA algorithm are generated the
following way:

Source code:
#include <stdio.h>
int gcd(int, int);
int exteuclid(int , int );

122
int fme(int, int, int);
int keygen(int,int *,int *);
void main()
{
int p,q,n,fin,i,e,d;
int M,C,plain;
//Key generation
printf("Enter 2 Prime Nos: ");
scanf("%d%d", &p,&q);
n=p*q;
fin=(p-1)*(q-1);
keygen(fin,&e,&d);
printf("%d %d",e,d);
printf("\nPublic Keys: %d , %d\n", e, n);
printf("Private Keys: %d , %d", d,n);
// encryption
do
{
printf("\n\nEnter PlainText below %d: ",n);
scanf("%d",&M);
}
while (!(M < n));
C= fme(M,e,n);
printf("\nCipher Text: %d",C);
// decryption
plain=fme(C,d,n);
printf("\n\nDecrypted Text: %d", plain);
}
//gcd of two numbers
int gcd(int a, int b)
{
int r;
if (b==0)
return a;
r=a%b;
gcd(b,r);
}

//finding multiplicative inverse


int exteuclid(int m, int x)
{
int a[3], b[3], t[3],i,q;
a[0]=1;

123
a[1]=0;
a[2]=m;
b[0]=0;
b[1]=1;
b[2]=x;
while(1)
{
if (b[2]==0)
return 0;
if(b[2]=1)
return b[1];
q=a[2]/b[2];
for (i=0; i<3; i++)
{
t[i]= a[i]-q*b[i];
a[i]=b[i];
b[i]=t[i];
}
}
}
//cal a power b mod n
int fme(int a, int b, int n)
{
int f=1, t=a;
while(b>0)
{
if (b%2==1)
f=(f*t) % n;
t=(t*t) %n;
b=b/2;
}
return f;
}
// generating keys e and d
int keygen (int m, int *e, int *d)
{
int x0=2,a,c=3,y;
a=(x0+2)%m;
while (1)
{
y=(a*x0+c)%m;
*d=exteuclid(m,y);
if (*d<0) *d += m;

124
if (*d != 0 )
{
*e=y;
break;
}
x0 = y;
}
}

Output:
Enter 2 prime nos: 11
17
Public keys: 11,187
Private keys: 131,187
Enter plain text below 187:14
Cipher text: 146
Decrypted text: 14

125

You might also like