Unit 5
Unit 5
1. IP Address –
An IP address is a unique address that distinguishes a device on the internet or a local
network.
An IP address identifies a machine in an IP network and is used to determine the destination
of a data packet.
IP stands for “Internet Protocol.”
IP Address is referred to as a logical address.
It is composed of octets. The range of each octet varies from 0 to 255.
Range of the IP Address – 0.0.0.0 to 255.255.255.255
For Example – 192.168.0.1
2. Port Number –
A port number is a way to identify a specific process to which an internet or other network
message is to be forwarded when it arrives at a server.
It's part of a network address, along with the IP address, to ensure data is routed to the correct
application. Think of it like an apartment number within a building (the IP address).
Example:
When you visit a website, your request is sent to the server's IP address and port 80, which tells
the server to direct the request to the web server application.
It comprises a set of rules governing the format of data sent via the internet or local
network.
Protocol defines how data is transmitted between different devices in the same network.
Eg:-TCP, FTP, Telnet, SMTP, POP (Post Office Protocol) etc.
4. 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.
Reserved sockets
Reserved sockets refer to sockets that are pre-defined and assigned to specific protocols or
services. These sockets, typically within the range of 0 to 1023, are used for established services like
HTTP, FTP, and SSH.
Proxy Server
A proxy server acts as a gateway between your device and the internet, masking your IP address
and enhancing online privacy. The proxy server also prevents the identification of the client’s IP
address when the client makes any request to any other servers.
1. IPV4
Class A range for first byte is 0-127. Class A type of IP addresses have First byte consisting of Network
address with first bit as 0 and the next 3 bytes with host id.
Hence, number of hosts are more when compared to number of networks.
The default subnet masks for class A networks is 255.0.0.0.
There are 128 possible Class A networks.
However, any address that begins with 127. is considered a loopback address.
Host Ranges from:-
0.0.0.0 to 127.255.255.255
Example
2.134.213.2
135.58.24.17
Class D: Class D range for first byte is 224-239. Class D is used for multicasting and its starting bits are
1110
Class E: Class E range for first byte is 240-255. Class E is reserved for future use and its starting bits
are 1111
The IPv6 address consists mainly of two 64-bit segments where the higher part of the bits is
classified as the network part, and the lower 64 bits are classified as the client ID. The network part
is subdivided into the Global Unicast Address (GUA) and subnet ID.
1. CookieHandler
2. CookieManager
3. DatagramPacket
4. InetAddress
5. ServerSocket
6. Socket
7. DatagramSocket
8. Proxy
9. URL
10. URLConnection
1. CookiePolicy
2. CookieStore
3. FileNameMap
4. SocketOption
5. SocketImplFactory
6. ProtocolFamily
The java.net.InetAddress class provides methods to get the IP address of any hostname.
An IP address is represented by 32-bit or 128-bit unsigned number.
InetAddress can handle both IPv4 and IPv6 addresses.
There are 2 types of addresses :
Unicast — An identifier for a single interface.
Multicast — An identifier for a set of interfaces.
Factory methods.
Three commonly used InetAddress factory methods are.
a)static InetAddress getLocalHost( )throws UnknownHostException
Returns the InetAddress object that represents the localhost.
If these methods are unable to resolve the host name,they throw an UnknownHostException.
Instance Methods:-
The InetAddress class also has several other methods.
byte[ ] getAddress( )
Returns a four-element 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.
Boolean equals(Object other)
Returns true if this object has the same Internet address as other.
The URL class is a wrapper of standard URL string. It is a final class and is directly inherited from
the Object class.
This class provides a simple way of accessing information across the Internet using URLs.
URL class has following constructors,and each can throw a MalformedURLException.
1. URL(String spec)
Creates a URL object from the String representation.
Example 1:
import java.net.*;
public class URLDemo{
public static void main(String[] args){
try
{
URL url=new URL("https://msbte.org.in/file/ALearningManualBAsicScienceM_090220210025.pdf");
System.out.println("Protocol: "+url.getProtocol());
System.out.println("Host Name: "+url.getHost());
System.out.println("Port Number: "+url.getPort());
System.out.println("Default Port Number: "+url.getDefaultPort());
System.out.println("File: "+url.getFile());
}
catch(Exception e){System.out.println(e);}
}
}
URLConnection
The Java URLConnection class is an abstract class that represents a communication link
between the URL and the application. It can be used to read and write data to the specified
resource referred by the URL.
Constructor
protected URLConnection(URL url)
It constructs a URL connection to the specified URL.
Features:-
1. URLConnection is an abstract class. The two subclasses HttpURLConnection and
JarURLConnection makes the connetion between the client Java program and URL
resource on the internet.
2. With the help of URLConnection class, a user can read and write to and from any resource
referenced by an URL object.
3. Once a connection is established and the Java program has an URLConnection object, we can
use it to read or write or get further information like content length, etc.
openConnection()
The openConnection() method of the URL class returns the object of URLConnection class.
Instance of URLConnection can be obtained by calling the openConnection() method on a URL object.
InputStream getInputStream() It returns an input stream that reads from the open condition.
Program to display Date, Content Type, Content Length and Contents of Web Page.
import java.io.*;
import java.net.*;
import java.util.Date;
public class URLDemo
{
public static void main(String[] args)
{
try
{
URL url=new URL("https://msbte.ac.in/");
URLConnection con=url.openConnection();
System.out.println("Date="+new Date(con.getDate()));
System.out.println("Type of contents="+(con.getContentType()));
System.out.println("Length of contents="+(con.getContentLength()));
System.out.println("Expiration Date="+new Date(con.getExpiration()));
System.out.println("Last Modified Date="+new Date(con.getLastModified()));
/* This Block prints the contents of Web Page
InputStream stream=con.getInputStream();
int i;
while((i=stream.read())!=-1)
{
System.out.print((char)i);
}
Output:-
Date=Tue Jan 17 13:09:25 IST 2023
Type of contents=text/html
length of contents=1121949
Expiration Date=Thu Jan 01 05:30:00 IST 1970
Last Modified Date=Tue Jan 17 11:12:56 IST 2023
The following 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.
5. If communication is established, the client now has a Socket object capable of communicating
with the server.
1. Socket class
The java.net.Socket class in Java facilitates client-side TCP communication, enabling interaction
between a client and a server.
It represents a socket, which serves as an endpoint for communication between two machines over
a network.
When you create a Socket object, it implicitly establishes the connection between the client and the
server as well as send and receive data.
After you have created a socket, you can get the address and port details associated with the socket by
the use of the following methods:
1. InetAddress getInetAddress( ): It returns the InetAddress associated with the Socket object. It
returns null if the socket is not connected.
2. int getPort( ): It returns the remote port to which the invoking Socket object is connected. It
returns 0 if the socket is not connected.
3. int getLocalPort( ): Returns the local port to which the invoking Socket object is bound. It returns
-1 if the socket is not bound.
4. InputStream getInputStream( ) throws IOException: Returns the InputStream associated with
the invoking socket.
5. OutputStream getOutputStream( ) throws IOException: Returns the OutputStream associated
with the invoking socket.
6. void connect(SocketAddress endpoint) :- Connects this socket to the server.
7. void bind(SocketAddress bindpoint):- Binds the socket to a local address.
8. isConnected( ): Returns true if the socket is connected to a server
9. isBound( ): Returns true if the socket is bound to an address
10. isClosed( ): Returns true if the socket is closed.
2. ServerSocket class:-
The ServerSocket class is used to create servers that listen for either local or remote client
programs to connect to them on standard ports.
The ServerSocket object can create a Socket object to receive and transmit data through the
socket.
Constructor:-
ServerSocket(int port) throws IOException
This constructor is used to create a server socket on the specified port. It throws an IOException.
Methods:
Socket accept()
This method listens for a connection request and accepts the connection. When the connection
is accepted, a Socket object is returned, that can be used to send and receive data through the
connection.
bind(SocketAddress endpoint) Binds the ServerSocket to a specific address (IP address and
port number).
InetAddress getInetAddress()
These methods returns an IP address used by the invoking ServerSocket object.
void close()
Last method closes the socket and releases any system resources associated with it.
Creating Client:
To create the client application, we need to create the instance of Socket class. Here, we need to pass
the IP address or hostname of the Server and a port number. Here, we are using "localhost"
because our server is running on same system.
Socket s=new Socket("localhost",6666);
Let's see a simple of Java socket programming where client sends a text and server receives and prints
it.
// MyServer.java
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=dis.readLine();
System.out.println("message= "+str);
ss.close();
}
catch(Exception e)
{
System.out.println(e);
To execute this program open two command prompts and execute each program at each command
prompt.
After running the client application, a message will be displayed on the server console.
MyServer.java
import java.net.*;
import java.io.*;
class MyServer{
public static void main(String args[])throws Exception
{
ServerSocket ss=new ServerSocket(3333);
Socket s=ss.accept();
DataInputStream din=new DataInputStream(s.getInputStream());
//MyClient.java
import java.net.*;
import java.io.*;
class MyClient{
public static void main(String args[])throws Exception
{
Socket s=new Socket("localhost",3333);
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str="",str2="";
while(!str.equals("stop"))
{
str=br.readLine(); // Write something to stream
dout.writeUTF(str);
dout.flush();
dout.close();
s.close();
}
}
Methods of DatagramSocket
1. void send(DatagramPacket packet)throws IOException
This method sends the datagram’s data to the previously defined host and port by taking a
DatagramPacket object as a parameter.
Method Description
1) InetAddress It returns the IP address of the machine to which the datagram is being sent
getAddress() or from which the datagram was received.
2) byte[] getData() It returns the data contained in Datagram. This is stored in array of bytes
3) int getLength() It returns the length of the data to be sent or the length of the data received.
It returns the port number on the remote host to which the datagram is being
4) int getPort()
sent or from which the datagram was received.
5) SocketAddress It gets the SocketAddress (IP address + port number) of the remote host that
getSocketAddress() the packet is being sent to or is coming from.
6) void setAddress
It sets the IP address of the machine to which the datagram is being sent.
(InetAddress iaddr)