Chapter 03 Networking Security Objectives 1 To learn
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 Server. Socket 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 Inet. Address class -> Java Inet. Address class is java’s representation of an IP address. -> It is a combination of IP address and Host name. -> The java. net. Inet. Address 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 Inet. Address class Method Description public static Inet. Address It returns the object of Inet. Address containing get. By. Name(String host) throws Local. Host IP and name. Unknown. Host. Exception public static Inet. Address get. Local. Host() throws Unknown. Host. Exception It returns the object of Inet. Adddress containing local host name and address. public static Inet. Address[ ] get. All. By. Name(String host. Name) throws Unknown. Host. Exception It returns an array of Inet. Addresses that represent all of the addresses that a particular name resolves to.
import java. io. *; import java. net. *; public class Inet. Demo{ public static void main(String[] args) { try { Inet. Address ip=Inet. Address. get. By. Name("www. javatpoint. com"); Inet. Address SW[] = Inet. Address. get. All. By. Name("www. nba. com"); System. out. println("Host Name: "+ip. get. Host. Name()); System. out. println("IP Address: "+ip. get. Host. Address()); 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 Inet. Address 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[ ] get. Address( ) Returns a byte array that represents the object’s Internet address in network byte order. String get. Host. Address( ) Returns a string that represents the host address associated with the Inet. Address object. String get. Host. Name( ) Returns a string that represents the host name associated with the Inet. Address object. boolean is. Multicast. Address( ) Returns true if this Internet address is a multicast address. Otherwise, it returns false. String to. String( ) 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. Server. Socket 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 Server. Socket object, denoting which port number communication is to occur on. 2) The server invokes the accept() method of the Server. Socket 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 Output. Stream and an Input. Stream. The client's Output. Stream is connected to the server's Input. Stream, and the client's Input. Stream is connected to the server's Output. Stream. • TCP is a two-way communication protocol hence data can be sent across both streams at the same time.
Server. Socket Class Constructors The java. net. Server. Socket class is used by server applications to obtain a port and listen for client requests. The Server. Socket class has four constructors 1) public Server. Socket(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 Server. Socket(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 Server. Socket(int port, int backlog, Inet. Address address) throws IOException Similar to the previous constructor, the Inet. Address parameter specifies the local IP address to bind to. The Inet. Address 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 Server. Socket() throws IOException Creates an unbound server socket. When using this constructor, use the bind() method when you are ready to bind the server socket.
Server. Socket Class Methods 1) public int get. Local. Port() 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 timeout value has been set using the set. So. Timeout() method. Otherwise, this method blocks indefinitely. 3)public void set. So. Timeout(int timeout) Sets the time-out value for how long the server socket waits for a client during the accept(). 4) public void bind(Socket. Address host, int backlog) Binds the socket to the specified server and port in the Socket. Address object. This method is used when Server. Socket is instantiated using the no-argument constructor.
Socket Class Constructors 1) public Socket(String host, int port) throws Unknown. Host. Exception, 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(Inet. Address host, int port) throws IOException This constructor is identical to the previous constructor, except that the host is denoted by an Inet. Address object. 3) public Socket(String host, int port, Inet. Address local. Address, int local. Port) 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(Inet. Address host, int port, Inet. Address local. Address, int local. Port) throws IOException. This constructor is identical to the previous constructor, except that the host is denoted by an Inet. Address 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(Socket. Address 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 Inet. Address get. Inet. Address() This method returns the address of the other computer that this socket is connected to. 3)public int get. Port() Returns the port the socket is bound to on the remote machine. 4) public int get. Local. Port() Returns the port the socket is bound to on the local machine.
Socket Class Methods 5) public Socket. Address get. Remote. Socket. Address() Returns the address of the remote socket. 6) public Input. Stream get. Input. Stream() throws IOException Returns the input stream of the socket. The input stream is connected to the output stream of the remote socket. 7)public Output. Stream get. Output. Stream() 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 My. Client { public static void main(String[] args) { try { Socket s=new Socket("localhost", 6666); Data. Output. Stream dout=new Data. Output. Stream(s. get. Output. Stream()); dout. write. UTF("Hello Server"); dout. flush(); dout. close(); s. close(); }catch(Exception e) { System. out. println(e); } } }
import java. io. *; import java. net. *; public class My. Server { public static void main(String[] args) { try { Server. Socket ss=new Server. Socket(6666); Socket s=ss. accept(); //establishes connection Data. Input. Stream dis=new Data. Input. Stream(s. get. Input. Stream()); String str=(String)dis. read. UTF(); 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 sc 1=new Scanner(s. get. Input. Stream()); System. out. println("Enter any number"); number=sc. next. Int(); Print. Stream p=new Print. Stream(s. get. Output. Stream()); p. println(number); temp = sc 1. next. Int(); 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; Server. Socket s 1=new Server. Socket(1342); Socket ss=s 1. accept(); Scanner sc=new Scanner(ss. get. Input. Stream()); number=sc. next. Int(); temp=number*2; Print. Stream p=new Print. Stream(ss. get. Output. Stream()); p. println(temp); Inet. Address ip= Inet. Address. get. Local. Host(); System. out. print(ip); } }
Example using UDP connection import java. io. *; import java. net. Datagram. Packet; import java. net. Datagram. Socket; public class UDPClient { public static void main(String args[])throws Exception { Datagram. Socket ds=new Datagram. Socket(); int i=8; byte[] b=String. value. Of(i). get. Bytes(); Inet. Address ia= Inet. Address. get. Local. Host(); Datagram. Packet dp= new Datagram. Packet(b, b. length, ia, 9999); ds. send(dp); byte[] b 1=new byte[1024]; Datagram. Packet dp 1= new Datagram. Packet(b 1, b 1. length); ds. receive(dp 1); String str=new String(dp 1. get. Data(), 0, dp 1. get. Length()); System. out. println("Result is " + str); } }
import java. io. *; import java. net. Datagram. Packet; import java. net. Datagram. Socket; public class UDPServer { public static void main(String args[])throws Exception { Datagram. Socket ds=new Datagram. Socket(9999); byte[] b 1= new byte[1024]; Datagram. Packet dp=new Datagram. Packet(b 1, b 1. length); ds. receive(dp); String str=new String(dp. get. Data(), 0, dp. get. Length()); int num= Integer. parse. Int(str. trim()); int result=num*num; byte[] b 2=String. value. Of(result). get. Bytes(); Inet. Address ia= Inet. Address. get. Local. Host(); Datagram. Packet dp 1=new Datagram. Packet(b 2, b 2. length, ia, dp. get. Port()); ds. send(dp 1); } }
URL class in Java -> Hierarchy of classes -> Methods of the class -> Examples using the class
Hierarchy of Classes Datagram. Packe t Datagram. Socket Inet. Address Object Socket Server. Socket 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 Malformed. URLException Creates a URL by putting together the given parts. 2) public URL(String protocol, String host, String file) throws Malformed. URLException Identical to the previous constructor, except that the default port for the given protocol is used. 3) public URL(String url) throws Malformed. URLException Creates a URL from the given String.
URL class Methods public String get. Protocol() it returns the protocol of the URL. public String get. Host() it returns the host name of the URL. public String get. Port() it returns the Port Number of the URL. public String get. File() it returns the file name of the URL. public URLConnection open. Connection() 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. get. Protocol()); System. out. println("Host Name: "+url. get. Host()); System. out. println("Port Number: "+url. get. Port()); System. out. println("File Name: "+url. get. File()); } 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 open. Connection() method of URL class is used. • Syntax: public URLConnection open. Connection()thr ows IOException • get. Input. Stream() 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 URLConnection. Reader { public static void main(String[] args) throws Exception { URL tp = new URL("http: //www. tutorialspoint. com/"); URLConnection yc = tp. open. Connection(); Buffered. Reader in = new Buffered. Reader(new Input. Stream. Reader( yc. get. Input. Stream())); String input. Line; while ((input. Line = in. read. Line()) != null) System. out. println(input. Line); 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 Security. Manager, to obtain a reference to this object, invoke System. get. Security. Manager. • For eg. Security. Manager sm = System. get. Security. Manager(); • 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 Security. Manager 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: Security. Manager security = System. get. Security. Manager(); if (security != null) { security. check. XXX(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 Security. Exception if the operation is not permitted. • The only exception to this convention is check. Top. Level. Window, which returns a boolean value.
• The current security manager is set by the set. Security. Manager method and the current security manager is obtained by the get. Security. Manager method. • The special method check. Permission(java. security. Permission) determ ines whether an access request indicated by a specified permission should be granted or denied. • The default implementation calls Access. Controller. check. Permission(perm); If a requested access isallowed, check. Permission returns quietly. If denied, a Security. Exception is thrown.
• The default implementation of each of the other check methods in Security. Manager is to call the check. Permission 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 check. Exit method of the security manager.
public void exit(int status) { Security. Manager security = System. get. Security. Manager(); if (security != null) security. check. Exit(status); exit. Internal(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 check. Exit method simply returns and normal processing continues. • If the security manager doesn't want to grant the request, the check. Exit method throws a Security. Exception. • The exit method continues only if no exception occurred. It then calls the private native exit. Internal method that actually terminates the virtual machine.
import java. security. Access. Control. Exception; public class Enable. Security. Manager { 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. set. Property("test. txt", "123456"); System. out. println(" test. txt is : " + System. get. Property("test. txt")); // Enable the security manager try { Security. Manager security. Manager = new Security. Manager(); System. set. Security. Manager(security. Manager); } catch (Security. Exception se) { // Security. Manager already set } try { System. set. Property("java. home", "123456"); } catch (Access. Control. Exception ace) { System. out. println("Write access to the test. txt system property is not allowed!"); } } }
- Slides: 43