Download as pdf or txt
Download as pdf or txt
You are on page 1of 41

Program 1: Understanding and using of commands like ifconfig, netstat, ping,

arp, telnet, ftp, finger, traceroute, whoisetc. Usage of elementary socket


system calls (socket (), bind(), listen(),
accept(),connect(),send(),recv(),sendto(),recvfrom())..

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
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
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 <FQDN> 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.

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 “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.

1
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.
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

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 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.
FINGER:
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.

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.

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.

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").

2
2. Implementation of Connection oriented concurrent service (TCP).
Client Program:

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include<netinet/in.h>
#include <arpa/inet.h>
main(int argc, char *argv[])
{
int sockfd, rval;
char buff1[20],buff2[20];
struct sockaddr_in server, client;
int len;
sockfd=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(sockfd==-1)
{
perror("\n SOCK_ERR\n");
exit(1);
}
server.sin_family=AF_INET;
server.sin_addr.s_addr=inet_addr("10.2.1.254");
server.sin_port=htons(3339);
rval=connect(sockfd,(struct sockaddr *)&server, sizeof(server));
if(rval!=-1)
{
printf("\n enter a message \n");
scanf("%s", buff1);
rval=send(sockfd,buff1,sizeof(buff1),0);
if(rval==-1)
{
perror("\n SEND_ERR\n");
exit(1);
}
rval=recv(sockfd,buff2,sizeof(buff2),0);
if(rval!=-1)
{
printf("\n Received message is %s \n", buff2);
}
else
3
{
perror("\nRECV_ERR\n");
exit(1);
}
}

Server Program:

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
main(int argc, char *argv[])
{
int sockfd,new_sockfd,rval,pid;
char buff1[20],buff2[20];
struct sockaddr_in server, client;
int len;
sockfd=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(sockfd==-1)
{
perror("\n SOCK_ERR\n");
exit(1);
}
server.sin_family=AF_INET;
server.sin_addr.s_addr=inet_addr("10.2.1.254");
server.sin_port=htons(3339);
rval=bind(sockfd,(struct sockaddr*)&server,sizeof(server));
if(rval!=-1)
{
listen(sockfd,5);
while(1)
{
new_sockfd=accept(sockfd,(struct sockaddr*)&client,&len);
if(new_sockfd!=-1)
{
pid=fork();
if(pid==0)
{
printf("\n child process executing \n");
printf("\n child process is is %d", getpid());
len=sizeof(server);
4
rval=recv(new_sockfd, buff1,sizeof(buff1),0);
if(rval==-1)
{
perror("\n RECV_ERR\n");
exit(1);
}
else
{
printf("\n received message is %s\n", buff1);
}
rval=send(new_sockfd,buff1,sizeof(buff1),0);
if(rval!=-1)
{
printf("\n message sent successfully \n");
}
else
{
perror("\nSEND_ERR\n");
exit(1);
}
}
else
{
printf("\n parent process\n");
printf("parent process id is %d \n", getppid());
exit(1);
}
}
else
{
perror("\n ACCEPT_ERR\n");
exit(1);
}
}
}
else
{
perror("\nBIND_ERR\n");
close(sockfd);
}
}

5
OUTPUT

6
3. Implementation of Connectionless Iterative time service (UDP)
Sever 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;
struct sockaddr_in local,remote;
char str[100];
if(argc!=2)
{
printf("usage:server<port>");
exit(0);
}
if((s=socket(AF_INET,SOCK_DGRAM,0))==-1)
{
perror("socket");
exit(1);
}
bzero((char *)&local,sizeof(local));
local.sin_family=AF_INET;
local.sin_port=htons((short)atoi(argv[1]));
local.sin_addr.s_addr=htonl(INADDR_ANY);
if(bind(s,(struct sockaddr*)&local,sizeof(local))==-1)
{
perror("bind");
exit(1);
}
t=sizeof(remote);
memset(str,0,100);
for(;;)
{
int n;
while((n=recvfrom(s,str,100,0,(structsockaddr *)&remote,&t))>0)
{
printf("%s",str);
7
if(sendto(s,str,n,0,(structsockaddr*)&remote,sizeof(remote))<0)
{
perror("send to");
}
memset(str,0,100);
}
if(n<0)
{
perror("recv from");
exit(0);
}
}
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;
struct sockaddr_in local,remote;
char str[100];
if(argc!=3)
{
printf("\n usage:client<servwer-address><port>");
exit(0);
}
if((s=socket(AF_INET,SOCK_DGRAM,0))==-1)
{
perror("socket");
exit(1);
}
bzero((char *)&local,sizeof(local));
local.sin_family=AF_INET;
local.sin_port=htons(7658);
8
local.sin_addr.s_addr=inet_addr(argv[1]);

if(bind(s,(struct sockaddr *)&local,sizeof(local))==-1)


{
perror("bind");
exit(1);
}
bzero((char *)&remote,sizeof(remote));
remote.sin_family=AF_INET;
remote.sin_port=htons((short)atoi(argv[2]));
remote.sin_addr.s_addr=inet_addr(argv[1]);
t=sizeof(remote);
while(printf(">"),fgets(str,100,stdin),!feof(stdin))
{
int n;

if(sendto(s,str,strlen(str),0,(structsockaddr*)&remote,sizeof(remote))<0)
{
perror("send");
exit(1);
}

9
OUTPUT
Server side:

Client side:

10
4. Implementation of Select system call.

Server Program:

#include<stdio.h>
#include<netinet/in.h>
#include<sys/types.h>
#include<string.h>
#include<stdlib.h>
#include<sys/socket.h>
#include<sys/select.h>
#include<unistd.h>
#define MAXLINE 20
#define SERV_PORT 7134
main(int argc,char **argv) {
int i,j,maxi,maxfd,listenfd,connfd,sockfd;
int nread,client[FD_SETSIZE];
ssize_t n; fd_set rset,allset;
char line[MAXLINE];
socklen_t clilen;
struct sockaddr_in cliaddr,servaddr;
listenfd=socket(AF_INET,SOCK_STREAM,0);
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(SERV_PORT);
bind(listenfd,(struct sockaddr *)&servaddr,sizeof(servaddr));
listen(listenfd,1);
maxfd=listenfd; maxi=-1;
for(i=0;i<FD_SETSIZE;i++)
client[i]=-1;
FD_ZERO(&allset);
FD_SET(listenfd,&allset);
for(; ;) {
rset=allset;
nread=select(maxfd+1,&rset,NULL,NULL,NULL);
if(FD_ISSET(listenfd,&rset)) {
clilen=sizeof(cliaddr);
connfd=accept(listenfd,(struct sockaddr*)&cliaddr,&clilen);
for(i=0;i<FD_SETSIZE;i++)
if(client[i]<0) {
11
client[i]=connfd;
break;
}
if(i==FD_SETSIZE)
{
printf("too many clients");
exit(0);
}
FD_SET(connfd,&allset);
if(connfd>maxfd)
maxfd=connfd;
if(i>maxi)
maxi=i;
if(--nread<=0)
continue; }
for(i=0;i<=maxi;i++) {
if((sockfd=client[i])<0)
continue;
if(FD_ISSET(sockfd,&rset)) {
if((n=read(sockfd,line,MAXLINE))==0)
{
close(sockfd);
FD_CLR(sockfd,&allset);
client[i]=-1;
}
else
{
printf("line recieved from the client :%s\n",line);
for(j=0;line[j]!='\0';j++)
line[j]=toupper(line[j]);
write(sockfd,line,MAXLINE); }
if(--nread<=0) break;
}
}
}
}

Client Program:

#include<netinet/in.h>
#include<sys/types.h>
#include<stdio.h>
#include<stdlib.h>
12
#include<string.h>
#include<sys/socket.h>
#include<sys/select.h>
#include<unistd.h>
#define MAXLINE 20
#define SERV_PORT 7134
main(int argc,char **argv)
{
int maxfdp1;
fd_set rset;
char sendline[MAXLINE],recvline[MAXLINE];
int sockfd;
struct sockaddr_in servaddr;
if(argc!=2) {
printf("usage tcpcli <ipaddress>");
return; }
sockfd=socket(AF_INET,SOCK_STREAM,0);
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(SERV_PORT);
inet_pton(AF_INET,argv[1],&servaddr.sin_addr);
connect(sockfd,(struct sockaddr*)&servaddr,sizeof(servaddr));
printf("\n enter data to be send");
while(fgets(sendline,MAXLINE,stdin)!=NULL) {
write(sockfd,sendline,MAXLINE);
printf("\n line send to server is %s",sendline);
read(sockfd,recvline,MAXLINE);
printf("line recieved from the server %s",recvline);
}
exit(0);
}

13
OUTPUT
Server side:

Client Side:

14
5. Implementation of getsockopt (), setsockopt () system calls

#include<stdio.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <fcntl.h>
#include <netinet/tcp.h>
#include <sys/types.h>
main(int argc,char *argv[])
{
int sockfd,a,b,c;
sockfd=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
int len=sizeof(a);
char s[20];
getsockopt(sockfd,IPPROTO_TCP,TCP_MAXSEG,&a,&len);
{
printf("PROTOCOL LEVEL>Da Max Segment Size is :%d\n", a);
}
getsockopt(sockfd,IPPROTO_TCP,TCP_NODELAY,s,len);
getsockopt(sockfd,IPPROTO_TCP,TCP_NODELAY,&b,&len);
{
printf("PROTOCOL LEVEL>Da option value is:%d\n", b);
}
setsockopt(sockfd,SOL_SOCKET,SO_KEEPALIVE,s,len);
getsockopt(sockfd,SOL_SOCKET,SO_KEEPALIVE,&c,&len);
{
printf("SOCKET LEVEL>Da option value is %d\n",c);
}
}

15
OUTPUT

16
6. Implementation of getpeername () system call.

#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
void main()
{
int s;
struct sockaddr_in server, addr;
socklen_t len;

s = socket(PF_INET, SOCK_STREAM, 0);


server.sin_family = AF_INET;
inet_aton("10.2.1.254",&server.sin_addr);
server.sin_port = htons(80);
connect(s, (struct sockaddr*)&server, sizeof(server));
len = sizeof(addr);
getpeername(s, (struct sockaddr*)&addr, &len);
printf("Peer IP address: %s\n", inet_ntoa(addr.sin_addr));
printf("Peer port : %d\n", ntohs(addr.sin_port));
}

17
OUTPUT

18
7. Implementation of remote command execution using socket system calls.

Server Program:

#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
main(int argc,char *argv[])
{
int sockfd, new_sockfd, rval, fd;
char buff1[400],buff2[400];
struct sockaddr_in server, client;
int len;
sockfd=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(sockfd==-1)
{
perror("\nsock_error\n");
exit(1);
}
server.sin_family=AF_INET;
server.sin_addr.s_addr=inet_addr(argv[1]);
server.sin_port=htons(atoi(argv[2]));
rval=bind(sockfd,(struct sockaddr*)&server,sizeof(server));
if(rval!=-1)
{
listen(sockfd,5);
while(1)
{
len=sizeof(client);
new_sockfd=accept(sockfd,(struct sockaddr*)&client,&len);
if(new_sockfd!=-1)
{
rval=recv(new_sockfd,buff1,sizeof(buff1),0);
if(rval==-1)
{
perror("\n recev_error\n");
exit(1);
}
19
else
{
strcat(buff1,">file.txt");
system(buff1);
fd=open("file.txt",O_RDONLY,0666);
if(fd==-1)
{
printf("\n file_error\n");
exit(1);

}
read(fd,buff2,sizeof(buff2));
}
rval=send(new_sockfd,buff2,sizeof(buff2),0);
if(rval!=-1)
{
printf("\n message sent successfully!\n");
}
else
{
perror("\n send_error\n");
exit(1);
}
}
else
{
perror("\n accept_error");
exit(1);
}
}
}
else
{
perror("\n bind_error\n");
close(sockfd);
}
}

20
Client program:

#include <sys/types.h>
#include <arpa/inet.h>
#include<netinet/in.h>
main(int argc, char *argv[]){
int sockfd,rval;
char buff1[400],buff2[400];
struct sockaddr_in server;
sockfd=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(sockfd==-1)
{
perror("\nSOCK_ERR\n");
exit(1);
}
server.sin_family=AF_INET;
server.sin_addr.s_addr=inet_addr(argv[1]);
server.sin_port=htons(atoi(argv[2]));
rval=connect(sockfd,(struct sockaddr*)&server,sizeof(server));
if(rval!=-1)
{
printf("\n Enter any shell command: \n");
scanf("%s",buff1);
rval=send(sockfd,buff1,sizeof(buff1),0);
if(rval==-1)
{
perror("\nSEND_ERR\n");
exit(1);
}
rval=recv(sockfd,buff2,sizeof(buff2),0);
if(rval!=-1)
{
printf("\n received data is:%s\n", buff2);
}
else
{
printf("\n RECV_ERR\n");
}
}
else
{
perror("\nCONNECT_ERR\n");
}}
21
OUTPUT
Server side:

Client side:

22
8. Implementation of Distance Vector Routing Algorithm
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


{

BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));

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


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

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


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

graph = new int[v][v];


via = new int[v][v];
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--;
23
System.out.print("Cost: ");
int c = Integer.parseInt(br.readLine());
graph[s][d] = c;
graph[d][s] = c;
}

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);
print_tables();
System.out.println();
}

