0% found this document useful (0 votes)
19 views63 pages

CN Lab

Uploaded by

kannababu.4724
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views63 pages

CN Lab

Uploaded by

kannababu.4724
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

1.

Understanding and using of commands like ifconfig, netstat, ping, arp, telnet, ftp, finger,
traceroute, whois etc. Usage of elementary socket system calls (socket (), bind(),
listen()accept(),connect(),send(),recv(),sendto(),recvfrom()).

REGD.N0:-21K61A6101
Program Objective:
Understanding and using of commands like ifconfig, netstat, ping, arp, telnet, ftp, finger,
traceroute, whois
Program Description:
UNIX utilities are commands that, generally, perform a single task. It may be as simple as
printing the date and time, or a complex as finding files that match many criteria throughout a
directory hierarchy
IFCONFIG
The Unix command ifconfig (short for interface configurator) serves to configure and control
TCP/IP network interfaces from a command line interface (CLI). Common uses for ifconfig
include setting an interface's IP address and netmask, and disabling or enabling a given
interface. Ipconfig is an MS-DOS utility that can be used from MS-DOS and an MS-DOS shell to
display the network settings currently assigned and given by a network. This command can be
utilized to verify a network connection as well as to verify your network settings. Syntax:
ipconfig [/allcompartments] [/? | /all | /renew [adapter] | /release [adapter] | /renew6
[adapter] | /release6 [adapter] | /flushdns | /displaydns | /registerdns | /showclassid adapter
| /setclassid adapter [classid] | /showclassid6 adapter | /setclassid6 adapter [classid] ] Example:
ipconfig /all

Sasi institute of technology and engineering 1


NETSTAT
netstat (network statistics) is a command-line tool that displays network connections (both
incoming and outgoing), routing tables, and a number of network interface statistics. It is used
for finding problems in the network and to determine the amount of traffic on the network as
a performance measurement.
Parameters

REGD.N0:-21K61A6101
Parameters used with this command must be prefixed with a hyphen (-) rather than a slash (/).
-a : Displays all active TCP connections and the TCP and UDP ports on which the computer is
listening.
-e : Displays ethernet statistics, such as the number of bytes and packets sent and received.
This parameter can be combined with -s.
-f : Displays fully qualified domain names for foreign addresses.
-i : Displays network interfaces and their statistics (not available under Windows) -n : Displays
active TCP connections, however, addresses and port numbers are expressed numerically and
no attempt is made to determine names.
-o : Displays active TCP connections and includes the process ID (PID) for each connection.
-p Linux: Process : Show which processes are using which sockets
Syntax: NETSTAT [-a] [-b] [-e] [-f] [-n] [-o] [-p proto] [-r] [-s] [-x] [-t] [interval]
OUTPUT

PING
Ping is a computer network tool used to test whether a particular host is reachable across an IP
network; it is also used to self test the network interface card of the computer, or as a speed
test. It works by sending ICMP “echo request” packets to the target host and listening for ICMP

Sasi institute of technology and engineering 2


“echo response” replies. Ping does not estimate the round-trip time, as it does not factor in the
user's connection speed, but instead is used to record any packet loss, and print a statistical
summary when finished. The word ping is also frequently used as a verb or noun, where it is
usually incorrectly used to refer to the round-trip time, or measuring the round-trip time.
Syntax: ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS] [-r count] [-s count] [[-j host-list] | [-k
host-list]] [-w timeout] [-R] [-S srcaddr] [-4] [-6 target_name]
OUTPUT

REGD.N0:-21K61A6101
ARP
In computer networking, the Address Resolution Protocol (ARP) is the method for finding a
host's link layer (hardware) address when only its Internet Layer (IP) or some other Network
Layer address is known. ARP has been implemented in many types of networks; it is not an IP-
only or Ethernet-only protocol. It can be used to resolve many different network layer protocol
addresses to interface hardware addresses, although, due to the overwhelming prevalence of
IPv4 and Ethernet, ARP is primarily used to translate IP addresses to Ethernet MAC addresses.
Arp syntax:
ARP -s inet_addr eth_adr [if_addr]
ARP -d inet_addr [if_addr]
ARP -a [inet_addr] [-N if_addr]
Example: arp -a
OUTPUT

Sasi institute of technology and engineering 3


REGD.N0:-21K61A6101
TELNET
Telnet (Telecommunication network) is a network protocol used on the Internet or local area
network (LAN) connections. Typically, telnet provides access to a command-line interface on a
remote machine. The term telnet also refers to software which implements the client part of
the protocol. Telnet clients are available for virtually all platforms
Protocol details:
Telnet is a client-server protocol, based on a reliable connection-oriented transport. Typically
this protocol is used to establish a connection to TCP port 23 Syntax: telnet [-468ELadr] [-S tos]
[-b address] [-e escapechar] [-l user] [-n tracefile] [host [port]] Example: telnet myhost.com
FTP
File Transfer Protocol (FTP):
FTP is a network protocol used to transfer data from one computer to another through a
network such as the Internet.FTP is a file transfer protocol for exchanging and manipulating
files over a TCP computer network. An FTP client may connect to an FTP server to manipulate
files on that server.FTP runs over TCP. It defaults to listen on port 21 for incoming connections
from FTP clients. A connection to this port from the FTP Client forms the control stream on
which commands are passed from the FTP client to the FTP server and on occasion from the

Sasi institute of technology and engineering 4


FTP server to the FTP client. FTP uses out-of-band control, which means it uses a separate
connection for control and data. Thus, for the actual file transfer to take place, a different
connection is required which is called the data stream.
Syntax: ftp [-46pinegvd] [host [port]]
Example: ftp exampleftp.computerhope.com
FINGER:

REGD.N0:-21K61A6101
In computer networking, the Name/Finger protocol and the Finger user information protocol
are simple network protocols for the exchange of human-oriented status and user information.
finger looks up and displays information about system users.
Syntax: finger [-lmsp] [user ...] [user@host ...]
Example: finger -p ch

