0% found this document useful (0 votes)
41 views47 pages

Unit-4 Networking

This document discusses networking concepts like ports, sockets, proxy servers, and addressing in Java. It provides details on ports and their numbering, the socket mechanism for inter-process communication, the role of a proxy server, interfaces and classes in the java.net package related to networking, and methods in the InetAddress class for working with IP addresses and domain names.

Uploaded by

Shashikant More
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views47 pages

Unit-4 Networking

This document discusses networking concepts like ports, sockets, proxy servers, and addressing in Java. It provides details on ports and their numbering, the socket mechanism for inter-process communication, the role of a proxy server, interfaces and classes in the java.net package related to networking, and methods in the InetAddress class for working with IP addresses and domain names.

Uploaded by

Shashikant More
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Unit -4 Networking

Mundhe Shankar Gangadharrao


Lecturer In Information Technology
Government Polytechnic Nanded
Client-Server
Ports
• When a computer system seeks to connect to another computer, the port
serves as a communication endpoint.

• Port is a 16-bit unsigned integer number from 1 to 65535.

• Port number is a logical address assigned for each application on computer


hardware that uses the Internet for the communication process.

• Port number is unique for every application on a computer device. However,


the operating system can automatically assign a port number.

• Well-known ports—Ports in the range 0 to 1023 are assigned and controlled.


• Registered ports—Ports in the range 1024 to 49151 are not assigned or
controlled, but can be registered to prevent duplication.
• Dynamic ports—Ports in the range 49152 to 65535 are not assigned,
controlled, or registered.
Sockets

The socket mechanism provides a means of inter-process communication (IPC) by


establishing named contact points between which the communication take place.
Proxy Server
• The proxy server is a computer on the internet that accepts the incoming
requests from the client and forwards those requests to the destination
server.

• It works as a gateway between the end-user and the internet.

• It has its own IP address.

• It separates the client system and web server from the global network.

• In other words, we can say that the proxy server allows us to access any
websites with a different IP address.

• It plays an intermediary role between users and targeted websites or servers.


It collects and provides information related to user requests.
• The most important point about a proxy server is that it does not encrypt
traffic.
Proxy Server
Interfaces in java.net package
Interface Description
ContentHandlerFactory This interface defines a factory for content
handlers.
CookiePolicy CookiePolicy implementations decide which
cookies should be accepted and which should
be rejected.
CookieStore A CookieStore object represents a storage for
cookie.
DatagramSocketImplFactory This interface defines a factory for datagram
socket implementations.
FileNameMap A simple interface which provides a mechanism
to map between a file name and a MIME type
string.
ProtocolFamily Represents a family of communication
protocols.
SocketImplFactory This interface defines a factory for socket
implementations.
SocketOption<T> A socket option associated with a socket.
Classes in java.net package
Class Description

Authenticator The class Authenticator represents an object that knows how to obtain
authentication for a network connection.
CacheRequest Represents channels for storing resources in the ResponseCache.

CacheResponse Represent channels for retrieving resources from the ResponseCache.

ContentHandler The abstract class ContentHandler is the superclass of all classes that read
an Object from a URLConnection.
CookieHandler A CookieHandler object provides a callback mechanism to hook up a HTTP state
management policy implementation into the HTTP protocol handler.
CookieManager CookieManager provides a concrete implementation of CookieHandler, which
separates the storage of cookies from the policy surrounding accepting and
rejecting cookies.
DatagramPacket This class represents a datagram packet.

DatagramSocket This class represents a socket for sending and receiving datagram packets.

DatagramSocketImpl Abstract datagram and multicast socket implementation base class.

HttpCookie An HttpCookie object represents an HTTP cookie, which carries state information
between server and user agent.
HttpURLConnection A URLConnection with support for HTTP-specific features.

IDN Provides methods to convert internationalized domain names (IDNs) between a


normal Unicode representation and an ASCII Compatible Encoding (ACE)
representation.
Inet4Address This class represents an Internet Protocol version 4 (IPv4) address.

Inet6Address This class represents an Internet Protocol version 6 (IPv6) address.


Class Name Description
InetAddress This class represents an Internet Protocol (IP) address.

InetSocketAddress This class implements an IP Socket Address (IP address + port number) It can
also be a pair (hostname + port number), in which case an attempt will be
made to resolve the hostname.
InterfaceAddress This class represents a Network Interface address.

JarURLConnection A URL Connection to a Java ARchive (JAR) file or an entry in a JAR file.

