Chapter4 NW

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 53

Ch-04

Networking Basics
Marks:10
Prepared by :
Prof. Biradar R.Y.
Socket
A socket is one endpoint of a two-way
communication link between two programs
running on the network.
 A socket is bound to a port number.
 Port is represented by a positive (16-bit)
integer value.
 Sockets provide the communication
mechanism between two computers using
TCP/IP.
 Socket is a combination of an IP address and a
port number.

2
Protocol
 A protocol is a set of rules basically that is
followed for communication.
 IP (Internet Protocol): Low level routing protocol.
Divides data into small packets and send on given
address. It does not guarantee to deliver the
packets.
 Transmission Control Protocol (TCP): Higher level
protocol. Reliability to deliver data. Connection
oriented protocol.
 User Datagram Protocol (UDP): Next to TCP. It
support fast, connectionless, unreliable transport
of data packets.
3
 Transmission Control Protocol (TCP)
Example: HTTP, FTP, and Telnet.

 User Datagram Protocol (UDP):


Example:Clock server and
Ping.

4
Difference Between TCP & UDP
TCP UDP
Connection oriented Connectionless
Reliable Unreliable
Retransmit No retransmission
Slower data transmission Faster data transmission
Require more cost Less cost than TCP
Gives acknowledgement No acknowledgement

TCP header size is 20 bytes. UDP Header size is 8 bytes.


TCP is heavy-weight. UDP is lightweight.
TCP is used by HTTP, HTTPs, UDP is used by DNS, DHCP,
FTP, SMTP and Telnet SNMP, RIP
5
IP Address
 number identifying of a computer on the Internet
 unique number assigned to a node of a network
 range from 0 to 255.
 Known as logical address
 Can be changed
 IP Address Classes
1. Class A : 1 to 126
2. Class B : 128 to 191
3. Class C : 192 to 223
4. Class D : 224 to239
5. Class E : 240 to254
IP Address
 Ranges 127.x.x.x are reserved for the loopback
or localhost,
for example, 127.0.0.1 is the loopback
address.
 Range 255.255.255.255 broadcasts to all hosts
on the local network.

 IP address: 2 version
 IPv4 : 32–bits and in decimal (Now)
 IPv6 : 128-bits and in hexadecimal (Future)
Port
 used to uniquely identify different
applications
 acts as a communication endpoint between
applications.
 associated with the IP address for
communication between two applications.
 Port is of 16-bit address.

8
Reserved Ports
 Ports are used to identify right application.
 IP address is used to identify right computer.
 Port number range : 0 to 65535
 1024 ports are reserved.
 Port numbers between 0 and 1,023 are reserved for
standard services, such as email, FTP, and HTTP.
Protocol Reserved Port
FTP 21
Telnet 23
SMTP 25
HTTP 80
Proxy Server
 It is mediator between real web server
and
a client applications like web browser.

Mr. Nilesh
Vishwasra
Features of Proxy Server
 Filters specific request
 stores data in catche for future use
 Improving performance
 Provides security
 monitoring

Mr. Nilesh
Vishwasra
Socket Programming
• A socket is one end-point of a two-way
communication link between two programs running
on the network.
• Socket is combination of an IP address and a port
number.
• Socket classes are used to represent the connection
between a client program and a server program.
Socket Programming
• can be connection-oriented or connection-less.

• Socket
Connection
Oriented
• ServerSocket

Connection
•DatagramSocket
less • DatagramPacket
Server-Client Communication
Socket Programming with TCP
• Supports Connection-oriented ,reliable,
bidirectional and stream based
communication
• initial handshaking phase
• The package java.net provides support
for
• sockets programming.
import java.net.*;
• Contains classes and interfaces to
encapsulate the “Socket” Paradigm.
Classes & Interfaces from java.net
package

InetAddress
Socket
URL
URLConnection
ServerSocket
DatagramSocket

DatagramPacket
17
InetAddress class
 Represents IP address

 IP address is represented by 32-bit or 128-bit

 InetAddress class is encapsulate both


numeric IP address (eg .74.125.236.88)
and the domain name (eg.
www.google.com) for the address.

 For example, mostly every internet user


don't know IP address for google.com
13
About InetAddress class
 InetAddress Class has no visible
constructors. to create a InetAddress
object.
 Factory Method is used to create
objects.
 Three factory methods:
 static InetAddress getLocalHost()
 static InetAddress getByName(String
hostName)
 static InetAddress[] getAllByName(String
hostName).

19
 All methods generate : UnknownHostException
Instance Methods
 boolean equals(Object other)
 byte[] getAddress(): Return four element of
IP address.
 String getHostAddress(): Return host
address associated with InetAddress.
 String getHostName(): Return host name.
 boolean isMultiCastAddress()