TRACEROUTE:
traceroute is a computer network tool used to determine the route taken by packets across an
IP network . An IPv6 variant, traceroute6, is also widely available.Traceroute is often used for
network troubleshooting. By showing a list of routers traversed, it allows the user to identify
the path taken to reach a particular destination on the network. This can help identify routing
problems or firewalls that may be blocking access to a site. Traceroute is also used by
penetration testers to gather information about network infrastructure and IP ranges around a
given host. It can also be used when downloading data, and if there are multiple mirrors
available for the same piece of data, one can trace each mirror to get a good idea of which
mirror would be the fastest to use.
Syntax: traceroute [-46dFITUnreAV] [-f first_ttl] [-g gate,...] [-i device]
[-m max_ttl] [-p port] [-s src_addr] [-q nqueries]
-N squeries] [-t tos] [-l flow_label] [-w waittime]
[-z sendwait] [-UL] [-D] [-P proto] [--sport=port] [-M method]
[-O mod_options] [--mtu] [--back] host [packet_len]
Example: traceroute www.google.com
WHO IS:
WHOIS (pronounced "who is"; not an acronym) is a query/response protocol which is widely
used for querying an official database in order to determine the owner of a domain name, an
IP address, or an autonomous system number on the Internet. WHOIS lookups were
traditionally made using a command line interface, but a number of simplified web-based tools
now exist for looking up domain ownership details from different databases. WHOIS normally
runs on TCP port 43.

Sasi institute of technology and engineering 5