MulticastSocket The multicast datagram socket class is useful for sending and receiving IP
multicast packets.
NetPermission This class is for various network permissions.

NetworkInterface This class represents a Network Interface made up of a name, and a list of IP
addresses assigned to this interface.
PasswordAuthentication The class PasswordAuthentication is a data holder that is used by
Authenticator.
Proxy This class represents a proxy setting, typically a type (http, socks) and a socket
address.
ProxySelector Selects the proxy server to use, if any, when connecting to the network
resource referenced by a URL.
ResponseCache Represents implementations of URLConnection caches.

SecureCacheResponse Represents a cache response originally retrieved through secure means, such
as TLS.
ServerSocket This class implements server sockets.

Socket This class implements client sockets (also called just "sockets").
SocketAddress This class represents a Socket Address with no protocol
attachment.
SocketImpl The abstract class SocketImpl is a common superclass of all classes that
actually implement sockets.
SocketPermission This class represents access to a network via sockets.

StandardSocketOptions Defines the standard socket options.

URI Represents a Uniform Resource Identifier (URI) reference.

URL Class URL represents a Uniform Resource Locator, a pointer to a


"resource" on the World Wide Web.
URLClassLoader This class loader is used to load classes and resources from a search
path of URLs referring to both JAR files and directories.

URLConnection The abstract class URLConnection is the superclass of all classes that
represent a communications link between the application and a URL.

URLDecoder Utility class for HTML form decoding.

URLEncoder Utility class for HTML form encoding.

URLPermission Represents permission to access a resource or set of resources defined


by a given url, and for a given set of user-settable request methods and
request headers.
URLStreamHandler The abstract class URLStreamHandler is the common superclass for all
stream protocol handlers.
Addressing
IPv4 address range
Internet Addressing
• Handling internet addresses (domain names, and IP addresses) is made
easy with Java. Internet addresses are represented in Java by the
InetAddress class.
• InetAddress provides simple methods to convert between domain names,
and numbered addresses.

• InetAddress
• The InetAddress class is used to encapsulate both the numerical IP
address and the domain name for that address.

• We interact with this class by using the name of an IP host, which is more
convenient and understandable than its IP address.


• InetAddressClass
static methods you can use to create new
InetAddress objects.
• –getByName(String host)
• –getAllByName(String host)
• –getLocalHost()
• InetAddress x = InetAddress.getByName( “msbte.com”);
• Throws UnknownHostException
• Factory Methods

• static InetAddress getLocalHost( ) throws UnknownHostException


– –returns the IP address of the localhost machine.

• static InetAddress getByName(String hostName)throws UnknownHostException


–returns an InetAddress instance representing the hostname.

static InetAddress[ ] getAllByName(String hostName) throws UnknownHostException


– –returns an array of InetAddress instances representing the hostname.
class InetAddressTest
{
public static void main(String args[]) throws UnknownHostException
{
InetAddress Address = InetAddress.getLocalHost();
System.out.println(Address);
Address = InetAddress.getByName("www.javatpont.com");
System.out.println(Address);
InetAddress SW[] = InetAddress.getAllByName("www.yahoo.com");

for (int i=0; i<SW.length; i++)


System.out.println(SW[i]);
}
} DESKTOP-QS72KVS/192.168.1.93
www.javatpont.com/103.224.182.251
www.yahoo.com/202.165.107.49
www.yahoo.com/202.165.107.50
www.yahoo.com/2406:2000:e4:1605:0:0:0:9001
www.yahoo.com/2406:2000:e4:1605:0:0:0:9000
• Instance Methods

• boolean equals(Object obj)


• –Compares two IP addresses, returns true if there is a match.

• byte[ ] getAddress( )
• –Returns the IP address in byte format.

• String getHostAddress( )
• –Returns the IP address in dotted decimal format.

• String getHostName( )
• –Returns the hostname of the InetAddress.

• boolean isMulticastAddress( )
• –Returns true if the InetAddress is a multicast address (class D address).

• String toString()
• –Converts this IP address to a String.
class InetAddressTest1
{
public static void main(String args[])throws UnknownHostException
{
InetAddress Address = InetAddress.getByName("www.google.com");
System.out.println(Address.getHostAddress());
System.out.println(Address.getHostName());
if(Address.isMulticastAddress())
System.out.println("It is multicast address");
}
}

216.58.203.4
www.google.com
Server socket
• The constructors used to server socket are given below. All of them throw IO
Exception

