[go: up one dir, main page]

0% found this document useful (0 votes)
20 views62 pages

Chap 4 Networking

Uploaded by

aryankaldate6
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)
20 views62 pages

Chap 4 Networking

Uploaded by

aryankaldate6
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/ 62

Chapter No-o4

Networking
Prepared by,
Mrs Suwarna Thakre
Socket Overview
O A network socket is a lot like an electrical socket.

Various plugs around the network have a standard


way of delivering their payload. Anything that
understands the standard protocol can “plug in” to
the socket and communicate.

O With electrical sockets, it doesn’t matter if we plug

in a lamp or a toaster; as long as they are expecting


60Hz, 115-volt electricity, the devices will work.
Socket Overview
O Think how our electric bill is created. There is a meter

somewhere between house and the rest of the network.

O For each kilowatt of power that goes through that meter,

you are billed. The bill comes to your “address.” So


eventhough the electricity flows freely around the power
grid, all of the sockets in your house have a particular
address. The same idea applies to network sockets,
except we talk about TCP/IP packets and IP addresses
rather than electrons and street addresses.
Internet Protocol (IP)
O Internet Protocol (IP) is a low-level routing

protocol that breaks data into small packets


and sends them to an address across a
network, which does not guarantee to deliver
said packets to the destination.
Transmission Control
Protocol (TCP)
O 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.
User Datagram Protocol
(UDP)
O User Datagram Protocol (UDP): sits

next to TCP and can be used directly