static void update_table(int source)


{
for(int i = 0; i < v; i++)
{
if(graph[source][i] != 9999)
{
int dist = graph[source][i];
for(int j = 0; j < v; j++)
24
{
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;
}
}
}
}
}

static void update_tables()


{
int k = 0;
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;
}
else
{
rt[i][j] = 9999;
via[i][j] = 100;
}
}
}
25
}
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();
}
}
}

26
OUTPUT

27
9. Implementation of SMTP.
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.internet.MimeMessage;
public class EmailSend {

public static void main(String args[]){


try{
String host ="smtp.gmail.com" ;
String user = "your email address";
String pass = "your password";
String to = "receiever email ";
String from = "sender email";
String subject = "This is confirmation number for your
expertprogramming account. Please insert this number to activate your
account.";
String messageText = "Your Is Test Email :";
boolean sessionDebug = false;

Properties props = System.getProperties();

props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.required", "true");

java.security.Security.addProvider(new
com.sun.net.ssl.internal.ssl.Provider());
Session mailSession = Session.getDefaultInstance(props, null);
mailSession.setDebug(sessionDebug);
Message msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject); msg.setSentDate(new Date());
msg.setText(messageText);

Transport transport=mailSession.getTransport("smtp");
transport.connect(host, user, pass);

28
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
System.out.println("message send successfully");
}catch(Exception ex)
{
System.out.println(ex);
}

}
}