• ServerSocket (int port) throws BindException, IOException


– creates a server socket bounded to the specified port with a queue length 50.

• ServerSocket (int port, int maxQueue) throws BindException, IOException


– creates a server socket bounded to the specified port with a queue length of maxQueue.

• ServerSocket (int port, int maxQ, InetAddress ip) throws IOException


– creates a server socket bounded to the specified port with a queue length of maxQueue. On a
multihomed host, ip specifies the IP Address to which this socket binds.
Methods of ServerSocket class
• boolean getReuseAddress()--Tests if SO_REUSEADDR is enabled.
• int getSoTimeout()--Retrieve setting for SO_TIMEOUT.
• protected void implAccept (Socket s)
– Subclasses of ServerSocket use this method to override accept() to return their own subclass
of socket.
• boolean isBound ()--Returns the binding state of the ServerSocket.
• boolean isClosed ()--Returns the closed state of the ServerSocket.
• void setPerformancePreferences (int connectionTime, int latency, int bandwidth)
– Sets performance preferences for this ServerSocket.
• void setReceiveBufferSize (int size)
– Sets a default proposed value for the SO_RCVBUF option for sockets accepted from
this ServerSocket.
• void setReuseAddress (boolean on)
– Enable/disable the SO_REUSEADDR socket option.
• static void setSocketFactory ( SocketImplFactory fac)
– Sets the server socket implementation factory for the application.
• void setSoTimeout (int timeout)
– Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds.
• String toString ()
– Returns the implementation address and implementation port of this socket as a String.
• Socket accept()
– Listens for a connection to be made to this socket and accepts it.

• void bind(SocketAddress endpoint)


– Binds the ServerSocket to a specific address (IP address and port number).

• void bind(SocketAddress endpoint, int backlog)


– Binds the ServerSocket to a specific address (IP address and port number).

• void close() -Closes this socket.

• ServerSocketChannel getChannel ()
– Returns the unique ServerSocketChannel object associated with this socket, if any.

• InetAddress getInetAddress()
– Returns the local address of this server socket.

• int getLocalPort() -Returns the port number on which this socket is listening.

• SocketAddress getLocalSocketAddress()
– Returns the address of the endpoint this socket is bound to.

• int getReceiveBufferSize()
– Gets the value of the SO_RCVBUF option for this ServerSocket, that is the proposed buffer size that
will be used for Sockets accepted from this ServerSocket.
Client socket

• The constructors used to serve socket are given below. All of them throw IO
Exception

• public Socket(String host, int port) throws UnknownHostException,


IOException.
– Creates a socket connecting to the local host to the named host and port

• public Socket(InetAddress host, int port) throws IOException


– Creates a socket using a preexisting InetAddress and port
• Socket class Methods
• void bind (SocketAddress bindpoint)--Binds the socket to a local address.
• void close()----Closes this socket.
• void connect ( SocketAddress endpoint)--Connects this socket to the server.
• void connect ( SocketAddress endpoint, int timeout)
– Connects this socket to the server with a specified timeout value.
• SocketChannel getChannel()
– Returns the unique SocketChannel object associated with this socket, if any.
• InetAddress getInetAddress()
– Returns the address to which the socket is connected.
• InputStream getInputStream()----Returns an input stream for this socket.
• boolean getKeepAlive()-----Tests if SO_KEEPALIVE is enabled.

• InetAddress getLocalAddress()
– Gets the local address to which the socket is bound.
• int getLocalPort()
• Returns the local port number to which this socket is bound.
• SocketAddress getLocalSocketAddress()
– Returns the address of the endpoint this socket is bound to.
• boolean getOOBInline ()---Tests if SO_OOBINLINE is enabled.
• OutputStream getOutputStream ()----Returns an output stream for this socket.
• int getPort()--Returns the remote port number to which this socket is connected.
• int getReceiveBufferSize()Gets the value of the SO_RCVBUF option for
this Socket, that is the buffer size used by the platform for input on this Socket.
• SocketAddress getRemoteSocketAddress()Returns the address of the endpoint
this socket is connected to, or null if it is unconnected.
• boolean getReuseAddress()-----Tests if SO_REUSEADDR is enabled.
• int getSendBufferSize()
– Get value of the SO_SNDBUF option for this Socket, that is the buffer size used by the platform
for output on this Socket.
• int getSoLinger()----Returns setting for SO_LINGER.
• int getSoTimeout()----Returns setting for SO_TIMEOUT.
• boolean getTcpNoDelay()----Tests if TCP_NODELAY is enabled.
• int getTrafficClass()Gets traffic class or type-of-service in the IP header for packets
sent from this Socket
• booleanisBound()Returns the binding state of the socket.