The WHOIS system originated as a method that system administrators could use to look up
information to contact other IP address or domain name administrators (almost like a "white
pages").
Syntax: whois [ -h HOST ] [ -p PORT ] [ -aCFHlLMmrRSVx ] [ -g SOURCE:FIRST-LAST ] [ -i ATTR ] [ -
S SOURCE ] [ -T TYPE ] object
Example: whois www.google.com

REGD.N0:-21K61A6101
Socket
To do network I/O, the first thing a process must do is to call the socket system call, specifying
the type of communication protocol desired.
#include<sys/types.h>
#include<sys/socket.h>
int socket(int family, int type, int protocol);
The family is one of
AF_UNIX -- Unix internal protocols
AF_INET -- Internet protocols
AF_NS -- Xerox NS Protocols
AF_IMPLINK-- IMP link layer
The AF_ prefix stands for "address family." In the first project, we are going to use AF_INET.
The socket type is one of the following:
SOCK_STREAM stream socket
SOCK_DGRAM datagram socket
SOCK_RAW raw socket
SOCK_SEQPACKETsequenced packet socket
SOCK_RDM reliably delivered message socket (not implemented yet)
The protocol argument to the socket system call is typically set to 0 for most user applications.
The valid combinations are shown as follows

Sasi institute of technology and engineering 6


/* A program to create a socket using socket systemcall*/
#include<stdio.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.
h>

REGD.N0:-21K61A6101
#include<stdlib.h>
int main() {
int sfd; struct sockaddr_in serv_addr;
if((sfd=socket(AF_INET,SOCK_STREAM,0))<0)
{ perror("socket
error"); exit(-1);
}
serv_addr.sin_family=AF_INET; serv_addr.sin_port=htons(4890);

serv_addr.sin_addr.s_addr=inet_addr("172.16.0.1");
if((bind(sfd,(struct sockaddr *) & serv_addr,sizeof(serv_addr)))<0)
{ perror("bind
error"); exit(-1);
}
printf("address binded...."); printf("\nserver ip address
is %s",inet_ntoa(serv_addr.sin_addr)); printf("\n port
number=%d\n",ntohs(serv_addr.sin_port)); close(sfd);
return 0; } O/P:
address binded.... server ip address
is 172.16.0.1
portnumber=4890

O/P: SOCKET CREATED....


Bind
The bind system call assigns a name to an unnamed socket.
#include<sys/types.h>

Sasi institute of technology and engineering 7


#include<sys/socket.h>
int bind(int sockfd, struct sockaddr *myaddr, int addrlen);
The first argument is the socket descriptor returned from socket system call. The second
argument is a pointer to a protocol-specific address and the third argument is the size of this
address. There are three uses of bind
1. Servers register their well-known address with the system. It tells the system "this is my

REGD.N0:-21K61A6101
address and any messages received for this address are to be given to me." Both
connectionoriented and connectionless servers need to do this before accepting client
requests.
2. A client can register a specific address for itself.
3. A connectionless client needs to assure that the system assigns it some unique address, so
that the other end (the server) has a valid return address to send its responses to. This
corresponds to making certain an envelope has a valid return address, if we expect to get a
reply from the person we sent the letter to
#include<stdio.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<stdlib.h>
int main() {
int sfd; struct sockaddr_in serv_addr;
if((sfd=socket(AF_INET,SOCK_STREAM,0))<0)
{ perror("socket
error"); exit(-1);
}
serv_addr.sin_family=AF_INET; serv_addr.sin_port=htons(4890);

serv_addr.sin_addr.s_addr=inet_addr("172.16.0.1"); if((bind(sfd,(struct
sockaddr *) & serv_addr,sizeof(serv_addr)))<0)
{ perror("bind
error"); exit(-1);
}
printf("address binded...."); printf("\nserver ip address is
%s",inet_ntoa(serv_addr.sin_addr)); printf("\n port

Sasi institute of technology and engineering 8


number=%d\n",ntohs(serv_addr.sin_port)); close(sfd); return
0; }
O/P:
address binded.... server ip address
is 172.16.0.1
portnumber=4890

REGD.N0:-21K61A6101
connect
A client process connects a socket descriptor following the socket system call to establish a
connection with a server.

#include <sys/types.h>

#include <sys/socket.h>

int connect(int sockfd, struct sockaddr *servaddr, int addrlen);


The sockfd is a socket descriptor that was returned by the socket system call. The second and third
arguments are a pointer to a socket address, and its size, as described earlier. For most
connectionoriented protocols (TCP, for example), the connect system call results in the actual
establishment of a connection between the local system and the foreign system. The connect
system call does not return until the connection is established, or an error is returned to the process.
The client does not have to bind a local address before calling connect. The connection typically
causes these four elements of the association 5-tuple to be assigned: local-addr,
localprocess,foreign-addr, and foreign-process. In all the connection-oriented clients, we will let
connect assign the local address.
Accept
After a connection-oriented server executes the listen system call described above, an actual
connection from some client process is waited for by having the server execute the accept system
call.
#include <sys/types.h>
#include <sys/socket.h>
int accept(int sockfd, struct sockaddr *peer, int *addrlen);
accept takes the first connection request on the queue and creates another socket with the same
properties as sockfd. If there are no connection requests pending, this call blocks the caller until one
arrives.
The peer and addrlen arguments are used to return the address of the connected peer process (the
client). addrlen is called a value-result argument: the caller sets its value before the system call,
and the system call stores a result in the variable. For this system call the caller sets addrlen to the
size of the sockaddr structure whose address is passed as the peer argument.
send, sendto, recv and recvfrom
Sasi institute of technology and engineering 9
These system calls are similar to the standard read and write system calls, but additional arguments
are required.
#include <sys/types.h>

#include <sys/socket.h>
int send(int sockfd, char *buff, int nbytes, int flags); int sendto(int sockfd, char *buff, int
nbytes, int flags, struct sockaddr *to, int addrlen); int recv(int sockfd, char *buff, int nbytes,

REGD.N0:-21K61A6101
int flags); int recvfrom(int sockfd, char *buff, int nbytes, int flags, struct sockaddr *from, int
*addrlen);
The first three arguments, sockfd, buff, and nbytes, to the four system calls are similar to the first
three arguments for read and write. The flags argument can be safely set to zero ignoring the
details for it. The to argument for sendto specifies the protocol-specific address of where the data
is to be sent. Since this address is protocol-specific, its length must be specified by addrlen.
Therecvfrom system call fills in the protocol-specific address of who sent the data into from. The
length of this address is also returned to the caller in addrlen. Note that the final argument to
sendtois an integer value, while the final argument to recvfrom is a pointer to an integer value.
close
The normal Unix close system call is also used to close a socket.
int close(int fd);
If the socket being closed is associated with a protocol that promises reliable delivery (e.g., TCP
or SPP), the system must assure that any data within the kernel that still has to be transmitted or
acknowledged, is sent. Normally, the system returns from the close immediately, but the kernel
still tries to send any data already queued.

RESULT:

Sasi institute of technology and engineering 10


AIM:
To implement connection oriented concurrent service(TCP).

REGD.N0:-21K61A6101
Description:
The Transmission Control Protocol (TCP) is one of the core protocols of the Internet
protocol suite. It is responsible for providing reliable, ordered, and error-checked delivery
of data between applications running on different hosts. TCP is a connection-oriented
protocol, which means that it establishes a connection between two hosts before any data
is transmitted. This connection allows TCP to keep track of the order of the data packets
and to retransmit any packets that are lost or corrupted.
Server Program:
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h> int
main(int argc,char * argv[])
{
int s,s2,t,len,cp;
struct sockaddr_in
local,rem;
char str[100];
s=socket(AF_INET,SOCK_STREAM,0);
if(s==-1) {
perror("socket");
exit(1); }
bzero((char *)&local,sizeof(local));
local.sin_family=AF_INET;
local.sin_port=htons(atoi(argv[1]));
local.sin_addr.s_addr=htonl(INADDR_ANY);
if(bind(s,(struct sockaddr *)&local,sizeof(local))==-1)
{ perror(
"bind");
Sasi institute of technology and engineering 11
exit(1); }
if(listen(s,
5)==-1)
{
perror("
listen");
exit(1); }
for(;;)

REGD.N0:-21K61A6101
{ int
done,n;
printf("waiting for a connection...");
t=sizeof(rem); s2=accept(s,(struct sockaddr *)&rem,&t);
if(s2==-1) {
perror("accept");
exit(1); } printf("connecte
d");
if((cp=fork())<0 ) { perror("fork error"); } else
if(cp==0) {
close(s); done=0; do
{
n=recv(s2,str,100,0); printf("%s",str); if(n<=0)
{ if(n<0) perror("recv"); done=1; }
if(!done)
if(send(s2,str,n,0)<0) { perror("send"); done=1; }
}while(!done); exit(0); }
close(s2);
} return 0;
}
Client Program:

#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h> int main(int argc,char *argv[])
{
int s,t,len,a; struct

Sasi institute of technology and engineering 12


sockaddr_in rem; char str[100];
if(argc!=3) {
printf("valid server address");
exit(0);
}
s=socket(AF_INET,SOCK_STREAM,0);

REGD.N0:-21K61A6101
if(s==-1) {
perror("socket");
exit(1);
}
printf("connected\n");
while(printf(">"),fgets(str,100,stdin),!feof(stdin))
{ if(send(s,str,strlen(str),0)==-1)
{ perror("send");
exit(1); } if((t=recv(s,str,100,0))>0)
{
str[t]='\0';
printf("echo>%s",str);
} else { if(t<0)
perror("recv");
else
printf("server closed connection\n"); exit(1);
} } close(s);
return 0;
}

RESULT:

Sasi institute of technology and engineering 13


AIM:
To implement connectionless iterative time service(UDP);

REGD.N0:-21K61A6101
DESCRIPTION:

The User Datagram Protocol (UDP) is one of the core protocols of the Internet protocol
suite. It is a connectionless protocol, meaning that it does not establish a connection
between two hosts before data is transmitted. This makes UDP faster and more
lightweight than TCP, but it also means that UDP is less reliable. UDP does not guarantee
that data will be delivered in order or that it will be delivered at all.

UDPserver.c

#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

#include <string.h>

#include <sys/types.h>

#include <sys/socket.h>

#include <arpa/inet.h>

#include <netinet/in.h>

#define PORT 8080

#define MAXLINE 1024

int main() {

int sockfd;

char buffer[MAXLINE];

char *hello = "Hello from server";


Sasi institute of technology and engineering 14
struct sockaddr_in servaddr, cliaddr;

if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) {

perror("socket creation failed");

exit(EXIT_FAILURE);

REGD.N0:-21K61A6101
}

memset(&servaddr, 0, sizeof(servaddr));

memset(&cliaddr, 0, sizeof(cliaddr));

servaddr.sin_family = AF_INET; // IPv4

servaddr.sin_addr.s_addr = INADDR_ANY;

servaddr.sin_port = htons(PORT);

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

perror("bind failed");

exit(EXIT_FAILURE);

int len, n;

len = sizeof(cliaddr); //len is value/result

n = recvfrom(sockfd, (char *)buffer, MAXLINE, MSG_WAITALL, ( struct

sockaddr *) &cliaddr,&len);

buffer[n] = '\0';

printf("Client : %s\n", buffer);

sendto(sockfd, (const char *)hello, strlen(hello), MSG_CONFIRM, (const struct

sockaddr *) &cliaddr, len);

Sasi institute of technology and engineering 15


printf("Hello message sent.\n");

return 0;

UDPclient:

REGD.N0:-21K61A6101
#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

#include <string.h>

#include <sys/types.h>

#include <sys/socket.h>

#include <arpa/inet.h>

#include <netinet/in.h>

#define PORT 8080

#define MAXLINE 1024

int main() {

int sockfd;

char buffer[MAXLINE];

char *hello = "Hello from client";

struct sockaddr_in servaddr;

if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) {

perror("socket creation failed");

exit(EXIT_FAILURE);

Sasi institute of technology and engineering 16


memset(&servaddr, 0, sizeof(servaddr));

servaddr.sin_family = AF_INET;

servaddr.sin_port = htons(PORT);

servaddr.sin_addr.s_addr = INADDR_ANY;

REGD.N0:-21K61A6101
int n, len;

sendto(sockfd, (const char *)hello, strlen(hello),

MSG_CONFIRM, (const struct sockaddr *) &servaddr,

sizeof(servaddr));

printf("Hello message sent.\n");

n = recvfrom(sockfd, (char *)buffer, MAXLINE,

MSG_WAITALL, (struct sockaddr *) &servaddr,&len);

buffer[n] = '\0';

printf("Server : %s\n", buffer);

close(sockfd);

return 0;

RESULT:

Sasi institute of technology and engineering 17


AIM:

REGD.N0:-21K61A6101
To implement system call.

DESCRIPTION:

System calls are typically implemented using a system call table (SCT), which is an array
of pointers to functions that implement the system calls. When an application makes a
system call, it provides an identifier that corresponds to the index of the function in the
system call table. The kernel then calls the appropriate function to handle the request.

PROGRAM:

#include <stdio.h>

#include <sys/time.h>

#include <sys/types.h>

#include <unistd.h>

int main(void) {

fd_set rfds;

struct timeval tv;

int retval;

FD_ZERO(&rfds);

FD_SET(0, &rfds);

/* Wait up to five seconds. */

tv.tv_sec = 5;

tv.tv_usec = 0;

retval = select(1, &rfds, NULL, NULL, &tv);

Sasi institute of technology and engineering 18


/* Don’t rely on the value of tv now! */

if (retval == -1)

perror("select()");

else if (retval)

REGD.N0:-21K61A6101
printf("Data is available now.\n");

/* FD_ISSET(0, &rfds) will be true. */

else

printf("No data within five seconds.\n");

return 0;

RESULT:

Sasi institute of technology and engineering 19


AIM:

REGD.N0:-21K61A6101
To implement getsockopt(), setsockopt() system calls

DESCRIPTION:

Getsockopt and setsockopt manipulate the options associated with a socket. Options may exist at
multiple protocol levels; they are always present at the uppermost socket level. When
manipulating socket options the level at which the option resides and the name of the option must
be specified. To manipulate options at the socket level, level is specified as SOL_SOCKET. To
manipulate options at any other level the protocol number of the appropriate protocol controlling
the option is supplied

Server.c

#include <stdio.h>

#include <string.h>

#include <unistd.h>

#include <netdb.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <arpa/inet.h>

int main() {

struct sockaddr_in saddr,caddr;

socklen_t clen;

int sock, csock, reuse = 1, ret=0;

socklen_t ntrcv, ntsnd;

struct timeval tout, tsnd, trcv;

Sasi institute of technology and engineering 20


if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) perror("failed to create socket");

else {

if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0)

perror("failed allowing server socket to reuse address");

REGD.N0:-21K61A6101
else {

// set up the server address

memset((char *) &saddr, 0, sizeof(saddr));

saddr.sin_family = AF_INET;

saddr.sin_addr.s_addr = inet_addr("127.0.0.1");

saddr.sin_port = htons(45454);

if (bind(sock, (struct sockaddr *) &saddr, sizeof(saddr)) < 0) perror("failed to bind");

else {

if (listen(sock,5) < 0) perror("failed to listen");

else {

clen = sizeof(caddr);

if ((csock = accept(sock, (struct sockaddr *) &caddr, &clen)) < 0) perror("failed to

accept");

else {

tout.tv_sec=0;

tout.tv_usec=10000;

perror("errno prior to timeout");

if (getsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &trcv, &ntrcv) < 0) perror("2");

else if (getsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tsnd, &ntsnd) < 0) perror("3");

Sasi institute of technology and engineering 21


else if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tout, sizeof(tout)) < 0)
perror("4");

else if (setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tout, sizeof(tout)) < 0)


perror("5");

else {

REGD.N0:-21K61A6101
printf ("all ok so far in server\n");

sleep(1);

if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &trcv, ntrcv) < 0) perror("6");

else if (setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tsnd, ntsnd) < 0) perror("7");

if (close(csock) < 0) perror("failed to close csock");

if (close(sock) < 0) perror("failed to close sock");

return ret;

Client.c:

#include <stdio.h>

#include <string.h>

#include <unistd.h>

#include <netdb.h>

Sasi institute of technology and engineering 22


#include <sys/socket.h>

#include <netinet/in.h>

#include <arpa/inet.h>

int main() {

REGD.N0:-21K61A6101
struct sockaddr_in addr;

struct hostent *server;

int sock = 0;

if (!(server = gethostbyname("127.0.0.1"))) perror("failed to resolve host");

else {

memset((char *) &addr, 0, sizeof(addr));

addr.sin_family = AF_INET;

bcopy((char *)server->h_addr, (char *)&addr.sin_addr.s_addr, server->h_length);

addr.sin_port = htons(45454);

if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) perror("failed to create client

socket");

else {

if (connect(sock,(struct sockaddr *) &addr,sizeof(addr)) < 0) perror("failed to connect to

server");

else {

printf("Connection is established will sleep now\n");

sleep(3);

printf("done sleeping\n");

close(sock);

Sasi institute of technology and engineering 23


printf("socket is closed\n");

REGD.N0:-21K61A6101
return 0;

RESULT:

Sasi institute of technology and engineering 24


AIM:
To implement of getpeername() system call.

REGD.N0:-21K61A6101
DESCRIPTION:
Getpeername returns the name of the peer connected to socket s. The namelen parameter should
be initialized to indicate the amount of space pointed to by name. On return it contains the actual
size of the name returned(in bytes). The name is truncated if the buffer provided is too small.
Server.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
void error_handling(char *message);
int main(int argc, char *argv[])
{
int serv_sock;
int clnt_sock;
struct sockaddr_in serv_addr;
struct sockaddr_in clnt_addr;
socklen_t clnt_addr_size;
char message[]="Hello World!";
if(argc!=2){
printf("Usage : %s <port>\n", argv[0]);
exit(1);
}
serv_sock=socket(PF_INET, SOCK_STREAM, 0);

Sasi institute of technology and engineering 25


if(serv_sock == -1)
error_handling("socket() error");
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=htonl(INADDR_ANY);

REGD.N0:-21K61A6101
serv_addr.sin_port=htons(atoi(argv[1]));
if(bind(serv_sock, (struct sockaddr*) &serv_addr, sizeof(serv_addr))==-1 )
error_handling("bind() error");
if(listen(serv_sock, 5)==-1)
error_handling("listen() error");
clnt_addr_size=sizeof(clnt_addr);
clnt_sock=accept(serv_sock, (struct sockaddr*)&clnt_addr,&clnt_addr_size);
if(clnt_sock==-1)
error_handling("accept() error");
write(clnt_sock, message, sizeof(message));
struct sockaddr_in addr1;
struct sockaddr_in addr2;
struct sockaddr_in addr3;
struct sockaddr_in addr4;
socklen_t serv_len = sizeof(serv_addr);
int serv_peer_err = getpeername(serv_sock, (struct sockaddr *)&addr1, &serv_len);
int clnt_peer_err = getpeername(clnt_sock, (struct sockaddr *)&addr2, &clnt_addr_size);
int serv_sock_err = getsockname(serv_sock, (struct sockaddr *)&addr3, &serv_len);
int clnt_sock_err = getsockname(clnt_sock, (struct sockaddr *)&addr4, &clnt_addr_size);
printf("Server socket's ip : %s\n", inet_ntoa(addr3.sin_addr));
printf("Server socket's port : %d\n", ntohs(addr3.sin_port));
printf("Server socket's peer ip : %s\n", inet_ntoa(addr1.sin_addr));
printf("Server socket's peer port : %d\n\n\n\n\n\n", ntohs(addr1.sin_port));
printf("Client socket's ip : %s\n", inet_ntoa(addr4.sin_addr));
printf("Client socket's port : %d\n", ntohs(addr4.sin_port));

Sasi institute of technology and engineering 26


printf("Client socket's peer ip : %s\n", inet_ntoa(addr2.sin_addr));
printf("client socket's peer port %d\n", ntohs(addr2.sin_port));
printf("%d %d %d %d\n", serv_peer_err, clnt_peer_err, serv_sock_err, clnt_sock_err);
close(clnt_sock);
close(serv_sock);

REGD.N0:-21K61A6101
return 0;
}
void error_handling(char *message)
{
fputs(message, stderr);
fputc('\n', stderr);
exit(1);
}
Client.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
void error_handling(char *message);
int main(int argc, char* argv[])
{
int sock;
struct sockaddr_in serv_addr;
char message[30];
int str_len;
if(argc!=3){
printf("Usage : %s <IP> <port>\n", argv[0]);
exit(1);

Sasi institute of technology and engineering 27


}
sock=socket(PF_INET, SOCK_STREAM, 0);
if(sock == -1)
error_handling("socket() error");
memset(&serv_addr, 0, sizeof(serv_addr));

REGD.N0:-21K61A6101
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=inet_addr(argv[1]);
serv_addr.sin_port=htons(atoi(argv[2]));
if(connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr))==-1)
error_handling("connect() error!");
str_len=read(sock, message, sizeof(message)-1);
if(str_len==-1)
error_handling("read() error!");
struct sockaddr_in addr1;
struct sockaddr_in addr2;
int clnt_sock_err, clnt_peer_err;
socklen_t serv_len = sizeof(serv_addr);
clnt_peer_err = getpeername(sock, (struct sockaddr *)&addr1, &serv_len);
clnt_sock_err = getsockname(sock, (struct sockaddr *)&addr2, &serv_len);
printf("Client socket's ip : %s\n", inet_ntoa(addr2.sin_addr));
printf("client socket's port %d\n", ntohs(addr2.sin_port));
printf("Client socket's peer ip : %s\n", inet_ntoa(addr1.sin_addr));
printf("Client socket's peer port : %d\n", ntohs(addr1.sin_port));
printf("%d %d\n", clnt_sock_err, clnt_peer_err);
printf("Message from server: %s \n", message);
close(sock);
return 0;
}
void error_handling(char *message)
{

Sasi institute of technology and engineering 28


fputs(message, stderr);
fputc('\n', stderr);
exit(1);
}

REGD.N0:-21K61A6101

RESULT:

Sasi institute of technology and engineering 29


AIM:
To Implementation of remote command execution using socket system calls

REGD.N0:-21K61A6101
DESCRIPTION:
Remote command execution (RCE) is a security vulnerability that allows an attacker to
execute arbitrary commands on a remote system. This vulnerability can be exploited to
gain unauthorized access to the system, steal data, or install malware.One common way
to implement RCE is using socket system calls. Sockets are a mechanism for inter-
process communication (IPC) that allows processes to communicate with each other over
a network. Socket system calls can be used to create a socket, bind it to an address, listen
for incoming connections, accept connections, and send and receive data

Server.c:

#include <sys/types.h>

#include <sys/socket.h>

#include <stdio.h>

#include <stdlib.h>

#include <netdb.h>

#include <netinet/in.h>

#include <string.h>

#include <sys/stat.h>

#include <arpa/inet.h>

#include <unistd.h>

#define MAX 1000

int main()

Sasi institute of technology and engineering 30


int serverDescriptor = socket(AF_INET, SOCK_DGRAM, 0);

int size;

char buffer[MAX], message[] = "Command Successfully executed !";

struct sockaddr_in clientAddress, serverAddress;

REGD.N0:-21K61A6101
socklen_t clientLength = sizeof(clientAddress);

bzero(&serverAddress, sizeof(serverAddress));

serverAddress.sin_family = AF_INET;

serverAddress.sin_addr.s_addr = htonl(INADDR_ANY);

serverAddress.sin_port = htons(9976);

bind(serverDescriptor, (struct sockaddr *)&serverAddress, sizeof(serverAddress));

while (1)

bzero(buffer, sizeof(buffer));

recvfrom(serverDescriptor, buffer, sizeof(buffer), 0, (struct sockaddr *)&clientAddress,

&clientLength);

system(buffer);

printf("Command Executed ... %s ", buffer);

sendto(serverDescriptor, message, sizeof(message), 0, (struct sockaddr *)&clientAddress,

clientLength);

close(serverDescriptor);

return 0;

Sasi institute of technology and engineering 31


Client.c:

#include <sys/types.h>

#include <sys/socket.h>

#include <stdio.h>

REGD.N0:-21K61A6101
#include <unistd.h>

#include <netdb.h>

#include <netinet/in.h>

#include <string.h>

#include <arpa/inet.h>

#define MAX 1000

int main()

int serverDescriptor = socket(AF_INET, SOCK_DGRAM, 0);

char buffer[MAX], message[MAX];

struct sockaddr_in cliaddr, serverAddress;

socklen_t serverLength = sizeof(serverAddress);

bzero(&serverAddress, sizeof(serverAddress));

serverAddress.sin_family = AF_INET;

serverAddress.sin_addr.s_addr = inet_addr("127.0.0.1");

serverAddress.sin_port = htons(9976);

bind(serverDescriptor, (struct sockaddr *)&serverAddress, sizeof(serverAddress));

while (1)

Sasi institute of technology and engineering 32


printf("\nCOMMAND FOR EXECUTION ... ");

fgets(buffer, sizeof(buffer), stdin);

sendto(serverDescriptor, buffer, sizeof(buffer), 0, (struct sockaddr *)&serverAddress,

serverLength);

REGD.N0:-21K61A6101
printf("\nData Sent !");

recvfrom(serverDescriptor, message, sizeof(message), 0, (struct sockaddr


*)&serverAddress,

&serverLength);

printf("UDP SERVER : %s", message);

return 0;

RESULT:

Sasi institute of technology and engineering 33


AIM:

REGD.N0:-21K61A6101
To implement of Distance vector routing algorithm

DESCRIPTION:

The Distance Vector Routing Algorithm (DVRA), also known as the Bellman-Ford algorithm,
is a routing protocol used in computer networks to determine the best path for data
packets to travel. It is a distributed algorithm, meaning that each router in the network
maintains its own routing table and periodically exchanges this information with its
neighbors.

PROGRAM:

import java.io.*;

public class DVR

static int graph[][];

static int via[][];

static int rt[][];

static int v;

static int e;

public static void main(String args[]) throws IOException

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

System.out.println("Please enter the number of Vertices: ");

v = Integer.parseInt(br.readLine());
Sasi institute of technology and engineering 34
System.out.println("Please enter the number of Edges: ");

e = Integer.parseInt(br.readLine());

graph = new int[v][v];

via = new int[v][v];

REGD.N0:-21K61A6101
rt = new int[v][v];

for(int i = 0; i < v; i++)

for(int j = 0; j < v; j++)

if(i == j)

graph[i][j] = 0;

else

graph[i][j] = 9999;

for(int i = 0; i < e; i++)

System.out.println("Please enter data for Edge " + (i + 1) + ":");

System.out.print("Source: ");

int s = Integer.parseInt(br.readLine());

s--;

System.out.print("Destination: ");

int d = Integer.parseInt(br.readLine());

d--;

System.out.print("Cost: ");

Sasi institute of technology and engineering 35


int c = Integer.parseInt(br.readLine());

graph[s][d] = c;

graph[d][s] = c;

REGD.N0:-21K61A6101
dvr_calc_disp("The initial Routing Tables are: ");

System.out.print("Please enter the Source Node for the edge whose cost has changed: ");

int s = Integer.parseInt(br.readLine());

s--;

System.out.print("Please enter the Destination Node for the edge whose cost has
changed: ");

int d = Integer.parseInt(br.readLine());

d--;

System.out.print("Please enter the new cost: ");

int c = Integer.parseInt(br.readLine());

graph[s][d] = c;

graph[d][s] = c;

dvr_calc_disp("The new Routing Tables are: ");

static void dvr_calc_disp(String message)

System.out.println();

init_tables();

update_tables();

System.out.println(message);
Sasi institute of technology and engineering 36
print_tables();

System.out.println();

static void update_table(int source)

REGD.N0:-21K61A6101
{

for(int i = 0; i < v; i++)

if(graph[source][i] != 9999)

int dist = graph[source][i];

for(int j = 0; j < v; j++)

int inter_dist = rt[i][j];

if(via[i][j] == source)

inter_dist = 9999;

if(dist + inter_dist < rt[source][j])

rt[source][j] = dist + inter_dist;

via[source][j] = i;

Sasi institute of technology and engineering 37


}

static void update_tables()

int k = 0;

REGD.N0:-21K61A6101
for(int i = 0; i < 4*v; i++)

update_table(k);

k++;

if(k == v)

k = 0;

static void init_tables()

for(int i = 0; i < v; i++)

for(int j = 0; j < v; j++)

if(i == j)

rt[i][j] = 0;

via[i][j] = i;

Sasi institute of technology and engineering 38


else

rt[i][j] = 9999;

via[i][j] = 100;

REGD.N0:-21K61A6101
}

static void print_tables()

for(int i = 0; i < v; i++)

for(int j = 0; j < v; j++)

System.out.print("Dist: " + rt[i][j] + " ");

System.out.println();

RESULT:

Sasi institute of technology and engineering 39


AIM:

REGD.N0:-21K61A6101
To implement of SMTP.

ALGORITHM:

1. Start the SMTP program

2. Import the package javax.mail .*; and java.mail.internet.*;

3. Using the following function send the message

InternetAddress("XXXXXX", "XXXXX");

4. InternetAddress() is used for set the address msg.setContent("Wish You a Happy


Christmas

2008", "text/plain");

5. Msg.setconet() it is used to set the content

6. msg.setRecipient(Message.RecipientType.TO, bhuvangates);//set the message


Recipient

7. msg.setSubject("Greetings");-set the subject of the message

8. Transport.send(msg);-transport the message

9. Finally the terminate the SMTP Program

PROGRAM:

import java.util.Properties;

import javax.mail.Message;

import javax.mail.MessagingException;

import javax.mail.Session;

Sasi institute of technology and engineering 40


import javax.mail.Transport;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeMessage;

public class SendMailImpl {

REGD.N0:-21K61A6101
private String smtpHost = "localhost";

public void sendMessage(String from, String[] recipients, String subject, String message)

throws MessagingException {

boolean debug = false;

//Set the host smtp address

Properties props = new Properties();

props.put("mail.smtp.host", smtpHost);

// create some properties and get the default Session

Session session = Session.getDefaultInstance(props, null);

session.setDebug(debug);

// create a message

Message msg = new MimeMessage(session);

// set the from and to address

InternetAddress addressFrom = new InternetAddress(from);

msg.setFrom(addressFrom);

InternetAddress[] addressTo = new InternetAddress[recipients.length];

for (int i = 0; i < recipients.length; i++) {

addressTo[i] = new InternetAddress(recipients[i]);

Sasi institute of technology and engineering 41


msg.setRecipients(Message.RecipientType.TO, addressTo);

// Setting the Subject and Content Type

msg.setSubject(subject);

msg.setContent(message, "text/html");

REGD.N0:-21K61A6101
Transport.send(msg);

public String getSmtpHost() {

return smtpHost;

public void setSmtpHost(String smtpHost) {

this.smtpHost = smtpHost;

RESULT:

Sasi institute of technology and engineering 42


AIM:

REGD.N0:-21K61A6101
To implementation of FTP

ALGORITHM:

1. Start the server starts and waits for filename.

2. The client sends a filename.

3. The server receives filename. If file is present, server starts reading file and continues to
send

a buffer filled with file contents encrypted until file-end is reached.

4. End is marked by EOF.

5. File is received as buffers until EOF is received. Then it is decrypted.

6. If Not present, a file not found is sent.

FTPclient.java:

import java.net.*;

import java.io.*;

import java.util.*;

class FTPClient

publicstaticvoid main(String args[]) throws Exception

Socket soc=new Socket("127.0.0.1",5217);

transferfileClient t=new transferfileClient(soc);


Sasi institute of technology and engineering 43
t.displayMenu();

class transferfileClient

REGD.N0:-21K61A6101
{

Socket ClientSoc;

DataInputStream din;

DataOutputStream dout;

BufferedReader br;

transferfileClient(Socket soc)

try

ClientSoc=soc;

din=new DataInputStream(ClientSoc.getInputStream());

dout=new DataOutputStream(ClientSoc.getOutputStream());

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

catch(Exception ex)

void SendFile() throws Exception

Sasi institute of technology and engineering 44


{

String filename;

System.out.print("Enter File Name :");

filename=br.readLine();

REGD.N0:-21K61A6101
File f=new File(filename);

if(!f.exists())

System.out.println("File not Exists...");

dout.writeUTF("File not found");

return;

dout.writeUTF(filename);

String msgFromServer=din.readUTF();

if(msgFromServer.compareTo("File Already Exists")==0)

String Option;

System.out.println("File Already Exists. Want to OverWrite (Y/N) ?");

Option=br.readLine();

if(Option=="Y")

dout.writeUTF("Y");

Sasi institute of technology and engineering 45


else

dout.writeUTF("N");

return;

REGD.N0:-21K61A6101
}

System.out.println("Sending File ...");

FileInputStream fin=new FileInputStream(f);

int ch;

do

ch=fin.read();

dout.writeUTF(String.valueOf(ch));

while(ch!=-1);

fin.close();

System.out.println(din.readUTF());

void ReceiveFile() throws Exception

String fileName;

System.out.print("Enter File Name :");

fileName=br.readLine();

Sasi institute of technology and engineering 46


dout.writeUTF(fileName);

String msgFromServer=din.readUTF();

if(msgFromServer.compareTo("File Not Found")==0)

REGD.N0:-21K61A6101
System.out.println("File not found on Server ...");

return;

elseif(msgFromServer.compareTo("READY")==0)

System.out.println("Receiving File ...");

File f=new File(fileName);

if(f.exists())

String Option;

System.out.println("File Already Exists. Want to OverWrite (Y/N) ?");

Option=br.readLine();

if(Option=="N")

dout.flush();

return;

FileOutputStream fout=new FileOutputStream(f);

Sasi institute of technology and engineering 47


int ch;

String temp;

do

REGD.N0:-21K61A6101
temp=din.readUTF();

ch=Integer.parseInt(temp);

if(ch!=-1)

fout.write(ch);

}while(ch!=-1);

fout.close();

System.out.println(din.readUTF());

publicvoid displayMenu() throws Exception

while(true)

System.out.println("[ MENU ]");

System.out.println("1. Send File");

System.out.println("2. Receive File");

System.out.println("3. Exit");

Sasi institute of technology and engineering 48


System.out.print("\nEnter Choice :");

int choice;

choice=Integer.parseInt(br.readLine());

if(choice==1)

REGD.N0:-21K61A6101
{

dout.writeUTF("SEND");

SendFile();

elseif(choice==2)

dout.writeUTF("GET");

ReceiveFile();

else

dout.writeUTF("DISCONNECT");

System.exit(1);

FTPserver.java:

import java.net.*;

Sasi institute of technology and engineering 49


import java.io.*;

import java.util.*;

class FTPClient

REGD.N0:-21K61A6101
publicstaticvoid main(String args[]) throws Exception

Socket soc=new Socket("127.0.0.1",5217);

transferfileClient t=new transferfileClient(soc);

t.displayMenu();

class transferfileClient

Socket ClientSoc;

DataInputStream din;

DataOutputStream dout;

BufferedReader br;

transferfileClient(Socket soc)

try

ClientSoc=soc;

din=new DataInputStream(ClientSoc.getInputStream());

Sasi institute of technology and engineering 50


dout=new DataOutputStream(ClientSoc.getOutputStream());

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

catch(Exception ex)

REGD.N0:-21K61A6101
{

void SendFile() throws Exception

String filename;

System.out.print("Enter File Name :");

filename=br.readLine();

File f=new File(filename);

if(!f.exists())

System.out.println("File not Exists...");

dout.writeUTF("File not found");

return;

dout.writeUTF(filename);

String msgFromServer=din.readUTF();

if(msgFromServer.compareTo("File Already Exists")==0)

Sasi institute of technology and engineering 51


String Option;

System.out.println("File Already Exists. Want to OverWrite (Y/N) ?");

Option=br.readLine();

if(Option=="Y")

REGD.N0:-21K61A6101
{

dout.writeUTF("Y");

else

dout.writeUTF("N");

return;

System.out.println("Sending File ...");

FileInputStream fin=new FileInputStream(f);

int ch;

do

ch=fin.read();

dout.writeUTF(String.valueOf(ch));

while(ch!=-1);

fin.close();

Sasi institute of technology and engineering 52


System.out.println(din.readUTF());

void ReceiveFile() throws Exception

REGD.N0:-21K61A6101
String fileName;

System.out.print("Enter File Name :");

fileName=br.readLine();

dout.writeUTF(fileName);

String msgFromServer=din.readUTF();

if(msgFromServer.compareTo("File Not Found")==0)

System.out.println("File not found on Server ...");

return;

elseif(msgFromServer.compareTo("READY")==0)

System.out.println("Receiving File ...");

File f=new File(fileName);

if(f.exists())

String Option;

System.out.println("File Already Exists. Want to OverWrite (Y/N) ?");

Option=br.readLine();

Sasi institute of technology and engineering 53


if(Option=="N")

dout.flush();

return;

REGD.N0:-21K61A6101
}

FileOutputStream fout=new FileOutputStream(f);

int ch;

String temp;

do

temp=din.readUTF();

ch=Integer.parseInt(temp);

if(ch!=-1)

fout.write(ch);

}while(ch!=-1);

fout.close();

System.out.println(din.readUTF());

publicvoid displayMenu() throws Exception

Sasi institute of technology and engineering 54


{

while(true)

System.out.println("[ MENU ]");

REGD.N0:-21K61A6101
System.out.println("1. Send File");

System.out.println("2. Receive File");

System.out.println("3. Exit");

System.out.print("\nEnter Choice :");

int choice;

choice=Integer.parseInt(br.readLine());

if(choice==1)

dout.writeUTF("SEND");

SendFile();

elseif(choice==2)

dout.writeUTF("GET");

ReceiveFile();

else

dout.writeUTF("DISCONNECT");

Sasi institute of technology and engineering 55


System.exit(1);

REGD.N0:-21K61A6101
}

RESULT:

Sasi institute of technology and engineering 56


AIM:

REGD.N0:-21K61A6101
To implementation of HTTP

ALGORITHM:

1. Open the Server Socket: ServerSocket server = new ServerSocket( PORT );

2. Wait for the Client Request: Socket client = server.accept();

3. Create I/O streams for communicating to the client

DataInputStream is = new DataInputStream(client.getInputStream());

DataOutputStream os = new DataOutputStream(client.getOutputStream());

4. Perform communication with client Receive from client:

String line = is.readLine();

Send to client: os.writeBytes( Hello\n );

5. Close socket:

client.close();

server.java:

import java.net.*;

import java.io.*;

public class SimpleServer {

public static void main(String args[]) throws IOException

// Register service on port 1254


Sasi institute of technology and engineering 57
ServerSocket s = new ServerSocket(1254);

Socket s1=s.accept();

// Wait and accept a connection

// Get a communication stream associated with the

REGD.N0:-21K61A6101
socket OutputStream s1out = s1.getOutputStream();

DataOutputStream dos = new DataOutputStream (s1out);

dos.writeUTF( Hi there ); // Close the connection, but not the server socket

dos.close();

s1out.close();

s1.close(); } }

client.java:

import java.net.*;

import java.io.*;

public class SimpleClient {

public static void main(String args[]) throws IOException

{ // Open your connection to a server, at port 1254

Socket s1 = new Socket( localhost ,1254);

// Get an input file handle from the socket and read the input

InputStream s1In = s1.getInputStream();

DataInputStream dis = new DataInputStream(s1In);

String st = new String (dis.readUTF());

System.out.println(st);

Sasi institute of technology and engineering 58


// When done, just close the connection and exit

dis.close();

s1In.close();

s1.close();

REGD.N0:-21K61A6101
}

RESULT:

Sasi institute of technology and engineering 59


AIM:

To implement of RSA Algorithm.

REGD.N0:-21K61A6101
ALGORITHM:

INPUT: Required modulus bit length, kk.


OUTPUT: An RSA key pair ((N,e),d)((N,e),d) where N is the modulus, the product of two primes
(N=pqN=pq) not exceeding kk bits in length; ee is the public exponent, a number less than and
coprime to (p−1)(q−1)(p−1)(q−1); and dd is the private exponent such that
ed≡1mod(p−1)(q−1)ed≡1mod(p−1)(q−1).

Select a value of ee from 3,5,17,257,655373,5,17,257,65537

repeat

p ← genprime(k/2)

until (pmode)≠1(pmode)≠1

repeat

q ← genprime(k - k/2)

until (qmode)≠1(qmode)≠1

N ← pq

L ← (p-1)(q-1)

d ← modinv(e, L)

return (N,e,d)

PROGRAM:

import java.io.DataInputStream;

import java.io.IOException;

import java.math.BigInteger;
Sasi institute of technology and engineering 60
import java.util.Random;

public class RSA

private BigInteger p;

REGD.N0:-21K61A6101
private BigInteger q;

private BigInteger N;

private BigInteger phi;

private BigInteger e;

private BigInteger d;

private int bitlength = 1024;

private Random r;

public RSA()

r = new Random();

p = BigInteger.probablePrime(bitlength, r);

q = BigInteger.probablePrime(bitlength, r);

N = p.multiply(q);

phi = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));

e = BigInteger.probablePrime(bitlength / 2, r);

while (phi.gcd(e).compareTo(BigInteger.ONE) > 0 && e.compareTo(phi) < 0)

e.add(BigInteger.ONE);

Sasi institute of technology and engineering 61


}

d = e.modInverse(phi);

public RSA(BigInteger e, BigInteger d, BigInteger N)

REGD.N0:-21K61A6101
{

this.e = e;

this.d = d;

this.N = N;

@SuppressWarnings("deprecation")

public static void main(String[] args) throws IOException{

RSA rsa = new RSA();

DataInputStream in = new DataInputStream(System.in);

String teststring;

System.out.println("Enter the plain text:");

teststring = in.readLine();

System.out.println("Encrypting String: " + teststring);

System.out.println("String in Bytes: " + bytesToString(teststring.getBytes()));

byte[] encrypted = rsa.encrypt(teststring.getBytes());

byte[] decrypted = rsa.decrypt(encrypted);

System.out.println("Decrypting Bytes: " + bytesToString(decrypted));

System.out.println("Decrypted String: " + new String(decrypted));

Sasi institute of technology and engineering 62


}

private static String bytesToString(byte[] encrypted)

String test = "";

REGD.N0:-21K61A6101
for (byte b : encrypted){

test += Byte.toString(b);

return test;

public byte[] encrypt(byte[] message){

return (new BigInteger(message)).modPow(e, N).toByteArray();

public byte[] decrypt(byte[] message){

return (new BigInteger(message)).modPow(d, N).toByteArray();

RESULT:

Sasi institute of technology and engineering 63

You might also like