29
OUTPUT

30
10. Implementation of FTP.
Server Program:

import java.net.*;
import java.io.*;
public class ServerFile
{
ServerSocket serverSocket;
Socket socket;
int port;
ServerFile()
{
this(9999);
}
ServerFile(int port)
{
this.port = port;
}
void waitForRequests() throws IOException
{
serverSocket = new ServerSocket(port);
while (true)
{
System.out.println("Server Is WAITING...");
socket = serverSocket.accept();
System.out.println("Request Received From " +
socket.getInetAddress()+"@"+socket.getPort());
new ServantFile(socket).start();
System.out.println("Service Started Thread ");
}
}
public static void main(String[] args)
{
try
{
new ServerFile().waitForRequests();
}
catch (IOException e)
{
e.printStackTrace();
}

31
}
}

Client Program:

import java.io.*;
import java.net.*;
public class ClientFile
{
String serverAddress;
String fileName;
int port;
Socket socket;
ClientFile()
{
this("10.2.1.254", 9999, "Model.txt");
}
ClientFile(String serverAddress, int port, String fileName)
{
this.serverAddress = serverAddress;
this.port = port;
this.fileName = fileName;
}
void sendRequestForFile() throws UnknownHostException,IOException
{
socket = new Socket(serverAddress, port);
System.out.println("Connecting to Server...");
PrintWriter writer = new PrintWriter(new
OutputStreamWriter(socket.getOutputStream()));
writer.println(fileName);
writer.flush();
System.out.println("Request has been Sent... ");
getResponseFromServer();
socket.close();
}
void getResponseFromServer() throws IOException
{
BufferedReader reader = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
String response = reader.readLine();
if(response.trim().toLowerCase().equals("filenotfound"))
{
32
System.out.println(response);
return;
}
else
{
BufferedWriter fileWriter = new BufferedWriter(new
FileWriter("FileRecd.txt"));
do
{
fileWriter.write(response);
fileWriter.flush();
}while((response=reader.readLine())!=null);
fileWriter.close();
}
}
public static void main(String[] args)
{
try
{
new ClientFile().sendRequestForFile();
}
catch (UnknownHostException er)
{
er.printStackTrace();
}
catch (IOException er)
{
er.printStackTrace();
}
}
}