• boolean isClosed()Returns the closed state of the socket.


• boolean isConnected()Returns the connection state of the socket.
• boolean isInputShutdown()Returns whether the read-half of the socket connection is closed.
• boolean isOutputShutdown()Returns whether the write-half of the socket connection is closed.

• void sendUrgentData(int data)Send one byte of urgent data on the socket.


• void setKeepAlive(boolean on)Enable/disable SO_KEEPALIVE.
• void setOOBInline(boolean on)Enable/disable SO_OOBINLINE (receipt of TCP urgent data) By default, this
option is disabled and TCP urgent data received on a socket is silently discarded.
• void setPerformancePreferences(int connectionTime, int latency, int bandwidth)
– Sets performance preferences for this socket.

• void setReceiveBufferSize(int size)Sets the SO_RCVBUF option to the specified value for this Socket.
• void setReuseAddress(boolean on)Enable/disable the SO_REUSEADDR socket option.
• void setSendBufferSize(int size)Sets the SO_SNDBUF option to the specified value for this Socket.
• static void setSocketImplFactory(SocketImplFactory fac)
– Sets the client socket implementation factory for the application.
• void setSoLinger(boolean on, int linger)
– Enable/disable SO_LINGER with the specified linger time in seconds.
• void setSoTimeout(int timeout)Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds.
• void setTcpNoDelay(boolean on)Enable/disable TCP_NODELAY (disable/enable Nagle's algorithm).
• void setTrafficClass(int tc)Sets traffic class or type-of-service octet in the IP header for packets sent from
this Socket.
• void shutdownInput()Places the input stream for this socket at "end of stream".
• void shutdownOutput()Disables the output stream for this socket.
• StringtoString()Converts this socket to a String.
Programming TCP Client-Server in Java

• •All the classes related to sockets are in the java.net package,


• All the input/output stream classes are in the java.io package

•How to open a socket?


–If you are programming a client, then you would create an object of Socket class
–Machine name is the machine you are trying to open a connection to,
–PortNumber is the port (a number) on which the server you are trying to connect
to is running.

Socket MyClient;
try {
MyClient = new Socket("Machine name", PortNumber);
} catch (IOException e) {
System.out.println(e);
}
File: 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=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
} catch(Exception e) {
System.out.println(e);
}
}
}
MyClient.java
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);
}
}
}
Programs
URL class
Constructors of URL class

•URL (String urlspecifier)


–Creates a URL object from the String representation.

•URL (String protocol, String host, int port, String file)


–Creates a URL object from the specified protocol, host,
portnumber, and file.

•URL (String protocol, String host, String file)


–Creates a URL from the specified protocol name, host name, and
file name.

•URL (URL urlObj, String urlspecifier)


–Creates a URL by parsing the given spec within a specified
context.
• Important Methods of URL class
•getProtocol()
–Returns protocol of URL
•getHost()
–Returns hostname(domain name) of URL
•getPort()
–Returns port number of URL
•getFile()
–Returns filename of URL
•public URLConnection openConnection() throws IOException
–Creates (if not already in existance) a URLConnection object that
contains a connection to the remote object referred to by the
URL.
•public final Object getContent() throws IOException
–Gets the contents from this opened connection.
•public final InputStream openStream() throws IOException
–Opens an input stream.
import java.net.*;.
class Test {
public static void main(String[] arg) throws MalFormedURLException {
URL hp = New URL("http://www.google.com");
System.out.println(hp.getProtocol());
System.out.println(hp.getFile());
}
}
URL Connection Class

•The abstract class URLConnection is the superclass of all classes that represent a
communications link between the application and a URL.
Instances of this class can be used both to read from and to write to the resource
referenced by the URL.

• Constructor of URLConnection class

• protected URLConnection(URL url)


• –Constructs a URL connection to the specified URL. A connection to the object
referenced by the URL is not created.
• Methods of URLConnection class

•public abstract void connect()throws IOException


