Saturday, 20 April 2013

CORBA


CORBA is a mechanism in software for normalizing the method-call semantics between application objects that reside either in the same address space (application) or remote address space (same host, or remote host on a networkThe CORBA specification dictates that there shall be an ORB through which the application interacts with other objects. In practice, the application simply initializes the ORB, and accesses an internal Object Adapter which maintains such issues as reference counting, object (and reference) instantiation policies, object lifetime policies, etc. The Object Adapter is used to register instances of the generated code classes. Generated code classes are the result of compiling the user IDL code, which translates the high-level interface definition into an OS- and language-specific class base for use by the user application. This step is necessary in order to enforce the CORBA semantics and provide a clean user process for interfacing with the CORBA infrastructure.
Figure 1-2 CORBA  Architecture

Illustration of the autogeneration of the infrastructure code from an interface defined using the CORBA IDLThis figure illustrates the high-level paradigm for remote interprocess communications using CORBA. Issues not addressed here, but that are accounted-for in the CORBA specification include: data typing, exceptions, network protocol, communication timeouts, etc. For example: Normally the server side has the Portable Object Adapter (POA) that redirects calls either to the local servants or (to balance the load) to the other servers. Also, both server and client parts often have interceptors that are described below. Issues CORBA (and thus this figure) does not address, but that all distributed systems must address: object lifetimes, redundancy/fail-over, naming semantics (beyond a simple name), memory management, dynamic load balancing, separation of model between display/data/control semantics, etc.
CORBA defines an architecture for distributed objects. The basic CORBA paradigm is that of a request for services of a distributed object. Everything else defined by the OMG is in terms of this basic paradigm. The services that an object provides are given by its interface. Interfaces are defined in OMG's Interface Definition Language (IDL). Distributed objects are identified by object references, which are typed by IDL interfaces.
The ORB is the distributed service that implements the request to the remote object. It locates the remote object on the network, communicates the request to the object, waits for the results and when available communicates those results back to the client.
The ORB implements location transparency. Exactly the same request mechanism is used by the client and the CORBA object regardless of where the object is located. It might be in the same process with the client, down the hall or across the planet. The client cannot tell the difference.
The ORB implements programming language independence for the request. The client issuing the request can be written in a different programming language from the implementation of the CORBA object. The ORB does the necessary translation between programming languages. Language bindings are defined for all popular programming languages.

CORBAservicesline

OMG is pleased to announce a new format for its formal CORBAservices specifications. Previously, the CORBAservices were combined into one "binder" and you had the option to view/print the complete set of services or each service.
The new format treats each CORBAservice as its own stand-alone document. You have the option to view/print each CORBAservice separately. There are several CORBA services. The popular ones are described in detail in another module of this course. Below is a brief description of each:
Service
Description
Object life cycle
Defines how CORBA objects are created, removed, moved, and copied
Naming
Defines how CORBA objects can have friendly symbolic names
Events
Decouples the communication between distributed objects
Relationships
Provides arbitrary typed n-ary relationships between CORBA objects
Externalization
Coordinates the transformation of CORBA objects to and from external media
Transactions
Coordinates atomic access to CORBA objects
Concurrency Control
Provides a locking service for CORBA objects in order to ensure serializable access
Property
Supports the association of name-value pairs with CORBA objects
Trader
Supports the finding of CORBA objects based on properties describing the service offered by the object
Query
Supports queries on objects

Simple Network Management Protocol



Simple Network Management Protocol (SNMP) is a UDP-based network protocol. It is used mostly in network management systems to monitor network-attached devices for conditions that warrant administrative attention. SNMP is a component of the Internet Protocol Suite as defined by the Internet Engineering Task Force (IETF). It consists of a set of standards for network management, including an application layer protocol, a database schema, and a set of data objects
Control and supervision of modern networks can quickly become a challenging task, especially when handling heterogeneous network topologies. The Interpeak SNMP Agent resolves this by providing a uniform management interface using the industry-standard SNMP protocol.

The SNMP Protocol

Simple Network Management Protocol (SNMP) is one of the standard operations and maintenance protocols for the Internet. SNMP has been a key technology that enabled the Internet's phenomenal growth. This page provides information about this protocol, ranging from beginner's FAQs to the latest industry standard - SNMPv3. 

SNMP

SNMP standards are defined in a series of documents, called request for comments or RFCs, proposed by the Internet Engineering Task Force (IETF). A list of RFCs for SNMPv1, SNMPv2, and SNMPv3 is available. Please note that the IETF has changed the recommended status of SNMPv1 and SNMPv2c to historic. The IETF now recommends using SNMPv3 for internet management.

SNMPv3

SNMPv3 with Security and Administration
Information on SNMP Research's implementations, as well as general SNMPv3 information.

Advanced Protocol Operations
SNMP Research's initiative for product evolution, protocol enhancement, and to align with future industry standards.

Extended Security Options
SNMP Research products beginning with release 16.1 (domestic) support the Triple DES Privacy Protocol and the Advanced Encryption Standard (AES) Privacy Protocol for SNMPv3 privacy.

XML-Based Internet Management
Discover how SNMP Research has been developing solutions to incorporate the Extensible Markup Language (XML) into standards-based network management.

SNMP FAQ

SNMP FAQ (part 1) from comp.protocols.snmp
Beginner to advanced information about SNMP.

SNMP FAQ (part 2) from comp.protocols.snmp
Beginner to advanced information about SNMP.

SNMP Research Activities

The SNMP Research and IETF Activities Web page contains presentations on the Evolution of SNMP (EOS) and on the Status of Internet Management, as well as information about SNMPCONF activities.
Presentations from IM2001 and NANOG 22.

Requests for Comments (RFCs)

List of RFCs from the IETF (Internet Engineering Task Force).

SNMP & Network Web Sites

IETF: The Internet Engineering Task Force posts information on its groups, activities, and current happenings with the status of Internet network management.
Get the IEEE 802™ Program. The IEEE Standards Association and the IEEE 802 Plenary offer the "Get IEEE 802" pilot program, which grants public access to view and download individual electronic (PDF) IEEE Local and Metropolitan Area Network (IEEE 802) standards at no charge.
mibDepot is an online SNMP MIB reference site. A powerful search engine lets you search quickly for any MIB object or SNMP trap. This site includes MIBs from many vendors.
The Simple Times is a quarterly newsletter devoted to the "promotion of the Simple Network Management Protocol. " Each Issue contains technical articles, featured columns, standards, summaries, and a list of Internet resources.
The Simple Web is a Web site created and maintained by the SNMP group at the University of Twente in Holland. This page contains pointers to many sources of information about SNMP and management.
SNMP World is a Web site created and maintained by a group of Network Management Engineers. This page offers information about SNMP and network management.

SNMP Print Literature

Books About SNMP provides a list of books about SNMP technology and enterprise management using SNMP.

SNMP Mailing List

PSINet SNMP mailing list: snmp-request@lists.psi.com.

SNMP Testing Tools

Gambit Communications provides SNMP Agent simulation software.
InterWorking Labs provides a full line of test suite software products.
SimpleSoft provides SNMP agent simulation and automated agent testing software.

Proxy Agent Concepts

Proxy Agent Concepts provides information sheets.

Since its creation in 1988 as a short-term solution to manage elements in the growing Internet and other attached networks, SNMP has achieved widespread acceptance. SNMP was derived from its predecessor SGMP (Simple Gateway Management Protocol) and was intended to be replaced by a solution based on the CMIS/CMIP (Common Management Information Service/Protocol) architecture. This long-term solution, however, never received the widespread acceptance of SNMP.
SNMP is based on the manager/agent model consisting of an SNMP manager, an SNMP agent, a database of management information, managed SNMP devices and the network protocol. The SNMP manager provides the interface between the human network manager and the management system. The SNMP agent provides the interface between the manager and the physical device(s) being managed (see the illustration above).
SNMP is based on the manager/agent model
SNMP is based on the manager/agent model of a network management architecture.
The SNMP manager and agent use an SNMP Management Information Base (MIB) and a relatively small set of commands to exchange information. The SNMP MIB is organized in a tree structure with individual variables, such as point status or description, being represented as leaves on the branches. A long numeric tag or object identifier (OID) is used to distinguish each variable uniquely in the MIB and in SNMP messages.
SNMP uses five basic messages (GET, GET-NEXT, GET-RESPONSE, SET, and TRAP) to communicate between the SNMP manager and the SNMP agent. The GET and GET-NEXT messages allow the manager to request information for a specific variable.
The agent, upon receiving a GET or GET-NEXT message, will issue a GET-RESPONSE message to the SNMP manager with either the information requested or an error indication as to why the request cannot be processed. A SET message allows the SNMP manager to request a change be made to the value of a specific variable in the case of an alarm remote that will operate a relay. The SNMP agent will then respond with a GET-RESPONSE message indicating the change has been made or an error indication as to why the change cannot be made. The SNMP TRAP message allows the agent to spontaneously inform the SNMP manager of an "important" event.
As you can see, most of the messages (GET, GET-NEXT, and SET) are only issued by the SNMP manager. Because the TRAP message is the only message capable of being initiated by an SNMP agent, it is the message used by DPS Remote Telemetry Units (RTUs) to report alarms. This notifies the SNMP manager as soon as an alarm condition occurs, instead of waiting for the SNMP manager to ask.
The small number of commands used is only one of the reasons SNMP is "simple." The other simplifying factor is the SNMP protocol's reliance on an unsupervised or connectionless communication link. This simplicity has led directly to the widespread use of SNMP, specifically in the Internet Network Management Framework. Within this framework, it is considered "robust" because of the independence of the SNMP managers from the agents, e.g. if an SNMP agent fails, the SNMP manager will continue to function, or vice versa. The unsupervised communication link does however create some interesting issues for network alarm monitoring we will discuss more thoroughly in a later issue of our SNMP tutorial.

Each SNMP element manages specific objects with each object having specific characteristics. Each object / characteristic has a unique object identifier (OID) consisting of numbers separated by decimal points (i.e., 1.3.6.1.4.1.2682.1). These object identifiers naturally form a tree as shown below. The MIB associates each OID with a readable label (i.e., dpsRTUAState) and various other parameters related to the object. The MIB then serves as a data dictionary or code book that is used to assemble and interpret SNMP messages.
MIB object identifier tree
The branch of the MIB object identifier tree.
When an SNMP manager wants to know the value of an object / characteristic, such as the state of an alarm point, the system name, or the element uptime, it will assemble a GET packet that includes the OID for each object / characteristic of interest. The element receives the request and looks up each OID in its code book (MIB). If the OID is found (the object is managed by the element), a response packet is assembled and sent with the current value of the object / characteristic included. If the OID is not found, a special error response is sent that identifies the unmanaged object.
When an element sends a TRAP packet, it can include OID and value information (bindings) to clarify the event. DPS remote units send a comprehensive set of bindings with each TRAP to maintain traditional telemetry event visibility. Well-designed SNMP managers can use the bindings to correlate and manage the events. SNMP managers will also generally display the readable labels to facilitate user understanding and decision-making.
SNMP is a standard protocol that has wide acceptance in the industry and is flexible enough to describe almost anything. Because of these advantages, many network managers have come to believe that SNMP should be used for all network monitoring applications.
SNMP certainly has its place in an effective telecom network management solution, but this doesn't mean that any off-the-shelf SNMP manager can provide adequate visibility and control of your network.
The typical off-the-shelf SNMP manager is not designed for displaying and processing telemetry data for effective network monitoring, especially for the kind of real-world monitoring tasks network managers most need performed. These capabilities can be added to an SNMP manager, but it usually requires substantial custom software development.


RSA algorithm




Aim:Write a program to implement RSA algorithm
Theory: Cryptography has a long and colorful history. The message to be encrypted, known as the plaintext, are transformed by a function that is parameterized by a key. The output of the encryption process, known as the ciphertext, is then transmitted, often by messenger or radio. The enemy, or intruder, hears and accurately copies down the complete ciphertext. However, unlike the intended recipient, he does not know the decryption key and so cannot decrypt the ciphertext easily. The art of breaking ciphers is called cryptanalysis the art of devising ciphers (cryptography) and breaking them (cryptanalysis) is collectively known as cryptology.
There are several ways of classifying cryptographic algorithms. They are generally categorized based on the number of keys that are employed for encryption and decryption, and further defined by their application and use. The three types of algorithms are as follows:
1.      Secret Key Cryptography (SKC): Uses a single key for both encryption and decryption. It is also known as symmetric cryptography.
2.      Public Key Cryptography (PKC): Uses one key for encryption and another for decryption. It is also known as asymmetric cryptography.
3.      Hash Functions: Uses a mathematical transformation to irreversibly "encrypt" information

Public-key cryptography has been said to be the most significant new development in cryptography. Modern PKC was first described publicly by Stanford University professor Martin Hellman and graduate student Whitfield Diffie in 1976. Their paper described a two-key crypto system in which two parties could engage in a secure communication over a non-secure communications channel without having to share a secret key.
Generic PKC employs two keys that are mathematically related although knowledge of one key does not allow someone to easily determine the other key. One key is used to encrypt the plaintext and the other key is used to decrypt the ciphertext. The important point here is that it does not matter which key is applied first, but that both keys are required for the process to work. Because pair of keys is required, this approach is also called asymmetric cryptography.
In PKC, one of the keys is designated the public key and may be advertised as widely as the owner wants. The other key is designated the private key and is never revealed to another party. It is straight forward to send messages under this scheme.
The RSA algorithm is named after Ron Rivest, Adi Shamir and Len Adleman, who invented it in 1977. The RSA algorithm can be used for both public key encryption and digital signatures. Its security is based on the difficulty of factoring large integers.

Algorithm :
1.      Generate two large random primes, P and Q, of approximately equal size.
2.      Compute N = P x Q
3.      Compute Z = (P-1) x (Q-1).
4.      Choose an integer E, 1 < E < Z, such that GCD (E, Z) = 1
5.      Compute the secret exponent D, 1 < D < Z, such that E x D ≡ 1 (mod Z)
6.      The public key is (N, E) and the private key is (N, D).

Where, the values of P, Q, and Z should also be kept secret.
The message is encrypted using public key and decrypted using private key.
An example of RSA encryption :
1.      Select primes P=11, Q=3.
2.      N = P x Q = 11 x 3 = 33
Z = (P-1) x (Q-1) = 10 x 2 = 20
3.      Lets choose E=3
Check GCD(E, P-1) = GCD(3, 10) = 1 (i.e. 3 and 10 have no common factors except 1),
and check GCD(E, Q-1) = GCD(3, 2) = 1
therefore GCD(E, Z) = GCD(3, 20) = 1
4.      Compute D such that E x D ≡ 1 (mod Z)
compute D = E^-1 mod Z = 3^-1 mod 20
find a value for D such that Z divides ((E x D)-1)
find D such that 20 divides 3D-1.
Simple testing (D = 1, 2, ...) gives D = 7
Check: (E x D)-1 = 3.7 - 1 = 20, which is divisible by Z.
5.      Public key = (N, E) = (33, 3)
Private key = (N, D) = (33, 7).

Now say we want to encrypt the message m = 7,
Cipher code = M^E mod N
                    = 7^3 mod 33
                    = 343 mod 33
                    = 13.
    Hence the ciphertext c = 13.

To check decryption we compute Message’ = C^D mod N
                                                           = 13^7 mod 33
                                                           = 7.

Here, we don't have to calculate the full value of 13 to the power 7 here. We can make use of the fact that a = bc mod n = (b mod n).(c mod n) mod n so we can break down a potentially large number into its components and combine the results of easier, smaller calculations to calculate the final value.


Conclusion: Hence, we have implemented RSA algorithm.


Program Source Code :

Program to implement RSA Algorithm


import java.io.*;
import java.util.*;
class RSA
{
 public static void main(String args[])
 {
  Scanner ip=new Scanner(System.in);
  int p,q,n,e=1,j;
  int d=1,i1;
  int t1,t2;
  int pt[]= new int[10];
  int ct[]= new int[10];
  int rt[]= new int[10];
  String i=new String();
  System.out.println("Enter the two prime numbers:");
  p=ip.nextInt();
  q=ip.nextInt();
  System.out.println("Enter the message to be sent");
  i=ip.next();
  i1=i.length();
  for(j=0;j<i1;j++)
  {
   pt[j]=(i.charAt(j))-96;
  }
  n=p*q;
  t1=p-1;
  t2=q-1;
  while((t1*t2)%e==0)
  {
   e++;
  }
  for(j=0;j<i1;j++)
  {
   ct[j]=((int)Math.pow(pt[j],e))%n;
  }
  System.out.println("Sender Side:");
  System.out.println("----------------------");
  System.out.println("Public Key(e)= "+e);
  for(j=0;j<i1;j++)
  {
   System.out.println("Cipher Text= "+ct[j]);
  }
  System.out.println("Receiver Side:");
  System.out.println("----------------------");
  while((d*e)%(t1*t2)!=1)
  {
   d++;
  }
  System.out.println("Private Key(d)= "+d);
  for(j=0;j<i1;j++)
  {
   rt[j]=((int)Math.pow(ct[j],d))%n;
   System.out.println("Plain Text= "+rt[j]);
  }
  System.out.print("Decrypted Message:");
  for(j=0;j<i1;j++)
  {
   rt[j]=rt[j]+96;
   System.out.print((char)rt[j]);
  }
 }
}



C:\Program Files\Java\jdk1.6.0_02\bin>javac RSA.java

C:\Program Files\Java\jdk1.6.0_02\bin>java RSA

Enter the two prime numbers:
3
5
Enter the message to be sent
abcdefg
Sender Side:
------------------
Public Key(e)=3
Cipher Text= 1
Cipher Text= 8
Cipher Text= 12
Cipher Text= 4
Cipher Text= 5
Cipher Text= 6
Cipher Text= 13
Receiver Side:
------------------
Private key(d)=3
Plain Text= 1
Plain Text= 2
Plain Text= 3
Plain Text= 4
Plain Text= 5
Plain Text= 6
Plain Text= 7
Decrypted Message:abcdefg
C:\Program Files\Java\jdk1.6.0_02\bin>


Remote procedure call.



EXPERIMENT NO.6

AIM:
Program  on Remote procedure call.

THEORY:
            RPC is an interprocess communication technique that allows client and server software to communicate.
            An RPC is initiated by the client, which sends a request message to a known remote server to execute a specified procedure with supplied parameters. The remote server sends a response to the client, and the application continues its process.


Sequence of events during a RPC

1.     The client calls the client stub. The call is a local procedure call, with parameters pushed on to the stack in the normal way.
2.     The client stub packs the parameters into a message and makes a system call to send the message. Packing the parameters is called marshalling.
3.     The kernel sends the message from the client machine to the server machine.
4.     The kernel on the server machine passes the incoming packets to the server stub.
5.     Finally, the server stub calls the server procedure. The reply traces the same steps in the reverse direction.
         
            The RPC tools make it appear to users as though a client directly calls a procedure located in a remote server program. The client and server each have their own address spaces; that is, each has its own memory resource allocated to data used by the procedure. The following figure illustrates the RPC architecture.

            As the illustration shows, the client application calls a local stub procedure instead of the actual code implementing the procedure. Stubs are compiled and linked with the client application. Instead of containing the actual code that implements the remote procedure, the client stub code:
·       Retrieves the required parameters from the client address space.
·       Translates the parameters as needed into a standard NDR format for transmission over the network.
·       Calls functions in the RPC client run-time library to send the request and its parameters to the server.
The server performs the following steps to call the remote procedure.
1.    The server RPC run-time library functions accept the request and call the server stub procedure.
2.    The server stub retrieves the parameters from the network buffer and converts them from the network transmission format to the format the server needs.
3.    The server stub calls the actual procedure on the server.
            The remote procedure then runs, possibly generating output parameters and a return value. When the remote procedure is complete, a similar sequence of steps returns the data to the client.
1.    The remote procedure returns its data to the server stub.
2.    The server stub converts output parameters to the format required for transmission over the network and returns them to the RPC run-time library functions.
3.    The server RPC run-time library functions transmit the data on the network to the client computer.
            The client completes the process by accepting the data over the network and returning it to the calling function.
1.    The client RPC run-time library receives the remote-procedure return values and returns them to the client stub.
2.    The client stub converts the data from its NDR to the format used by the client computer. The stub writes data into the client memory and returns the result to the calling program on the client.
3.    The calling procedure continues as if the procedure had been called on the same computer.
            The run-time libraries are provided in two parts: an import library, which is linked with the application and the RPC run-time library, which is implemented as a dynamic-link library (DLL).
            The server application contains calls to the server run-time library functions which register the server's interface and allow the server to accept remote procedure calls. The server application also contains the application-specific remote procedures that are called by the client applications.




CONCLUSION:
            Remote procedure call is an inter-process communication technique initiated by the client, which sends a request message to a known remote server to execute a specified procedure with supplied parameters on remote server.
















PROGRAM:

import java.rmi.*;
public interface AddServerintf extends Remote
{
                double add(double d1,double d2)throws Remoteexceptions;
}

                                                                AddServerimpl.java

import java.rmi.*;
import java.rmi.server.*;
public class AddServerImpl extends Unicastremoteobject implements AddServerIntf
{
                public AddServerimpl()throws RemoteException
                {
                }

                public double add(double d1. Double d2)throws Remote Exception
                {
                return d1+d2;
                }
}
                                                               AddServer.java

import java.net.*;
import java.rmi.*;
public class AddServer
{
                public static void main(String args[])
                {
                                try
                                {
                                                AddServerImpl addServerImpl=new AddServerImpl();
                                                Naming.rebind(“AddServer”, addServerImpl);
                                }
                                catch(Exception e)
                                {
                                                System.out.println(“Exception:”+e);
                                }          
                }

}

                                                AddClient.java

import java.rmi.*;

public class AddClient
{
                public static void main(String args[])
                {
                                try
                                {
                                                String addServerURL=”rmi://”+args[0]+”/Addserver”;
                            AddServerIntf addServerIntf=(AddServerintf)Naming.lookup(addServerURL);

                                                System.out.println(“The first number is:”+args[1]);

                                                Double d1+double.valueof(args[1]).doubleValue();

                                                System.out.println(“The second number is:”+args[21]);

                                                Double d2=Double.valueOf(args[2]).doublevalue();

                                }

                                catch(Exception e)

                                {

                                                System.out.println(“Exception:”+e);    

                                }

                }          

}

OUTPUT:

Rmic AddServerImpl

Start rmiregistry

Java AddServer

Java AddClient 127.00.1 8 9

The first number is: 8

The second number is: 9

The sum is: 17

Objective Questions:
1.What is Remote Procedure Call (RPC)?
2.Which of the following statements about a remote procedure call is true?
(A) It is used to call procedures with addresses that are farther than 162 bytes away.
(B) It cannot return a value.
(C) It cannot pass parameters by reference.
(D) It cannot call procedures implemented in a different language.
(E) It is used to call procedures at an outer nesting level.

UDP client-server




AIM:
            Program for creating UDP client-server.

THEORY:
Socket Programming using UDP

            A UDP socket provides an unreliable bi-directional communication channel from one process to another
» A “datagram” abstraction
            Datagram packets are used to implement a connectionless packet delivery service supported by the UDP protocol. Each message is transferred from source machine to destination based on information contained within that packet. That means, each packet needs to have destination address and each packet might be routed differently, and might arrive in any order. Packet delivery is not guaranteed.
The format of datagram packet is:
                        | Msg | length | Host | serverPort |

A simple UDP server program that waits for client’s requests and then accepts the message (datagram) and sends back the same message is given below. Of course, an extended server program can manipulate client’s messages/request and send a new message as a response.

                        SERVER                                                            CLIENT
Fig :Client-Server communication in UDP


CONCLUSION:
            A UDP socket provides an unreliable bi-directional communication channel.









PROGRAM:
UDPServer.java
import java.util.*;
import java.io.*;
import java.net.*;
class UDPServer
{
public static void main(String S[])throws IOException
{
byte[] receive_data=new byte[1024];
byte[] send_data=new byte[1024];
DatagramSocket Server_Socket=new DatagramSocket(5000);
System.out.println("UDPServer waiting for client on port 5000");
while(true)
{
DatagramPacket receive_packet=new DatagramPacket(receive_data,receive_data.length);
Server_Socket.receive(receive_packet);
String data=new String(receive_packet.getData(),0,receive_packet.getLength());
InetAddress IPAddress=receive_packet.getAddress();
int receive_port=receive_packet.getPort();
if(data.equals("q")||data.equals("Q"))
break;
else
System.out.println("IPAdress"+receive_port+"said:"+data);
}
}
}
UDPClient.java
import java.util.*;
import java.io.*;
import java.net.*;
class UDPClient
{
public static void main(String S[])throws IOException
{
Scanner K=new Scanner(System.in);
byte[] send_data=new byte[1024];
DatagramSocket Client_Socket=new DatagramSocket();
InetAddress IPAddress=InetAddress.getByName("127.0.0.1");
while(true)
{
System.out.println("Type Something (q or Q to Quit)");
String data =K.nextLine();
if(data.equals("q")||data.equals("Q"))
break;
else
{
send_data=data.getBytes();
DatagramPacket send_Packet=new DatagramPacket(send_data,send_data.length,IPAddress,5000);
Client_Socket.send(send_Packet);
}
}
}
}

OUTPUT:
ۑ閩睞隌睞퍌퍜障睞

督卬ۑ閩睞隌睞障睞

Objective Questions
1 ______  is a connection-oriented and reliable protocol, ______ is a less reliable protocol.
2 The TCP and UDP protocols use ______ to map incoming data to a particular process running on a computer.
3 Datagrams are normally sent by ______  protocol.
4 Class ______ is used to create a packet of data for UDP protocol.
5 If something goes wrong related to the network, ______ will be thrown when dealing with TCP/UDP programming in Java.
6 The same port number can be reused many times when binding with sockets simultaneously: True or False.
7.UDP ( User Datagram Protocol) is
   (A)  Connectionless               (B)  Message Oriented
   (C)  Connection oriented       (D)  Both ( A) and ( B)

client-server socket.




AIM:
                  Program for client-server socket.

THEORY:
            A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent.Normally, a server runs on a specific computer and has a socket that is bound to a specific port number. The server just waits, listening to the socket for a client to make a connection request.
            On the client-side: The client knows the hostname of the machine on which the server is running and the port number on which the server is listening. To make a connection request, the client tries to rendezvous with the server on the server's machine and port. The client also needs to identify itself to the server so it binds to a local port number that it will use during this connection. This is usually assigned by the system.
A client's connection request
            If everything goes well, the server accepts the connection. Upon acceptance, the server gets a new socket bound to the same local port and also has its remote endpoint set to the address and port of the client. It needs a new socket so that it can continue to listen to the original socket for connection requests while tending to the needs of the connected client.
The connection is made
            On the client side, if the connection is accepted, a socket is successfully created and the client can use the socket to communicate with the server.The client and server can now communicate by writing to or reading from their sockets.Socket classes are used to represent the connection between a client program and a server program. The java.net package provides two classes--Socket and ServerSocket--that implement the client side of the connection and the server side of the connection, respectively.
.
Running the Programs
            You must start the server program first. To do this, run the server program using the Java interpreter, just as you would any other Java application. Remember to run the server on the machine that the client program specifies when it creates the socket.
            Next, run the client program. Note that you can run the client on any machine on your network; it does not have to run on the same machine as the server.
            If you are too quick, you might start the client before the server has a chance to initialize itself and begin listening on the port. If this happens, you will see a stack trace from the client. If this happens, just restart the client.

CONCLUSION :
            Sockets are the means by which computers on a network communicate











































PROGRAM:

Client Server Socket

//SERVER:
import java.io.*;
import java.net.*;
public class Server
{
            public Server()
            {}
            public static void main(String args[])
            {
                        try
                        {
                                    String num1 = null;
                                    ServerSocket server = new ServerSocket(8080);
                                    Socket s= server.accept();
            BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
                                    PrintWriter out = new PrintWriter(s.getOutputStream(),true);
                                    num1 = in.readLine();
                                    System.out.println("The requested integer number is: "+ num1);
                                    int i=Integer.parseInt(num1);
                                    out.println(Integer.toHexString(0x10000|i).substring(1).toUpperCase());
                                    int binry[]= new int[8];
                                    int octal[] = new int[4];
                                    binaryconversion(binry,i);
                                    octalconv(octal,i);
                                    System.out.println();
                                    num1=Integer.toString(binry[0]);
                                    for(int p =1; p<8;p++)
                                    {
                                                num1=num1 + Integer.toString(binry[p]);
                                    }
                                    //binary number
                                    out.println(num1);
           
                                    num1=Integer.toString(octal[0]);
                                    for(int p =1; p<4;p++)
                                    {
                                                num1=num1+Integer.toString(octal[p]);
                                    }
                                    //octal number
                                    out.println(num1);
                        }
                        catch(IOException a)
                        {
                                    System.out.println("Error in input");
                        }
            }

            public static void binaryconversion(int binry[], int i)
            {
                        int k;
                        for(k=0;k<8;k++)
                                    binry[k]=0;
                        k=7;

                        for(int a=i;a>0;)
                        {
                                    binry[k]=a%2;
                                    a=a/2;
                                    k--;
                        }
            }
            public static void octalconv(int octal[], int i)
            {
                        int k;
                        for(k=0;k<4;k++)
                                    octal[k]=0;
                        k=3;

                        for(int a=i;a>0;)
                        {
                                    octal[k]=a%8;
                                    a=a/8;
                                    k--;
                        }
            }
}

OUTPUT
The requested integer number is: 42
                                            


























                                                                Client Server Socket

//CLIENT:
import java.io.*;
import java.net.*;
public class client
{
public client()
{}
public static void main(String args[])throws IOException
{
String num1 = null;
Socket s = new Socket("localhost",8080);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number for conversion : ");
num1 = br.readLine();
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter out = new PrintWriter(s.getOutputStream(),true);
out.println(num1);
num1 = in.readLine();
System.out.println("The HEX number is:" + num1);

num1 = in.readLine();
System.out.println("The binary number is:" + num1);

num1 = in.readLine();
System.out.println("The Octal number is:" + num1);
}
}

OUTPUT:
Enter the number for conversion :
42
The HEX number is:002A
The binary number is:00101010
The Octal number is:0052


Objective Questions:
1.Java uses ______ class representing a server and ______ class representing the client that uses TCP protocol.
2. ______  is used to wait for accepting client connection requests.
3. In order to create a client socket connecting to a particular server, the IP address must be given to the client socket, otherwise, it cannot connect to the server: True or False.
4. Sockets provide an interface for programming networks at the transport layer: True or False.
5. Java TCP Socket uses the InputStream/OutputStream to read/write data to the network channel:
True or False.
6. Call Socket.close() method will close the TCP server that socket connects to: True or False.
7. The socket instance does not need to be explicitly closed to release all the resources it occupies, as the Java Garbage Collection mechanism will do it automatically: True or False
8. The following line of code
  Socket socket = new Socket(“localhost,” 1254);
  will create a TCP server at localhost port 1254: True or False.