Servant File:

import java.net.*;
import java.io.*;
public class ServantFile extends Thread
{
Socket socket;
String fileName;
BufferedReader in;
33
PrintWriter out;
ServantFile(Socket socket) throws IOException

this.socket = socket;
in = new BufferedReader(newInputStreamReader(socket.getInputStream()));
out = new PrintWriter(newOutputStreamWriter(socket.getOutputStream()));
}
public void run()
{
try
{
fileName = in.readLine();
File file = new File(fileName);
if (file.exists())
{
BufferedReader fileReader = new
BufferedReader(new FileReader(fileName));
String content = null;
while ((content = fileReader.readLine())!=null)
{
out.println(content);
out.flush();
}
System.out.println("File has been Sent...");
}
else
{
System.out.println("Requested File was Not Found...");
out.println("File Not Found");
out.flush();
}
socket.close();
System.out.println("Connection Closed!");
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
34
}
public static void main(String[] args)
{
}
}
OUTPUT
Server Side:

Client Side:

35
11. Implementation of HTTP
Server Program:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(12001);
System.out.println("HTTP Server (only POST implemented) is ready and is
listening on Port Number 12001 \n");
while(true) {
Socket clientSocket = serverSocket.accept();
System.out.println(clientSocket.getInetAddress().toString() + " " +
clientSocket.getPort());
BufferedReader in = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
OutputStream out = clientSocket.getOutputStream();
String temp;
while((temp=in.readLine()) != null)
System.out.println(temp);
String response = "HTTP/1.1 200 OK\n\r";
response = response + "Date: Thr, 08 NOV 2018 20:08:11 GMT\n\r";
response = response + "Server: venkat Server\n\r";
response = response + "Connection: close\n\r";
response = response + "1";
byte[] bytes = response.getBytes();
out.write(bytes);
out.flush();
in.close();
out.close();
}
} catch(Exception e) {
System.out.println("ERROR: " + e.getMessage());
System.exit(1);
}
}
}

