29
Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur EXPERIMENT NO. 01 Aim: Networking Security Programming with TCP/IP for Application layer, Transport layer, Network layer, Datalink layer protocols. Program:- import java.io.*; public class { public static void main(String args[]) { int sd[MAX_SOCKS]; /* one per TCP/IPv6, UDP/IPv6, TCP/IP, UDP/IP */ char *port, *addr = NULL; struct addrinfo *res, hints; port = argv[1]; /* port number as a string – must not be NULL */ if(argc == 3) addr = argv[2]; /* hostname – NULL implies ANY address */ memset(&hints, '\0', sizeof(hints)); hints.ai_flags = AI_PASSIVE; /* if usrreq.addr NULL, sets sockaddr to ANY */ err = getaddrinfo(usrreq.addr, usrreq.port, &hints, &res); if(err) { if(err == EAI_SYSTEM) perror("getaddrinfo"); else printf("getaddrinfo error %d - %s", err, gai_strerror(err)); return 1; } i = 0; for(aip = res; aip; aip = aip->ai_next) { CSE/SRIT/8 th /NS Lab/Prepared by Vivek Kumar Sinha

Network security Lab manual

Embed Size (px)

Citation preview

Page 1: Network security Lab manual

Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur

EXPERIMENT NO. 01

Aim: Networking Security Programming with TCP/IP for Application layer, Transport layer, Network layer, Datalink layer protocols.

Program:-

import java.io.*;public class { public static void main(String args[]) {

int sd[MAX_SOCKS]; /* one per TCP/IPv6, UDP/IPv6, TCP/IP, UDP/IP */ char *port, *addr = NULL; struct addrinfo *res, hints; port = argv[1]; /* port number as a string – must not be NULL */ if(argc == 3) addr = argv[2]; /* hostname – NULL implies ANY address */ memset(&hints, '\0', sizeof(hints)); hints.ai_flags = AI_PASSIVE; /* if usrreq.addr NULL, sets sockaddr to ANY */ err = getaddrinfo(usrreq.addr, usrreq.port, &hints, &res); if(err) { if(err == EAI_SYSTEM) perror("getaddrinfo"); else printf("getaddrinfo error %d - %s", err, gai_strerror(err)); return 1; }

i = 0; for(aip = res; aip; aip = aip->ai_next)

{ if(aip->ai_family != AF_INET && aip->ai_family != AF_INET6) continue;

/* create a socket for this protocol */ sd[i] = socket(res->ai_family, res->ai_socktype, res->ai_protocol); if(sd[i] < 0) {perror("socket"); return sd[i]; } err = socket_options(sd[i], aip); /* set SO_REUSEADDR, SO_REUSPORT etc. */ if(err == -1) {perror("socket_options"); return 1;} err = bind(sd[i], res->ai_addr, res->ai_addrlen); if(err == -1) {perror("bind"); return 1;} /** perform other per-socket work here – e.g. maybe create threads etc **/ if(i == NUM_ELT(sd)) {printf("Insufficient socket elements\n");

CSE/SRIT/8th/NS Lab/Prepared by Vivek Kumar Sinha

Page 2: Network security Lab manual

Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur

break;} i++; }

CSE/SRIT/8th/NS Lab/Prepared by Vivek Kumar Sinha

Page 3: Network security Lab manual

Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur

EXPERIMENT NO. 02

Aim: Socket Security Programming for address structures, byte manipulation & address conversion functions, elementary socket system calls.

Program:-import java.net.*;

public class host

{

socket address structure:

 sockaddr_instruct in_addr

{

in_addr_t s_addr; /* 32-bit IPv4 address */ /* network byte ordered */

};

struct sockaddr_in { uint8_t sin_len; /* length of structure (16) */

sa_family_t sin_family; /* AF_INET */

in_port_t sin_port; /* 16-bit TCP or UDP port number */ /* network byte ordered */

struct in_addr sin_addr; /* 32-bit IPv4 address */ /* network byte ordered */ char

sin_zero[8]; /* unused */

};

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

{

int sockfd, numbytes;

char buf[MAXDATASIZE];

struct addrinfo hints, *servinfo, *p;

int rv;

char s[INET6_ADDRSTRLEN];

if (argc != 2) {

fprintf(stderr,"usage: client hostname\n");

exit(1);

}

memset(&hints, 0, sizeof hints);

hints.ai_family = AF_UNSPEC;

CSE/SRIT/8th/NS Lab/Prepared by Vivek Kumar Sinha

Page 4: Network security Lab manual

Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur

hints.ai_socktype = SOCK_STREAM;

if ((rv = getaddrinfo(argv[1], PORT, &hints, &servinfo)) != 0) {

fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));

return 1;

}

// loop through all the results and connect to the first we can

for(p = servinfo; p != NULL; p = p->ai_next) {

if ((sockfd = socket(p->ai_family, p->ai_socktype,

p->ai_protocol)) == -1) {

perror("client: socket");

continue;

}

if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {

close(sockfd);

perror("client: connect");

continue;

}

CSE/SRIT/8th/NS Lab/Prepared by Vivek Kumar Sinha

Page 5: Network security Lab manual

Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur

EXPERIMENT NO. 03

Aim: APIs security Programming for windows socket API, window socket & blocking I/O model, blocking sockets, blocking functions, timeouts for blocking I/O.

Program:-

import java.net.*;

public class test { public static void main(String args[]) { // Create a non-blocking socket and check for connections try { // Create a non-blocking socket channel on port 8080 SocketChannel sChannel = createSocketChannel("www.xxx", 8080); // Before the socket is usable, the connection must be completed // by calling finishConnect(), which is non-blocking while (!sChannel.finishConnect()) { // Do something else System.out.println("wonderful"); } // Socket channel is now ready to use } catch (IOException e) { } } // Creates a non-blocking socket channel for the specified host name and port. // connect() is called on the new channel before it is returned. public static SocketChannel createSocketChannel(String hostName, int port) throws IOException { // Create a non-blocking socket channel SocketChannel sChannel = SocketChannel.open(); sChannel.configureBlocking(false); // Send a connection request to the server; this method is non-blocking sChannel.connect(new InetSocketAddress(hostName, port)); return sChannel; }}

CSE/SRIT/8th/NS Lab/Prepared by Vivek Kumar Sinha

Page 6: Network security Lab manual

Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur

CSE/SRIT/8th/NS Lab/Prepared by Vivek Kumar Sinha

Page 7: Network security Lab manual

Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur

EXPERIMENT NO. 04

Aim: Web Security Programming for firewall and others.

Program:-

import java.net.*;import java.io.*;public class { public static void main(String args[]) { try { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); ServerSocket ss=new ServerSocket(2345); Socket skt=ss.accept( ); BufferedReader skt_in=new BufferedReader(new InputStreamReader(skt.getInputStream( ))); PrintStream skt_out=new PrintStream(skt.getOutputStream( )); while(true) { System.out.println(skt_in.readLine( )); skt_out.println(“What is your name”); yourname=skt_in.readLine( ); System.out.println(yourname); String s=skt_in.readLine( ); System.out.println(s); String myname=br.readLine( ); skt_out.println(myname); break; } while(true) { String recv=skt_in.readLine( ); System.out.println(yourname+”:”+recv); String send=br.readLine( ); skt_out.println(send); } } catch(Exception e) { System.out.println(“Exception :”+e); } } import java.net.*;

CSE/SRIT/8th/NS Lab/Prepared by Vivek Kumar Sinha

Page 8: Network security Lab manual

Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur

import java.io.*;public class ChatClient{ public static void main(String args[]) { try { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); Socket skt=new Socket(“rungtaibm”,2345); BufferedReader skt_in=new BufferedReader(new InputStreamReader(skt.getInputStream( ))); PrintStream skt_out=new PrintStream(skt.getOutputStream( )); while(true) { skt_out.println(“hello can I connect”); skt_out.println(skt_in.readLine( )); String myname=br.readLine( ); skt_out.println(myname); skt_out.println(“What is yours”); String yourname=skt_in.readLine( ); System.out.println(yourname); break; } while(true) { String send=br.readLine( ); skt_out.println(send); String recv=skt_in.readLine( ); System.out.println(yourname +”:”+recv); } } catch(Exception e) { System.out.println(“Exception :”+e); } } }

CSE/SRIT/8th/NS Lab/Prepared by Vivek Kumar Sinha

Page 9: Network security Lab manual

Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur

EXPERIMENT NO. 05

Aim: Component Security Programming for CORBA.

Program:-

package cs652.corba.server;import org.omg.CosNaming.*;import org.omg.CosNaming.NamingContextPackage.*;import org.omg.CORBA.*;import org.omg.PortableServer.*;public class HelloWorldServer {

public static void main(String[] args) { try{ // create and initialize the ORB ORB orb = ORB.init(args, null); // get reference to rootpoa & activate the POAManager POA rootpoa =

POAHelper.narrow(orb.resolve_initial_references("RootPOA")); rootpoa.the_POAManager().activate(); // create servant and get the CORBA reference of it HelloWorldServiceImpl helloWorldImpl = new HelloWorldServiceImpl(); org.omg.CORBA.Object ref =

rootpoa.servant_to_reference(helloWorldImpl); HelloWorldService helloWorldService =

HelloWorldServiceHelper.narrow(ref); // get the root naming context and narrow it to the NamingContextExt object org.omg.CORBA.Object objRef =

orb.resolve_initial_references("NameService"); NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef); // bind the Object Reference in Naming NameComponent path[] = ncRef.to_name("HelloWorldService"); ncRef.rebind(path, helloWorldService); // wait for invocations from clients orb.run(); } catch (Exception e) {}}

}

CSE/SRIT/8th/NS Lab/Prepared by Vivek Kumar Sinha

Page 10: Network security Lab manual

Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur

EXPERIMENT NO. 06

Aim: Programming for Cryptography and Digital Signature.

Program:-

PublicKeyCryptography

import java.security.*;import java.security.cert.*;import javax.crypto.*;import sun.misc.BASE64Encoder;import sun.misc.BASE64Decoder;

public class PublicKeyCryptography {

public static void main(String[] args) {

SymmetricEncrypt encryptUtil = new SymmetricEncrypt();String strDataToEncrypt = "Hello World";byte[] byteDataToTransmit = strDataToEncrypt.getBytes();

// Generating a SecretKey for Symmetric EncryptionSecretKey senderSecretKey = SymmetricEncrypt.getSecret();

//1. Encrypt the data using a Symmetric Keybyte[] byteCipherText =

encryptUtil.encryptData(byteDataToTransmit,senderSecretKey,"AES");String strCipherText = new BASE64Encoder().encode(byteCipherText);

//2. Encrypt the Symmetric key using the Receivers public keytry{

// 2.1 Specify the Keystore where the Receivers certificate has been imported

KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());char [] password = "testpwd".toCharArray();java.io.FileInputStream fis = new

java.io.FileInputStream("/home/Joebi/workspace/OWASP_Crypto/org/owasp/crypto/testkeystore.ks"); ks.load(fis, password); fis.close();

// 2.2 Creating an X509 Certificate of the Receiver X509Certificate recvcert ;

CSE/SRIT/8th/NS Lab/Prepared by Vivek Kumar Sinha

Page 11: Network security Lab manual

Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur

MessageDigest md = MessageDigest.getInstance("MD5"); recvcert = (X509Certificate)ks.getCertificate("testrecv"); // 2.3 Getting the Receivers public Key from the Certificate PublicKey pubKeyReceiver = recvcert.getPublicKey(); // 2.4 Encrypting the SecretKey with the Receivers public Key byte[] byteEncryptWithPublicKey = encryptUtil.encryptData(senderSecretKey.getEncoded(),pubKeyReceiver,"RSA/ECB/PKCS1Padding"); String strSenbyteEncryptWithPublicKey = new BASE64Encoder().encode(byteEncryptWithPublicKey); // 3. Create a Message Digest of the Data to be transmitted md.update(byteDataToTransmit);

byte byteMDofDataToTransmit[] = md.digest();

String strMDofDataToTransmit = new String();for (int i = 0; i < byteMDofDataToTransmit.length; i++){

strMDofDataToTransmit = strMDofDataToTransmit + Integer.toHexString((int)byteMDofDataToTransmit[i] & 0xFF) ; }

// 3.1 Message to be Signed = Encrypted Secret Key + MAC of the data to be transmitted

String strMsgToSign = strSenbyteEncryptWithPublicKey + "|" + strMDofDataToTransmit; // 4. Sign the message // 4.1 Get the private key of the Sender from the keystore by providing the password set for the private key while creating the keys using keytool

char[] keypassword = "send123".toCharArray(); Key myKey = ks.getKey("testsender", keypassword); PrivateKey myPrivateKey = (PrivateKey)myKey; // 4.2 Sign the message Signature mySign = Signature.getInstance("MD5withRSA"); mySign.initSign(myPrivateKey); mySign.update(strMsgToSign.getBytes()); byte[] byteSignedData = mySign.sign();

// 5. The Values byteSignedData (the signature) and strMsgToSign (the data which was signed) can be sent across to the receiver

// 6.Validate the Signature // 6.1 Extracting the Senders public Key from his certificate

X509Certificate sendercert ;

CSE/SRIT/8th/NS Lab/Prepared by Vivek Kumar Sinha

Page 12: Network security Lab manual

Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur

sendercert = (X509Certificate)ks.getCertificate("testsender"); PublicKey pubKeySender = sendercert.getPublicKey(); // 6.2 Verifying the Signature Signature myVerifySign = Signature.getInstance("MD5withRSA"); myVerifySign.initVerify(pubKeySender); myVerifySign.update(strMsgToSign.getBytes()); boolean verifySign = myVerifySign.verify(byteSignedData); if (verifySign == false) { System.out.println(" Error in validating Signature "); } else System.out.println(" Successfully validated Signature ");

// 7. Decrypt the message using Recv private Key to get the Symmetric Key char[] recvpassword = "recv123".toCharArray(); Key recvKey = ks.getKey("testrecv", recvpassword); PrivateKey recvPrivateKey = (PrivateKey)recvKey; // Parsing the MessageDigest and the encrypted value String strRecvSignedData = new String (byteSignedData); String[] strRecvSignedDataArray = new String [10]; strRecvSignedDataArray = strMsgToSign.split("|"); int intindexofsep = strMsgToSign.indexOf("|"); String strEncryptWithPublicKey = strMsgToSign.substring(0,intindexofsep); String strHashOfData = strMsgToSign.substring(intindexofsep+1);

// Decrypting to get the symmetric key byte[] bytestrEncryptWithPublicKey = new BASE64Decoder().decodeBuffer(strEncryptWithPublicKey); byte[] byteDecryptWithPrivateKey = encryptUtil.decryptData(byteEncryptWithPublicKey,recvPrivateKey,"RSA/ECB/PKCS1Padding"); // 8. Decrypt the data using the Symmetric Key javax.crypto.spec.SecretKeySpec secretKeySpecDecrypted = new javax.crypto.spec.SecretKeySpec(byteDecryptWithPrivateKey,"AES"); byte[] byteDecryptText = encryptUtil.decryptData(byteCipherText,secretKeySpecDecrypted,"AES"); String strDecryptedText = new String(byteDecryptText); System.out.println(" Decrypted data is " +strDecryptedText); // 9. Compute MessageDigest of data + Signed message MessageDigest recvmd = MessageDigest.getInstance("MD5");

CSE/SRIT/8th/NS Lab/Prepared by Vivek Kumar Sinha

Page 13: Network security Lab manual

Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur

recvmd.update(byteDecryptText);byte byteHashOfRecvSignedData[] = recvmd.digest();

String strHashOfRecvSignedData = new String();

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

Integer.toHexString((int)byteHashOfRecvSignedData[i] & 0xFF) ; }

// 10. Validate if the Message Digest of the Decrypted Text matches the Message Digest of the Original Message

if (!strHashOfRecvSignedData.equals(strHashOfData)){

System.out.println(" Message has been tampered ");}

}

catch(Exception exp){

System.out.println(" Exception caught " + exp);exp.printStackTrace()

CSE/SRIT/8th/NS Lab/Prepared by Vivek Kumar Sinha

Page 14: Network security Lab manual

Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur

EXPERIMENT NO. 07

Aim : Java network Security programming.

Program:-

SymmetricEncrypt

import javax.crypto.KeyGenerator;import javax.crypto.SecretKey;import javax.crypto.Cipher;import java.security.Key;

import java.security.NoSuchAlgorithmException;import java.security.InvalidKeyException;import java.security.InvalidAlgorithmParameterException;import javax.crypto.NoSuchPaddingException;import javax.crypto.BadPaddingException;import javax.crypto.IllegalBlockSizeException;

import sun.misc.BASE64Encoder;

public class SymmetricEncrypt {

String strDataToEncrypt = new String();String strCipherText = new String();String strDecryptedText = new String();static KeyGenerator keyGen;private static String strHexVal = "0123456789abcdef";

public static SecretKey getSecret(){

try{keyGen = KeyGenerator.getInstance("AES");keyGen.init(128);

}

catch(Exception exp){

System.out.println(" Exception inside constructor " +exp);

}

CSE/SRIT/8th/NS Lab/Prepared by Vivek Kumar Sinha

Page 15: Network security Lab manual

Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur

SecretKey secretKey = keyGen.generateKey();return secretKey;

}

/** * Step2. Create a Cipher by specifying the following parameters * a. Algorithm name - here it is AES */

public byte[] encryptData(byte[] byteDataToEncrypt, Key secretKey, String Algorithm) {

byte[] byteCipherText = new byte[200];

try {Cipher aesCipher = Cipher.getInstance(Algorithm);

/** * Step 3. Initialize the Cipher for Encryption */

if(Algorithm.equals("AES")){

aesCipher.init(Cipher.ENCRYPT_MODE,secretKey,aesCipher.getParameters());}else

if(Algorithm.equals("RSA/ECB/PKCS1Padding")){

aesCipher.init(Cipher.ENCRYPT_MODE,secretKey);}

byteCipherText = aesCipher.doFinal(byteDataToEncrypt); strCipherText = new BASE64Encoder().encode(byteCipherText);

}

catch (NoSuchAlgorithmException noSuchAlgo){

System.out.println(" No Such Algorithm exists " + noSuchAlgo);

}

catch (NoSuchPaddingException noSuchPad){

CSE/SRIT/8th/NS Lab/Prepared by Vivek Kumar Sinha

Page 16: Network security Lab manual

Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur

System.out.println(" No Such Padding exists " + noSuchPad);

}

catch (InvalidKeyException invalidKey){

System.out.println(" Invalid Key " + invalidKey);

}

catch (BadPaddingException badPadding)

{System.out.println(" Bad

Padding " + badPadding);}

catch (IllegalBlockSizeException illegalBlockSize)

{System.out.println(" Illegal

Block Size " + illegalBlockSize);

illegalBlockSize.printStackTrace();}catch (Exception exp){

exp.printStackTrace();}

return byteCipherText;}

public byte[] decryptData(byte[] byteCipherText, Key secretKey, String Algorithm) {

byte[] byteDecryptedText = new byte[200];

try{Cipher aesCipher = Cipher.getInstance(Algorithm);if(Algorithm.equals("AES")){

aesCipher.init(Cipher.DECRYPT_MODE,secretKey,aesCipher.getParameters());}else if(Algorithm.equals("RSA/ECB/PKCS1Padding")){

CSE/SRIT/8th/NS Lab/Prepared by Vivek Kumar Sinha

Page 17: Network security Lab manual

Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur

aesCipher.init(Cipher.DECRYPT_MODE,secretKey);}

byteDecryptedText = aesCipher.doFinal(byteCipherText);strDecryptedText = new String(byteDecryptedText);

}

catch (NoSuchAlgorithmException noSuchAlgo){

System.out.println(" No Such Algorithm exists " + noSuchAlgo);

}

catch (NoSuchPaddingException noSuchPad){

System.out.println(" No Such Padding exists " + noSuchPad);

}

catch (InvalidKeyException invalidKey){

System.out.println(" Invalid Key " + invalidKey);

invalidKey.printStackTrace();}

catch (BadPaddingException badPadding){

System.out.println(" Bad Padding " + badPadding);

badPadding.printStackTrace();}

catch (IllegalBlockSizeException illegalBlockSize){

System.out.println(" Illegal Block Size " + illegalBlockSize);

illegalBlockSize.printStackTrace();}

catch (InvalidAlgorithmParameterException invalidParam)

{System.out.println(" Invalid Parameter "

+ invalidParam);}

CSE/SRIT/8th/NS Lab/Prepared by Vivek Kumar Sinha

Page 18: Network security Lab manual

Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur

return byteDecryptedText;}public static byte[] convertStringToByteArray(String strInput) {

strInput = strInput.toLowerCase();byte[] byteConverted = new byte[(strInput.length() + 1) / 2];int j = 0;int interimVal;int nibble = -1;

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

strHexVal.indexOf(strInput.charAt(i));if (interimVal >= 0) {

if (nibble < 0) {nibble = interimVal;

} else {byteConverted[j++] = (byte)

((nibble << 4) + interimVal);nibble = -1;

}}

}

if (nibble >= 0) {byteConverted[j++] = (byte) (nibble << 4);

}

if (j < byteConverted.length) {byte[] byteTemp = new byte[j];System.arraycopy(byteConverted, 0, byteTemp, 0,

j);byteConverted = byteTemp;

}

return byteConverted;}public static String convertByteArrayToString(byte[] block) {

StringBuffer buf = new StringBuffer();

for (int i = 0; i < block.length; ++i) {buf.append(strHexVal.charAt((block[i] >>> 4) &

0xf));buf.append(strHexVal.charAt(block[i] & 0xf));

}return buf.toString();}

CSE/SRIT/8th/NS Lab/Prepared by Vivek Kumar Sinha

Page 19: Network security Lab manual

Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur

EXPERIMENT NO. 08

Aim: Client Server Security Connection programming.

Program:-

class Main { public static void main(String[] args) { new TCPServer().start(); new TCPClient().start(); }

}

class TCPClient extends Thread {

// Connection properties private static final String HOST = "127.0.0.1"; private static final int PORT = 56565;

public void run() { // Socket class used for TCP connections Socket sock = null;

// I/O components BufferedReader input = null; BufferedWriter output = null;

try { // Connect our socket to the server. sock = new Socket(HOST, PORT);

// Use a BufferedReader to read data from the server. input = new BufferedReader(new InputStreamReader(sock.getInputStream()));

// Use a BufferedWriter to send data to the server. output = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));

// Send some data to the server. String toServer = "Are you there, Server?"; System.out.println("ToServer: " + toServer); output.write(toServer); output.newLine(); output.flush();

// Wait for a response from the server and display it.

CSE/SRIT/8th/NS Lab/Prepared by Vivek Kumar Sinha

Page 20: Network security Lab manual

Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur

String fromServer = input.readLine(); System.out.println("FromServer: " + fromServer);

} catch (final IOException ex) { } finally { // Do our best to ensure a clean close procedure. // Closing the socket will also close input and output. try { if (sock != null) { sock.close(); } } catch (final IOException ex) { } } }

}

class TCPServer extends Thread {

// Connection properties private static final int PORT = 56565;

public void run() { // ServerSocket class used to accept TCP connections ServerSocket server = null; Socket sock = null;

// I/O components BufferedReader input = null; BufferedWriter output = null;

try { // Create our server on the given port. server = new ServerSocket(PORT);

// Wait for a client to connect to us. sock = server.accept();

// Use a BufferedReader to read data from the client. input = new BufferedReader(new InputStreamReader(sock.getInputStream()));

// Use a BufferedWriter to send data to the client. output = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));

// Wait for the client to talk to us. String fromClient = input.readLine();

CSE/SRIT/8th/NS Lab/Prepared by Vivek Kumar Sinha

Page 21: Network security Lab manual

Shri Rawatpura Sarkar Institute Of Technology-II, New Raipur

System.out.println("FromClient: " + fromClient);

// Send them a response. String toClient = "Yes, I'm here, Client."; System.out.println("ToClient: " + toClient); output.write(toClient); output.newLine(); output.flush();

} catch (final IOException ex) { } finally { // Do our best to ensure a clean close procedure. // Closing the socket will also close input and output. try { if (sock != null) { sock.close(); } } catch (final IOException ex) { }

// Close the server socket, as well. try { if (server != null) { server.close(); } } catch (final IOException ex) { } } }

}

CSE/SRIT/8th/NS Lab/Prepared by Vivek Kumar Sinha