Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Chapter 03 Networking & Security Objectives :1) To learn the Java’s Built in support for network programming. 2) To write program to demonstrate connectivity through software SOCKETS,TCP,ISP,URL and the Java Security Package. Basics of Networking What Is a Socket? -> A socket is one end-point of a two-way communication link between two programs running on the network. -> 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. -> The client in socket programming must know two information: 1) IP Address of Server, and 2) Port number. What Is Port Number? -> A port number is the logical address of each application or process that uses a network or the Internet to communicate. -> It uniquely identifies a network-based application on a computer. -> Each application / program is allocated a 16-bit integer port number. This number is assigned automatically by the OS, manually by the user or is set as a default for some popular applications. -> For example : Port Number 80 for HTTP, 23 for Telnet and 25 for SMTP. TCP & UDP Protocols • TCP − TCP stands for Transmission Control Protocol, which allows for reliable communication between two applications. TCP is typically used over the Internet Protocol, which is referred to as TCP/IP. • UDP − UDP stands for User Datagram Protocol, a connection-less protocol that allows for packets of data to be transmitted between applications. Proxy Server • A proxy server is a computer that offers a computer network service to allow clients to make indirect network connections to other network services. • A client connects to the proxy server, then requests a connection, file, or other resource available on a different server. • The proxy provides the resource either by connecting to the specified server or by serving it from a cache Internet Addressing Java InetAddress class -> Java InetAddress class is java’s representation of an IP address. -> It is a combination of IP address and Host name. -> The java.net.InetAddress class provides methods to get the IP of any host name for example www.javatpoint.com, www.google.com, www.facebook.com etc. -> Factory Methods of InetAddress class Method Description public static InetAddress It returns the object of InetAddress containing getByName(String host) throws LocalHost IP and name. UnknownHostException public static InetAddress getLocalHost() throws UnknownHostException It returns the object of InetAdddress containing local host name and address. public static InetAddress[ ] getAllByName(String hostName) throws UnknownHostException It returns an array of InetAddresses that represent all of the addresses that a particular name resolves to. import java.io.*; import java.net.*; public class InetDemo{ public static void main(String[] args) { try { InetAddress ip=InetAddress.getByName("www.javatpoint.com"); InetAddress SW[] = InetAddress.getAllByName("www.nba.com"); System.out.println("Host Name: "+ip.getHostName()); System.out.println("IP Address: "+ip.getHostAddress()); for (int i=0; i<SW.length; i++) { System.out.println(SW[i]); } } catch(Exception e){System.out.println(e); } } Output : } Host Name: www.javatpoint.com IP Address: 206.51.231.148 www.nba.com/23.15.35.11 www.nba.com/23.15.35.18 Instance Methods • The InetAddress class also has several other methods, which can be used on the objects returned by the Factory methods Method Description boolean equals(Object other) Returns true if this object has the same Internet address as other. byte[ ] getAddress( ) Returns a byte array that represents the object’s Internet address in network byte order. String getHostAddress( ) Returns a string that represents the host address associated with the InetAddress object. String getHostName( ) Returns a string that represents the host name associated with the InetAddress object. boolean isMulticastAddress( ) Returns true if this Internet address is a multicast address. Otherwise, it returns false. String toString( ) Returns a string that lists the host name and the IP address Java Socket Programming or Network Programming • Sockets provide the communication mechanism between two computers using TCP. A client program creates a socket on its end of the communication and attempts to connect that socket to a server. • When the connection is made, the server creates a socket object on its end of the communication. The client and the server can now communicate by writing to and reading from the socket. • The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a mechanism for the server program to listen for clients and establish connections with them. Steps occur when establishing a TCP connection between two computers using sockets 1) The server instantiates a ServerSocket object, denoting which port number communication is to occur on. 2) The server invokes the accept() method of the ServerSocket class. This method waits until a client connects to the server on the given port. 3) After the server is waiting, a client instantiates a Socket object, specifying the server name and the port number to connect to. 4)The constructor of the Socket class attempts to connect the client to the specified server and the port number. If communication is established, the client now has a Socket object capable of communicating with the server. 5) On the server side, the accept() method returns a reference to a new socket on the server that is connected to the client's socket. TCP connection between two computers using sockets • After the connections are established, communication can occur using I/O streams. • Each socket has both an OutputStream and an InputStream. The client's OutputStream is connected to the server's InputStream, and the client's InputStream is connected to the server's OutputStream. • TCP is a two-way communication protocol hence data can be sent across both streams at the same time. ServerSocket Class Constructors The java.net.ServerSocket class is used by server applications to obtain a port and listen for client requests. The ServerSocket class has four constructors 1) public ServerSocket(int port) throws IOException Attempts to create a server socket bound to the specified port. An exception occurs if the port is already bound by another application. 2) public ServerSocket(int port, int backlog) throws IOException Similar to the previous constructor, the backlog parameter specifies how many incoming clients to store in a wait queue. 3) public ServerSocket(int port, int backlog, InetAddress address) throws IOException Similar to the previous constructor, the InetAddress parameter specifies the local IP address to bind to. The InetAddress is used for servers that may have multiple IP addresses, allowing the server to specify which of its IP addresses to accept client requests on. 4) public ServerSocket() throws IOException Creates an unbound server socket. When using this constructor, use the bind() method when you are ready to bind the server socket. ServerSocket Class Methods 1) public int getLocalPort() Returns the port that the server socket is listening on. 2) public Socket accept() throws IOException Waits for an incoming client. This method blocks until either a client connects to the server on the specified port or the socket times out, assuming that the time-out value has been set using the setSoTimeout() method. Otherwise, this method blocks indefinitely. 3)public void setSoTimeout(int timeout) Sets the time-out value for how long the server socket waits for a client during the accept(). 4) public void bind(SocketAddress host, int backlog) Binds the socket to the specified server and port in the SocketAddress object. This method is used when ServerSocket is instantiated using the no-argument constructor. Socket Class Constructors 1) public Socket(String host, int port) throws UnknownHostException, IOException. This constructor attempts to connect to the specified server at the specified port. If it does not throw an exception, the connection is successful and the client is connected to the server. 2) public Socket(InetAddress host, int port) throws IOException This constructor is identical to the previous constructor, except that the host is denoted by an InetAddress object. 3) public Socket(String host, int port, InetAddress localAddress, int localPort) throws IOException. Connects to the specified host and port, creating a socket on the local host at the specified address and port. 4) public Socket(InetAddress host, int port, InetAddress localAddress, int localPort) throws IOException. This constructor is identical to the previous constructor, except that the host is denoted by an InetAddress object instead of a String. 5)public Socket() Creates an unconnected socket. Use the connect() method to connect this socket to a server. Socket Class Methods 1) public void connect(SocketAddress host, int timeout) throws IOException This method connects the socket to the specified host. This method is needed only when you instantiate the Socket using the no-argument constructor. 2) public InetAddress getInetAddress() This method returns the address of the other computer that this socket is connected to. 3)public int getPort() Returns the port the socket is bound to on the remote machine. 4) public int getLocalPort() Returns the port the socket is bound to on the local machine. Socket Class Methods 5) public SocketAddress getRemoteSocketAddress() Returns the address of the remote socket. 6) public InputStream getInputStream() throws IOException Returns the input stream of the socket. The input stream is connected to the output stream of the remote socket. 7)public OutputStream getOutputStream() throws IOException Returns the output stream of the socket. The output stream is connected to the input stream of the remote socket. 8) public void close() throws IOException Closes the socket, which makes this Socket object no longer capable of connecting again to any server. import java.io.*; import java.net.*; public class MyClient { public static void main(String[] args) { try { Socket s=new Socket("localhost",6666); DataOutputStream dout=new DataOutputStream(s.getOutputStream()); dout.writeUTF("Hello Server"); dout.flush(); dout.close(); s.close(); }catch(Exception e) { System.out.println(e); } } } import java.io.*; import java.net.*; public class MyServer { public static void main(String[] args) { try { ServerSocket ss=new ServerSocket(6666); Socket s=ss.accept();//establishes connection DataInputStream dis=new DataInputStream(s.getInputStream()); String str=(String)dis.readUTF(); System.out.println("message= "+str); ss.close(); } catch(Exception e) { System.out.println(e); } } } import java.net.*; import java.util.Scanner; import java.io.*; public class client { public static void main(String args[])throws IOException { int number,temp; Scanner sc= new Scanner(System.in); Socket s=new Socket("10.2.1.45",1342); Scanner sc1=new Scanner(s.getInputStream()); System.out.println("Enter any number"); number=sc.nextInt(); PrintStream p=new PrintStream(s.getOutputStream()); p.println(number); temp = sc1.nextInt(); System.out.println(temp); } } import java.net.*; import java.util.Scanner; import java.io.*; public class server { public static void main(String args[]) throws IOException { int number,temp; ServerSocket s1=new ServerSocket(1342); Socket ss=s1.accept(); Scanner sc=new Scanner(ss.getInputStream()); number=sc.nextInt(); temp=number*2; PrintStream p=new PrintStream(ss.getOutputStream()); p.println(temp); InetAddress ip= InetAddress.getLocalHost(); System.out.print(ip); } } Example using UDP connection import java.io.*; import java.net.*; import java.net.DatagramPacket; import java.net.DatagramSocket; public class UDPClient { public static void main(String args[])throws Exception { DatagramSocket ds=new DatagramSocket(); int i=8; byte[] b=String.valueOf(i).getBytes(); InetAddress ia= InetAddress.getLocalHost(); DatagramPacket dp= new DatagramPacket(b,b.length,ia,9999); ds.send(dp); byte[] b1=new byte[1024]; DatagramPacket dp1= new DatagramPacket(b1, b1.length); ds.receive(dp1); String str=new String(dp1.getData(),0,dp1.getLength()); System.out.println("Result is " + str); } } import java.io.*; import java.net.*; import java.net.DatagramPacket; import java.net.DatagramSocket; public class UDPServer { public static void main(String args[])throws Exception { DatagramSocket ds=new DatagramSocket(9999); byte[] b1= new byte[1024]; DatagramPacket dp=new DatagramPacket(b1,b1.length); ds.receive(dp); String str=new String(dp.getData(),0,dp.getLength()); int num= Integer.parseInt(str.trim()); int result=num*num; byte[] b2=String.valueOf(result).getBytes(); InetAddress ia= InetAddress.getLocalHost(); DatagramPacket dp1=new DatagramPacket(b2,b2.length,ia,dp.getPort()); ds.send(dp1); } } URL class in Java -> Hierarchy of classes -> Methods of the class -> Examples using the class Hierarchy of Classes DatagramPacket DatagramSocket InetAddress Object Socket ServerSocket URL URLConnection URL class • URL stands for Uniform Resource Locator • It is a description of resource location on the Internet. • Java provides a class java.net.URL to manipulate URLs. • For example :- http://www.javapoint.com/URL-class • A URL contains many information: 1) Protocol: Here http is the protocol. 2) Server name or IP Address: Here, www.javatpoint.com is the server name. 3) Port Number: It is an optional attribute. If we write http//ww.javatpoint.com:80/URL-class, 80 is the port number. If port number is not mentioned in the URL, it returns -1. 4) File Name or directory name: In this case, URL-class is the file name. URL class Constructors 1) public URL(String protocol, String host, int port, String file) throws MalformedURLException Creates a URL by putting together the given parts. 2) public URL(String protocol, String host, String file) throws MalformedURLException Identical to the previous constructor, except that the default port for the given protocol is used. 3) public URL(String url) throws MalformedURLException Creates a URL from the given String. URL class Methods public String getProtocol() it returns the protocol of the URL. public String getHost() it returns the host name of the URL. public String getPort() it returns the Port Number of the URL. public String getFile() it returns the file name of the URL. public URLConnection openConnection() It returns the instance of URLConnection i.e. associated with this URL. URL class example import java.io.*; import java.net.*; public class URLDemo { public static void main(String[] args) { try { URL url=new URL("http://www.javatpoint.com/java-tutorial"); System.out.println("Protocol: "+url.getProtocol()); System.out.println("Host Name: "+url.getHost()); System.out.println("Port Number: "+url.getPort()); System.out.println("File Name: "+url.getFile()); } catch(Exception e) { System.out.println(e); } } } URLConnection class in Java • The Java URLConnection class represents a communication link between the URL and the application. • This class can be used to read and write data to the specified resource referred by the URL. • To create object of URLConnection class the openConnection() method of URL class is used. • Syntax:public URLConnection openConnection()thr ows IOException • getInputStream() method is used to display all the data of a webpage. It returns all the data of the specified URL in the stream that can be read and displayed. Displaying source code of a webpage by URLConnecton class import java.net.*; import java.io.*; public class URLConnectionReader { public static void main(String[] args) throws Exception { URL tp = new URL("http://www.tutorialspoint.com/"); URLConnection yc = tp.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader( yc.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); } } Java Security • Once a class has been loaded into the virtual machine and checked by the verifier, the second security mechanism of the Java platform comes into action: the security manager. • It is a class that allows applications to implement a security policy. • It allows an application to determine, before performing a possibly unsafe or sensitive operation, what the operation is and whether it is being attempted in a security context that allows the operation to be performed. • The application can allow or disallow the operation. Interacting with the Security Manager • The security manager is an object of type SecurityManager, to obtain a reference to this object, invoke System.getSecurityManager. • For eg. SecurityManager sm = System.getSecurityManager(); • If there is no security manager, this method returns null. • Once an application has a reference to the security manager object, it can request permission to do specific things • The SecurityManager class contains many methods with names that begin with the word check. • These methods are called by various methods in the Java libraries before those methods perform certain sensitive operations. • The invocation of such a check method is as follows: SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkXXX(argument, . . . ); } • The security manager is thereby given an opportunity to prevent completion of the operation by throwing an exception. • A security manager simply returns if the operation is permitted, but throws a SecurityException if the operation is not permitted. • The only exception to this convention is checkTopLevelWindow, which returns a boolean value. • The current security manager is set by the setSecurityManager method and the current security manager is obtained by the getSecurityManager method. • The special method checkPermission(java.security.Permission) determi nes whether an access request indicated by a specified permission should be granted or denied. • The default implementation calls AccessController.checkPermission(perm); If a requested access isallowed, checkPermission returns quietly. If denied, a SecurityException is thrown. • The default implementation of each of the other check methods in SecurityManager is to call the checkPermission method to determine if the calling thread has permission to perform the requested operation. • The following fig. shows hierarchy of permission classes. • The default behavior when running Java applications is that no security manager is installed, so all operations are permitted. • The appletviewer, on the other hand, enforces a security policy that is quite restrictive. • For example, applets are not allowed to exit the virtual machine. If they try calling the exit method, then a security exception is thrown. • The exit method of the Runtime class calls the checkExit method of the security manager. public void exit(int status) { SecurityManager security = System.getSecurityManager(); if (security != null) security.checkExit(status); exitInternal(status); } • The security manager now checks if the exit request came from the browser or an individual applet. If the security manager agrees with the exit request, then the checkExit method simply returns and normal processing continues. • If the security manager doesn't want to grant the request, the checkExit method throws a SecurityException. • The exit method continues only if no exception occurred. It then calls the private native exitInternal method that actually terminates the virtual machine. import java.security.AccessControlException; public class EnableSecurityManager { public static void main(String[] args) { /* No security manager is enabled by default. Thus all security checks to protected resources and operations are disabled. In order to enable security checks, the security manager must be enabled also */ // Security manager is disabled, read/write access to "java.home" system property is allowed System.setProperty("test.txt", "123456"); System.out.println(" test.txt is : " + System.getProperty("test.txt")); // Enable the security manager try { SecurityManager securityManager = new SecurityManager(); System.setSecurityManager(securityManager); } catch (SecurityException se) { // SecurityManager already set } try { System.setProperty("java.home", "123456"); } catch (AccessControlException ace) { System.out.println("Write access to the test.txt system property is not allowed!"); } } }