36
Client Program:

import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
try {
URL url = new URL("http://10.2.1.254:12001");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod("POST");
con.setUseCaches(false);
String test = "<name>Hello</name>";
byte[] bytes = test.getBytes();
con.setRequestProperty("Content-length", String.valueOf(bytes.length));
con.setRequestProperty("Content-type", "text/html");
OutputStream out = con.getOutputStream();
out.write(bytes);
out.flush();
BufferedReader in = new BufferedReader(new
InputStreamReader(con.getInputStream()));
String temp;
while((temp = in.readLine()) != null)
System.out.println(temp);
out.close();
in.close();
con.disconnect();
} catch(Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}

37
OUTPUT
Server side:

Client side:

38
12. Implementation of RSA algorithm.
import java.math.*;
import java.util.*;
class RSA
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int p,q,n,z,d=0,e,i;
System.out.println("Enter the number to be encrypted and decrypted");
int msg=sc.nextInt();
double c;
BigInteger msgback;
System.out.println("Enter 1st prime number p");
p=sc.nextInt();
System.out.println("Enter 2nd prime number q");
q=sc.nextInt();

n=p*q;
z=(p-1)*(q-1);
System.out.println("the value of z = "+z);

for(e=2;e<z;e++)
{
if(gcd(e,z)==1) // e is for public key exponent
{
break;
}
}
System.out.println("the value of e = "+e);
for(i=0;i<=9;i++)
{
int x=1+(i*z);
if(x%e==0) //d is for private key exponent
{
d=x/e;
break;
}
}
System.out.println("the value of d = "+d);
c=(Math.pow(msg,e))%n;

39
System.out.println("Encrypted message is : -");
System.out.println(c);
//converting int value of n to BigInteger
BigInteger N = BigInteger.valueOf(n);
// //converting float value of c to BigInteger
BigInteger C = BigDecimal.valueOf(c).toBigInteger();
msgback = (C.pow(d)).mod(N);
System.out.println("Derypted message is : -");
System.out.println(msgback);

static int gcd(int e, int z)


{
if(e==0)
return z;
else
return gcd(z%e,e);
}
}

40
OUTPUT

41

You might also like