20
URL
 URL is Uniform Resource Locator.

 It is used to recognize resource on the internet.

 It points to a resource on the World Wide Web

 Network resource could be text, documents,


plain web pages, programs or graphics.

21
URL
 URL string consist of following parts:
 protocol
 Host name or address
 Port number
 File or resource location.

22
http://www.msbte.com:80/index.html
• Exapmle:
http://www.msbte.com:80/index.html

• Protocol: http is the protocol.


• Host name or IP Address: www.msbte.com is the host
name.
• Port Number: It is an optional attribute.
80 is the port number.
If port number is not mentioned in the URL, it returns -1.
• File Name or directory name: index.html is the file name.
URL
 Ex
 http://www.msbte.com/index.html
 URL class has some constructors and it
throws MalformedURLException

 URL(String url)
 URL(String protocol, String hostname, int
port, String path)
 URL(URL obj, String url)

25
Methods of URL
Method Description
String getProtocol() It returns the protocol of the URL.

String getHost() It returns the host name of the URL.

It returns the port number of the URL. If


String getPort() port number is not mentioned in the URL, it
returns -1

String getFile() It returns the file name of the URL.

URLConnection It returns the instance of urlconnection i.E.


openConnection() Associated with this URL.

Returns the string representation of a


String toExternalForm()
specified URL
26
import java.net.*;
public class URLDemo
{
public static void main(String[] args)
{
try
{
URL url=new URL("http://www.msbte.org.in/index.html");
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());

} Output
catch(Exception e) Protocol: http
{ Host Name: msbte.org.in
System.out.println(e); Port Number: -1
} File Name: /index.html
}
URLConnection Class
 URLConnection is an abstract class

 Used for accessing the attributes of remote


resource.

 public URLConnection
openConnection()throws
IOException{ }

 openConnection() of URL class returns the


object of URLConnection class.
28
URLConnection Class methods
 int getContentLength() : Return size of
contents related to resource. If no length
then return -1.
 String getContentType(): Return type of
content of resource.
 long getDate() : Return date and time
of response
 long getLastModified() : return last date
and time modified of response

29
URLConnection Class methods
 long getExpiration(): Return expiration
date
and time in miliseconds.
 InputStream getInputStream() : Used to
get contents of resource.

30
import java.net.*;
import java.util.*;
import java.io.*;
public class UCDemo
{
public static void main(String[] args)
{
try
{
URL url=new URL("http://www.javatpoint.com/java-tutorial");
URLConnection uc=url.openConnection();

System.out.println("length: "+uc.getContentLength());
System.out.println("date of response: "+ new Date(uc.getDate()));
System.out.println("date of last modification: "+new Date(uc.getLastModified()));
System.out.println("content type: "+uc.getContentType());
InputStream in=uc.getInputStream();
int c;
while((c=in.read())!=-1)
{
System.out.print((char)c);
}

}
catch(Exception e)
{
System.out.println(e);
}
}
}
Socket Class
• implements one side of a two-way connection
• Used to create client sockets, is designed to
connect to server socket and initiate protocol
exchanges.
• Socket is implemented at the client side to
send request to the port of the machine
where ServerSocket is listening.
• When Socket object is created, it establishes
the connection b/w client and server.
Socket Class
• Constructors:-
Socket(String hostname, int port)
Socket(InetAdrress ipaddr, int port)

First argument is Hostname or IP address of


Server.
Second argument is TCP Port.
Socket Class Methods
• InetAddress getInetAdress()
• int getPort()
• int getLocalPort()
• InputStream getInputStream()
• OutputStream getOutputStream()
• void close()
ServerSocket Class
• Used to create server sockets
• ServerSocket is implemented at the server side so that it
can listen to the client’s request and respond to them
• Constructors:-
ServerSocket ( int port )
ServerSocket ( int port, int queueLength)
ServerSocket ( int port, int queueLength,
InetAddress localAddr)
• Method:-
Socket accept() : accept() is a blocking call that waits for a
client to initiate communication and returns a normal
Socket, that is used for communication with the client.
steps for creating a simple server program
are:
1) Open the Server Socket:
ServerSocket server = new ServerSocket( PORT );
2) Wait for the Client Request:
Socket sock = server.accept();
3)Create I/O streams for communicating to the client
DataInputStream receive= new DataInputStream(sock.getInputStream());
DataOutputStream send= new DataOutputStream(sock.getOutputStream());

4)Perform communication with client


Receive from client:
String line = receive.readLine();
Send to client:
send.writeBytes(“Hello\n”);
5)Close socket:
client.close();
steps for creating a simple client program
are:

1)Create a Socket Object:


Socket client = new Socket(server, port_id);
2)Create I/O streams for communicating with the server.
receive = new DataInputStream(client.getInputStream());
send = new DataOutputStream(client.getOutputStream());
3)Perform I/O or communication with the server:
Receive data from the server:
String line = receive.readLine();
Send data to the server:
send.writeBytes(“Hello\n”);
4)Close the socket when done:
client.close();
import java.net.*;
import java.io.*;
class TCPClient
{
public static void main(String args[])
{
BufferedReader receive; //DIS
PrintWriter send; //DOS
BufferedReader in;
try
{ Socket client=new Socket("localhost",3000);

receive=new BufferedReader(new
InputStreamReader(client.getInputStream()));
send=new PrintWriter(client.getOutputStream(),true);
in=new BufferedReader(new
InputStreamReader(System.in));
String msgsend="";

while(!msgsend.equals("bye"))
{
msgsend=in.readLine();
send.println(msgsend);

String msgreceive=receive.readLine();
if(msgreceive!=null)
System.out.println("From Server="+msgreceive);

}
client.close();
}
catch(Exception e){}
}
}
import java.net.*;
import java.io.*;
class TCPServer
{
public static void main(String args[])
{
BufferedReader receive;
PrintWriter send;
BufferedReader in;
try
{ ServerSocket server=new ServerSocket(3000);
System.out.println("Server is ready....");
Socket sock=server.accept();

receive=new BufferedReader(new
InputStreamReader(sock.getInputStream()));
send=new PrintWriter(sock.getOutputStream(),true);

in=new BufferedReader(new
InputStreamReader(System.in));
String msgreceive="";
while(true)
{
msgreceive=receive.readLine();
if(msgreceive!=null)
System.out.println("From Client="+msgreceive);
if(msgreceive.equals("bye"))
{
sock.close();
break;
}
String msgsend=in.readLine();
send.println(msgsend);
}
}
catch(Exception e){}
}
}
Socket Programming with

UDP
Connectionless and unreliable service.
• There isn’t an initial handshaking phase.
• Doesn’t have a pipe. No streams are attached to
the sockets.
• transmitted data may be received out of order, or
lost
• Datagrams are bundles of information passed
between machine.
• Datagram communication through Two classes
• DatagramPacket
• DatagramSocket
DatagramPacket
• Data container
• Each packet contains
InetAddress
Port of destination
Data
• Constructor:
• For Receiving data
 DatagramPacket(byte data[],int size)
 DatagramPacket(byte data[],int offset, int size)
• For Sending data
 DatagramPacket(byte data[],int size, InetAddress
ipAddr,int port)
 DatagramPacket(byte data[],int offset, int
size,InetAddress ipAddr, int port)

• Data in packet represented as byte array


Methods of DatagramPacket
• InetAddress getAddress() –destination InetAddress
• byte []getData() -used to retrieve data
• int getLength()
• int getPort()
• void setData(byte[] buf)
• void setAddress(InetAddress a)
• void setPort(int port);
• void setLength(int length)
DatagramSocket Class
• Create UDP socket
– Does not distinguish server / client sockets
• Constructor specifies InetAddress, port
• Set up UDP socket connection
• no guarantee of its content, arrival or arrival time.
• connection-less socket for sending and receiving
datagram packets.
• Constructor
1. DatagramSocket() throws SocketException
binds it to any available port on local machine
2. DatagramSocket(int port) throws
SocketException
binds the datagram socket to the specified port
3. DatagramSocket(int port, InetAddress address)
throws SocketException:
binds it to specified port and inetaddress.

Methods
–void receive( DatagramPacket p)
–void send( DatagramPacket p)
import java.io.*;
import java.net.*;
import java.util.*;
public class UDPClient
{
public static void main(String[] args)throws Exception
{
DatagramSocket client= new DatagramSocket();
InetAddress serverip=InetAddress.getLocalHost();

Scanner sc = new Scanner(System.in);


while (true)
{
String in = sc.nextLine();
byte buf[]=in.getBytes();
DatagramPacket p = new DatagramPacket(buf,buf.length,serverip,1234);
client.send(p);
}
import java.io.*;
import java.net.*;
public class UDPServer
{
public static void main(String[] args) throws Exception
{
DatagramSocket server=new DatagramSocket(1234);
System.out.println("-- Server is Running --");
String msg;
while (true)
{ byte[] buf = new byte[256];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
server.receive(packet);
msg = new String(packet.getData()).trim();
System.out.println( "From Client=" + msg);
}
}}
Whois in Java
• The WhoisClient class implements the client
side of the Internet Whois Protocol defined in
RFC 954.
Whois in Java
import java.io.IOException;
import org.apache.commons.net.whois.*;
public class JavaWhoisClient {

public static void main(String[] args) {


WhoisClient whois;

whois = new WhoisClient();

try {
whois.connect(WhoisClient.DEFAULT_HOST);
System.out.println(whois.query("=google.com"));
whois.disconnect();
} catch (IOException e) {
System.err.println("Error I/O exception: " + e.getMessage());
return;
}
}

You might also like