to support fast, connectionless,
unreliable transport of packets.
Reserved Socket
Socket number between 0 to 1023
are reserved for popular application protocols
(e.g., Port 80 for HTTP,
Port 443 for HTTPS,
Port 21 for FTP,
Port 23 for Telnet
Port 25 for SMTP,
etc
Reserved Socket
O If we consider the range of the port numbers, there are
0 to 65,535 ports available. The port numbers ranging
from 0 - 1023 are reserved ports or we can say that are
restricted ports. All the 0 to 1023 ports are reserved for
use by well-known services such as FTP, telnet and http
and other system services. These ports are called well-
known ports.
The Domain Name System
(DNS)
O DNS is the phonebook of the Internet. Humans access

information online through domain names, like


nytimes.com or espn.com. Web browsers interact through
Internet Protocol (IP) addresses. DNS translates domain
names to IP addresses so browsers can load Internet
resources.
Domain Name System (DNS)
Each device connected to the Internet has a unique IP
address which other machines use to find the device.
DNS servers eliminate the need for humans to
memorize IP addresses such as 192.168.1.1 (in IPv4),
or more complex newer alphanumeric IP addresses
such as 2400:cb00:2048:1::c629:d7a2 (in IPv6).
InetAddress
The InetAddress class has no visible
constructors. To create an InetAddress
object,we have to use one of the
available factory methods.
Methods of InetAddress Class
O static InetAddress getLocalHost( )throws

UnknownHostException

It simply returns the InetAddress object that represents the


local host.

O static InetAddress getByName(String hostName)throws

UnknownHostException

It returns an InetAddress for a host name passed to it.


Methods of InetAddress Class
O 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. It will
also throw an UnknownHostException if it can’t resolve
the name to at least one address.
The InetAddress class has
several other methods,
O public String getHostName():-it returns the

host name of the IP address.

O public String getHostAddress():-it returns the

IP address in string format.


Program Using InetAddress
// Demonstrate InetAddress. System.out.println("Host
name"+Address.getHostName());
import java.net.*;
System.out.println("Host
class InetAddressTest1 address"+Address.getHostAddress());
{
InetAddress SW[] =
public static void main(String args[]) InetAddress.getAllByName("www.google
throws UnknownHostException .com");
for (int i=0; i<SW.length; i++)
{ System.out.println(SW[i]);
InetAddress Address = }}
InetAddress.getLocalHost();
System.out.println(Address); C:\jdk1.8.0_121\bin>javac InetAddressTest1.java
C:\jdk1.8.0_121\bin>java InetAddressTest1
Address = CO-HOD/192.168.0.104
yahoo.com/74.6.143.26
InetAddress.getByName("yahoo.com"); Host nameyahoo.com
Host address74.6.143.26
System.out.println(Address); www.google.com/172.217.166.68
socket
O Client and server Establish connections and communicate via

socket

O 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.

O 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.
socket
O 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.
TCP/IP Client Socket

O TCP/IP sockets are used to implement reliable,


bidirectional, persistent, point-to- point,stream-
based connections between hosts on the
Internet. A socket can be used to connect Java’s
I/O system to other programs that may reside
either on the local machine or on any other
machine on the Internet.
Socket Constructor
There are two kinds of TCP sockets in Java. One is for servers,
and the other is for clients.
O Client socket is created by using Socket class Here are two
constructors used to create client sockets:
Socket(String hostName, int port)
Creates a socket connecting the local host to the named host
and port, can throw anUnknownHostException or an
IOException.
Socket Constructor
O This method attempts to connect to the specified server at
the specified port. If this constructor does not throw an
exception, the connection is successful and the client is
connected to the server.
O Socket(InetAddress ipAddress, int port)

Creates a socket using a preexisting InetAddress


object and a port, can throw an IOException.
This method is identical to the previous constructor, except
that the host is denoted by an InetAddress object.
A socket can be examined at any time for the
address and port information associated with
it, by using following methods
O InetAddress getInetAddress( ) Returns the
InetAddress associated with the Socket object.

O int getPort( ) Returns the remote port to which this


Socket object is connected.

O int getLocalPort( ) Returns the local port to which


this Socket object is connected
ServerSocket
ServerSockets are quite different from normal Sockets.
When we create a ServerSocket, it will register itself
with the system as having an interest in client
connections.
The constructors for ServerSocket reflect the port
number that we wish to accept connections on and,
optionally, how long we want the queue for said port to
be.
ServerSocket
O Once the Socket object has been created, it can also be
examined to gain access to the input and output streams
associated with it. Each of these methods can throw
anIOException if the sockets have been invalidated by a loss of
connection on the Net. These streams are used exactly like the
I/O streams to send and receive data.
O InputStream getInputStream( )

Returns the InputStream associated with the invoking socket.


O OutputStream getOutputStream( )

Returns theOutputStream associated with the invoking socket.


The following steps occur when establishing a TCP connection between
two computers using sockets −
• The server instantiates a ServerSocket object, denoting which port number
communication is to occur on.
• The server invokes the accept() method of the ServerSocket class. This method
waits until a client connects to the server on the given port.
After the server is waiting, a client instantiates a Socket object, specifying the
server name and the port number to connect to.
• 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.
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.
Continue..
O 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.
O TCP is a two-way communication protocol, hence data
can be sent across both streams at the same time.
Constructors of ServerSocket
O ServerSocket(int port) throws IOException

Attempts to create a server socket bound to the specified port


with a queue length of 50. An exception occurs if the port is
already bound by another application.
O ServerSocket(int port, int maxQueue)throws IOException

Similar to the previous constructor, the maxqueue


parameter specifies how many incoming clients to store
in a wait queue.
Constructors of ServerSocket
O ServerSocket(int port, int maxQueue,InetAddress
localAddress) throws IOException
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.
TCP/IP Server Sockets

O The queue length tells the system how

many client connections it can leave


pending before it should simply refuse
connections. The default is 50. The
constructors might throw an IOException.
Methods Of Server Sockets

O public int getLocalPort()

Returns the port that the server socket is listening on. This method is useful if
you passed in 0 as the port number in a constructor and let the server find a
port for you.
O 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.
//program for client
import java.net.*;
import java.io.*;
public class client1
{ public static void main(String args[])
{ try
{ Socket ss=new Socket("127.0.0.1",3456);
InputStream is=ss.getInputStream();
OutputStream os=ss.getOutputStream();
DataInputStream dis=new DataInputStream(is);
DataOutputStream dos=new DataOutputStream(os);
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("enter string");
String line=br.readLine();
dos.writeUTF(line);
String str=dis.readUTF();
System.out.println(str);}
catch(Exception e){} } }
//Server Side
import java.net.*;import java.io.*;
public class server1
{ public static void main(String args[])
{ try
{ ServerSocket ss=new ServerSocket(3456);
Socket s1=ss.accept();
System.out.println("Got Client");
InputStream is=s1.getInputStream();
OutputStream os=s1.getOutputStream();
DataInputStream dis=new DataInputStream(is);
DataOutputStream dos=new DataOutputStream(os);
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
String line=dis.readUTF();
System.out.println(line);
System.out.println("Enter Data");
String str=br.readLine();
dos.writeUTF(str); }
catch(Exception e) {}} }
OUTPUT
Uniform Resource Locator
(URL)
O URL: It is used to identify the
information on the Web.

O A URL specification is based on four

components.

O Protocol,host,port and file name


Uniform Resource Locator
(URL)
O Examples of URLs are
O http://www.osborne.com/
O http://www.osborne.com:80/index.html.
O Example
O http://www.osborne.com:80/index.htm.
Uniform Resource Locator
(URL)
O The first is the protocol to use, separated

from the rest of the locator by a colon (:).


Common protocols are http,ftp,smtp etc,
although these days almost everything is
being done via HTTP,e.g.HTTP
Uniform Resource Locator
(URL)
The second component is the host name or IP
address of the host to use. This is delimited on
the left by double slashes (//) and on the right
by a slash (/) or optionally a colon (:).

e.g. www.osborne.com:80
Uniform Resource Locator
(URL)
O Third component, the port number, is an
optional parameter, delimited on the left
from the host name by a colon (:) and on the
right by a slash (/).It defaults to port 80, the
predefined HTTP port.
O The fourth part is the actual file path
Methods of URL Class
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 String toExternalForm() The toExternalForm() function is a part of URL


class. The function toExternalForm() returns
the string representation of a specified URL

public int getDefaultPort() Returns the default port for the protocol of
the URL.
URL Constructors
O URL(String urlSpecifier) throws MalformedURLException

Creates a URL from the given String.

O URL(String protocolName, String hostName, int port, String

path) throws MalformedURLException

Creates a URL object from protocol, host, port and file name.
URL Constructors
O URL(String protocolName, String hostName, String
path) throws MalformedURLException
Identical to the previous constructor, except that
the default port for the given protocol is used.
O URL(URL urlObj, String urlSpecifier) throws
MalformedURLException
use an existing URL as a reference context and then
create a new URL from that context..
Program Using URL Class
import java.net.*;

class urldemo12346

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

{URL hp = new URL("https:// www.geeksforgeeks.org/download");

System.out.println("Protocol: " + hp.getProtocol());

System.out.println("Port: " + hp.getPort());

System.out.println("Host: " + hp.getHost());

System.out.println("File: " + hp.getFile());

System.out.println("Ext:" + hp.toExternalForm());

System.out.println("default port" +hp.getDefaultPort());}}


OUTPUT
C:\jdk1.8.0_181\bin>javac urldemo12346.java

C:\jdk1.8.0_181\bin>java urldemo12346
Protocol: https
Port: -1
Host: www.geeksforgeeks.org
File: /download
Ext:https:// www.geeksforgeeks.org/download
default port443
Notice that the port is –1; this means that one was not
explicitly set.
Program Using URL Class
/URLDemo.java }
import java.io.*;
import java.net.*;
catch(Exception e)
public class urldemo1 {System.out.println(e);
{ }
public static void main(String[] args)
{ }
try }
{
String p="http";
String name="www.nba.com"; C:\jdk1.2.2\bin>javac urldemo1.java
String file="xyz//html";
URL url=new URL(p,name,file);
C:\jdk1.2.2\bin>java urldemo1
System.out.println("Protocol: "+url.getProtocol()); Protocol: http
System.out.println("Host Name: "+url.getHost()); Host Name: www.nba.com
System.out.println("Port Number: "+url.getPort());
System.out.println("File Name: "+url.getFile());
Port Number: -1
File Name: xyz//html
URLConnection
O URLConnection is a general-purpose class for

accessing the attributes of a remote resource.


Once you make a connection to a remote server,
we can use URLConnection to inspect the
properties of the remote object before actually
transporting it locally.
URLConnection
O To access the actual bits or content information of a
URL, we create a URLConnection object from it,
using its openConnection( )method
O Syntax:

URLConnection openConnection( )
It returns a URLConnection object associated with the
invoking URL object. It may throw an IOException.
Methods Of URLConnection
O public String getContentType()Returns the value of

the content-type header field.

O public long getExpiration()Returns the value of

the expires header field.

O public long getDate()Returns the value of

the date header field.


Methods Of URLConnection
O public long getLastModified()Returns the value of

the last-modified header field. The result is the


number of milliseconds since January 1, 1970
GMT.

O public int getContentLength()Returns the value of

the content-length header field.


Program Using URLConnection
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;

public class urlopen1


{

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


{

URL u = new URL("http://www.google.com");


URLConnection uc = u.openConnection();
System.out.println("Content-type: " + uc.getContentType());
System.out.println("Date: " + new Date(uc.getDate()));
System.out.println("Last modified: " + new Date(uc.getLastModified()));
System.out.println("Expiration date: " + new Date(uc.getExpiration()));
System.out.println("Content-length: " + uc.getContentLength());
}
}
OUTPUT
C:\jdk1.2.2\bin>java urlopen1
Content-type: text/html; charset=ISO-8859-1
Date: Tue Oct 20 15:58:13 GMT+05:30 2020
Last modified: Thu Jan 01 05:30:00 GMT+05:30 1970
Expiration date: Thu Jan 01 05:30:00 GMT+05:30 1970
Content-length: -1
Datagrams
O Datagrams are bundles of information passed

between machines.

O There is no assurance that it will arrive or even that

someone will be there to catch it. Likewise,when the


datagram is received, there is no assurance that it
hasn’t been damaged in transit or that whoever
sent it is still there to receive a response.
Datagrams
Datagrams are bundles of information passed between
machines. Once the datagram has been released to its
intended target, there is no assurance that it will arrive
or even that someone will be there to catch it. Likewise,

when the datagram is received, there is no assurance


that it hasn’t been damaged in transit or that whoever
sent it is still there to receive a response.
Datagrams

O Java implements datagrams on top of the

UDP protocol by using two classes:

O The DatagramPacket object is the data

container, while the DatagramSocket is the


mechanism used to send or receive the
DatagramPackets.
DatagramPacket defines
several constructors.
O Java DatagramPacket is a message that can be sent or
received. If we send multiple packet, it may arrive in any order.
Additionally, packet delivery is not guaranteed.
O DatagramPacket(byte data[ ], int size)

constructor specifies a buffer that will receive data, and the size of
a packet. It is used for receiving data over a DatagramSocket.
O DatagramPacket(byte data[ ], int offset, int size)
offset into the buffer at which data will be stored.
DatagramPacket Constructors
O DatagramPacket(byte data[ ], int size,
InetAddress ipAddress, int port)
The third form specifies a target address and
port, which are used by a DatagramSocket to
determine where the data in the packet will be
sent.
.
DatagramPacket Constructors
O DatagramPacket(byte data[ ], int offset, int size,

InetAddress ipAddress, int port)

The fourth form transmits packets beginning at the


specified offset into the data.
Methods of DatagramPacket.

O InetAddress getAddress( ) Returns the destination

InetAddress, typically used for sending.

O 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.
Methods of DatagramPacket
O int getLength( )
Returns the length of the valid data contained
in the byte array that would be returned from
the getData( ) method

O int getPort( ) Returns the port number.


Constructors of DatagramSocket

O DatagramSocket class represents a connection-less


socket for sending and receiving datagram packets.
O A datagram is basically an information but there is
no guarantee of its content, arrival or arrival time.
O Ist datagram socket object is created to carry the
packet to the destination and to receive it whenever
server send any data

.
Constructors of DatagramSocket
O DatagramSocket() throws SocketEeption: it creates a
datagram socket and binds it with the available Port
Number on the localhost machine
O DatagramSocket(int port) throws SocketEeption: it
creates a datagram socket and binds it with the given
Port Number.
O DatagramSocket(int port, InetAddress address)
throws SocketEeption: it creates a datagram socket
and binds it with the specified port number and host
address.
//program for UDP client
import java.net.*;
public class udpclient
{
public static void main(String[] args) throws Exception
{
DatagramSocket ds = new DatagramSocket();
String str = "hello world";
InetAddress ip = InetAddress.getLocalHost();

DatagramPacket dp = new DatagramPacket(str.getBytes(),


str.length(), ip, 3000);
ds.send(dp);
//ds.close();
}
}
Str.getBytes() convert string to byte array
//Program for UDP SERVER
import java.net.*;
public class udpserver
{
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();
} }
Constructor of String(byte []bytes,int offset,int length)
getLength():returns the length of the data to be sent or the len
gth of the data to be received.
OUTPUT OF UDP

You might also like