–Opens a communications link to the resource referenced by this URL.
•public URL getURL()
–Returns the value of this URLConnection's URL field.
•public int getContentLength()
–Returns the value of the content-length header field.
•public String getContentType()
–Returns the value of the content-type header field.
•public long getDate()
–Returns the value of the date header field.
•public Object getContent()throws IOException
–Retrieves the contents of this URL connection.
•public InputStream getInputStream()throws IOException
–Returns an input stream that reads from this open connection.
•public OutputStream getOutputStream()throws IOException
–Returns an output stream that writes to this connection.
DataGrams
• A datagram is an independent, self-contained message sent over the network
whose arrival, arrival time, and content are not guaranteed.

• Datagrams are bundles of information passed between machines.

• Java implements datagrams on top of the UDP (User Datagram Protocol) protocol
by using two classes:

• DatagramPacket- object is the data container.

• DatagramSocket-is the mechanism used to send or receive the datagramPackets.


DatagramSocket Class
• Constructors

• DatagramSocket( ) throws SocketException : It creates a DatagramSocket


bound to any unused port on the local computer.

• DatagramSocket(int port) throws SocketException : It creates a


DatagramSocket bound to the port specified by port.

• DatagramSocket(int port, InetAddress ipAddress) throws SocketException :


– It constructs a DatagramSocket bound to the specified port and InetAddress.

• DatagramSocket(SocketAddress address) throws SocketException :


– It constructs a DatagramSocket bound to the specified SocketAddress.
• DatagramSocket defines many methods. Two of the most important are send( )
and receive( )

• void send(DatagramPacket packet) throws IOException


• void receive(DatagramPacket packet) throws IOException

• InetAddress getInetAddress( ) If the socket is connected, then the address is


returned. Otherwise, null is returned.
• int getLocalPort( ) Returns the number of the local port.
• int getPort( )Returns the number of the port to which the socket is connected. It
returns –1 if the socket is not connected to a port.
• boolean isBound( )
– Returns true if the socket is bound to an address. Returns false otherwise.
• boolean isConnected( )
– Returns true if the socket is connected to a server. Returns false otherwise.
• void setSoTimeout(int millis)
– throws SocketExceptionSets the time-out period to the number of milliseconds passed in millis.
DatagramPacket Class
• Few constructors

• DatagramPacket(byte data[ ], int size) :


– It specifies a buffer that will receive data and the size of a packet. It is used for receiving data
over a DatagramSocket

• DatagramPacket(byte data[ ], int offset, int size) :


– It allows you to specify an offset into the buffer at which data will be stored.

• DatagramPacket(byte data[ ], int size, InetAddress ipAddress, int port) :


– It specifies a target address and port, which are used by a DatagramSocket to determine where
the data in the packet will be sent.

• DatagramPacket(byte data[ ], int offset, int size, InetAddress ipAddress, int port) :
– It transmits packets beginning at the specified offset into the data.

• DatagramPacket(byte[] buf, int length)


– Constructs a DatagramPacket for receiving packets of length length.
• DataGramPacket methods
• InetAddress getAddress( ) Returns the address of the source (for datagrams
being received) or destination (for datagrams being sent).
• byte[ ] getData( ) Returns the byte array of data contained in the datagram.
Mostly used to retrieve data from the datagram after it has been received.
• int getLength( ) Returns the length of the valid data contained in the byte array
that would be returned from the getData( ) method. This may not equal the
length of the whole byte array.
• int getOffset( )
– Returns the starting index of the data.
• int getPort( ) Returns the port number.
• void setAddress(InetAddress ipAddress)
– Sets the address to which a packet will be sent. The address is specified by ipAddress.
• void setData(byte[ ] data)
– Sets the data to data, the offset to zero, and the length to number of bytes in data.
• void setData(byte[ ] data, int idx, int size)
– Sets the data to data, the offset to idx, and the length to size.
• void setLength(int size) Sets the length of the packet to size.
• void setPort(int port) Sets the port to port.
Example of Sending DatagramPacket by DatagramSocket

import java.net.*;

public class DSender{


public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket();
String str = "Welcome java";
InetAddress ip = InetAddress.getByName("127.0.0.1");

DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 3000);


ds.send(dp);
ds.close();
}
}
Example of Receiving DatagramPacket by DatagramSocket
import java.net.*;

public class DReceiver{

public static void main(String[] args) throws Exception {

DatagramSocket ds = new DatagramSocket(3000);


byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, 1024);
ds.receive(dp);
String str = new String(dp.getData(), 0, dp.getLength());
System.out.println(str);
ds.close();

}
}
String(byte[] bytes, int offset, int length)
Constructs a new String by decoding the specified subarray of bytes using the platform's default charset.
• The end

You might also like