Professional Documents
Culture Documents
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
DESCRIPTION
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.
-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
-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.
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.
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.
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
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).
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
[-] allmulti
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]
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 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)
;; 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
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.
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
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:
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>
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.
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>
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.
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>
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>
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.
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);
28
SERVER CLIENT
socket ()
socket ()
bind ()
bind ()
listen ()
connect ()
accept ()
read () write ()
write () read ()
Close()
Close()
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.
Increasing memory
addresses
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.
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];
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);
32
listen (sockfd,5);
for (;;)
{
chilen=sizeof(cli_addr);
printf("\n server is waiting for connection requests\n");
fflush(stdout);
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*/
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……..
34
/* client side program*/
#include<sys/socket.h>
#include<sys/types.h>
#include<strings.h>
#include<stdio.h>
#include<netinet/in.h>
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));
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);
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);
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);
}
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
Client 2 :
$ cc tcpcli2.c
37
$ ./a.out
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;
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
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
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);
#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
#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));
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
{
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");
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");
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
struct iovec {
void *iov_base; /* starting base address*/
size_t iov_len; /* number of bytes*/
};
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
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);
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
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_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = inet_addr(“135.135.4.4”);
server_address.sin_port=7991;
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 I am giving back the same character back to the client…….
68
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr(“135.135.4.4”);
address.sin_port=7991;
len = sizeof(address);
OUTPUT:
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>.
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;
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……
71
int main()
{
int sockfd , len , na;
char str[80];
struct sockaddr_in address , name;
int result;
char sent = ‘A’;
char received;
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr(“135.135.4.4”);
address.sin_port=7058;
len = sizeof(address);
72
printf(“ the port is %d \n”, htons(name.sin_port));
printf(“ the peername is %s \n”,str);
close(sockfd);
exit(0);
}
OUTPUT:
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> .
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.
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
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.
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
86
RPCGEN
Input file
rpcgen
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”
if(clnt = = NULL)
{
clnt_pcreateerror(host);
exit(1);
}
88
result_1 = date_1(NULL, clnt);
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
90
/*sample_Server.c*/
#include “sam.h”
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);
}
92
$./ sample_server
or put server to run in the background
$ ./sample_server&
h) Run your client program
$./sample_client <ipaddress> <amount>
/*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;
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>
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>
void encrypt(char*);
void decrypt(char*);
int main(void)
{
char s[MAXSIZE];
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:
Source code:
#include<stdio.h>
void main()
{
char message[100],emessage[100],dmessage[100];
int i,j=0,k,key,temp;
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 {
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';
for (i=0,j=0;emessage[i]!=0;i++)
{
if(emessage[i]==' ')
dmessage[j++]=emessage[i];
else
{
temp=emessage[i]-key;
if(temp<48)
dmessage[j++]=58-(48-temp);
else
dmessage[j++]=temp;
else
if(temp<97)
104
dmessage[j++]=123-(97-temp);
else
dmessage[j++]=temp;
}
else
dmessage[j++]=emessage[i];
}
}
dmessage[j]=0;
Output:
105
9.3 AIM: Program to encrypt and decrypt using transposition cipher.
Source code:
#include<stdio.h>
#include<string.h>
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;
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;
}
}
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';
for(i=0;retmessage[i]!=0;i++)
printf("%c",retmessage[i]);
return(0);
}
108
}
// emessage[k]='\0';
}
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;
}
int main()
{
int n,g,x,a,y,b;
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();
}
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];
}
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.
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);
}
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