0% found this document useful (0 votes)
112 views59 pages

Networking Basics

This document provides an overview of networking basics and Java networking concepts. It discusses client-server architecture, DNS, proxy servers, IP addresses, protocols, ports, MAC addresses, connection-oriented vs connection-less protocols, sockets, reserved ports, internet addressing with InetAddress class, Java networking classes and interfaces, exceptions, and methods of InetAddress class like getByName(), getAllByName(), getLocalHost(), equals(), getAddress(), getHostAddress(), getHostName(), isMulticastAddress(). The document is presented by Prof. Mane D.S., HOD of Computer Engineering department at S.P.M. Polytechnic, Kumathe.

Uploaded by

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

Networking Basics

This document provides an overview of networking basics and Java networking concepts. It discusses client-server architecture, DNS, proxy servers, IP addresses, protocols, ports, MAC addresses, connection-oriented vs connection-less protocols, sockets, reserved ports, internet addressing with InetAddress class, Java networking classes and interfaces, exceptions, and methods of InetAddress class like getByName(), getAllByName(), getLocalHost(), equals(), getAddress(), getHostAddress(), getHostName(), isMulticastAddress(). The document is presented by Prof. Mane D.S., HOD of Computer Engineering department at S.P.M. Polytechnic, Kumathe.

Uploaded by

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

Advanced Java Programming

Unit-4
Networking Basics
By
Prof. Mane D.S.
H.O.D. Computer Engineering Department
S.P.M. Polytechnic, Kumathe
Client-Server and network
• A computer running a program that makes a request for
services is called client machine.
• A computer running a program that offers requested
services from one or more clients is called server machine.
• The media for communication can be wired or wireless
network.

Client

Network

Client machine Server machine


DNS - Domain name system
• The Domain Name system (DNS) associates various sorts
of information with so-called domain names.
• Most importantly, it serves as the "phone book" for the
Internet by translating human-readable
computer
hostnames, e.g. www.example.com, into the
addresses, IP
equipment needs
e.g. to208.77.188.166,
deliver information.that
• It also storesnetworking
other information such as the list of
mail exchange servers that accept email for a given
domain.
Proxy Server
• Proxy servers are related to firewalls. If a
firewall prevents on a from
hosts making connections network
to the outside
direct a proxy server can act as a go-between.
world,
• Thus, a that is prevented from
machine
connecting to the external network
firewall would make a request for a web page
from the local proxy server by instead of
requesting the web page directly the
from remote web server. a
Department of Computer
Engineering
• The proxy server would then request the page
from the web server and forward the
response back to the original requester.
• One of the security advantages of using a
proxy server is that external hosts only find
out about the proxy server. They do not learn
the names and IP addresses of the internal
machines, making it more difficult to hack into
internal systems.

Department of Computer
Engineering
Java Networking Terminology
• IP Address
• Protocol
• Port Number
• MAC Address
• Connection-oriented and connection-less
protocol
• Socket

Department of Computer
Engineering
IP Address
• IP address is a unique number assigned to a
node of a network e.g. 192.168.0.1 . It is
composed of octets that range from 0 to
255.
• It is a logical address that can be changed.

Department of Computer
Engineering
Protocol
• A protocol is a set of rules basically that is
followed for communication. For example:
• TCP
• UDP
• FTP
• Telnet
• SMTP
• POP etc.
Department of Computer
Engineering
Ports
• The port number is used to uniquely identify
different applications.
• It acts as a communication endpoint between
applications.
• The port number is associated with the IP address
for communication between two applications.

Department of Computer
Engineering
MAC Address
• MAC (Media Access Control) Address is a
unique identifier of NIC (Network Interface
Controller). A network node can have
multiple NIC but each with unique MAC.

Department of Computer
Engineering
Connection-oriented and
connection-less
• In protocol
connection-oriented
protocol, acknowledgement is sent by the
receiver. So it is reliable but slow. The
example of connection-oriented protocol is
TCP.
• But, in connection-less protocol,
acknowledgement is not sent by the
receiver. So it is not reliable but fast. The
example of connection-less protocol is UDP.
Department of Computer
Engineering
Socket

sockets (end points)

logical connection

• A socket is an endpoint for communication between


two machines.
• The combination of an IP address and a port number.
Department of Computer
Engineering
• The tuple <IP address, Port >; creates a Socket
• Connection is a combination of {Source<IP address, Port > ,
Destination <IP address, Port >} i.e. source socket – destination
socket pair uniquely identifies a connection.
• Example

1343 Client
192.168.0.2

80 1567
Server Client
192.168.0.3
192.168.0.1

5488
Client
192.168.0.4

Department of Computer
Engineering
Reserved Ports
• 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.

Department of Computer
Engineering
• Reserved port numbers.

Service Port no.


echo 7
daytime 13
ftp 21
telnet 23
smtp 25
finger 79
http 80
pop3 110
Department of Computer
Engineering
Advanced Java Programming
Unit-4
Networking Basics
By
Prof. Mane D.S.
H.O.D. Computer Engineering Department
S.P.M. Polytechnic, Kumathe
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 methods
simple
to convert between domain names,
numbered
and addresses.

Department of Computer
Engineering
java networking classes and
interfaces
• To enable the rapid development of network
applications , Java provides a set of classes,
defined in a package called java.net.
• Key classes, interfaces, and exceptions in
java.net package simplifying the complexity
involved in creating client and server
programs are:

Department of Computer
Engineering
The Classes in java.net Package
• ContentHandler • ServerSocket
• DatagramPacket • Socket
• DatagramSocket • SocketImpl
• DatagramSocketImpl • URL
• HttpURLConnection • URLConnection
• InetAddress • URLEncoder
• MulticastSocket • URLStreamHandler

Department of Computer
Engineering
The Interfaces in java.net package
• ContentHandlerFactory
• FileNameMap
• SocketImplFactory
• URLStreamHandlerFactory

Department of Computer
Engineering
Exceptions in java.net package
• BindException
• ConnectException
• MalformedURLException
• NoRouteToHostException
• ProtocolException
• SocketException
• UnknownHostException
• UnknownServiceException
Department of Computer
Engineering
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.
• The InetAddress class hides the number
inside.

Department of Computer
Engineering
InetAddress class
• 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
Department of Computer
Engineering
22
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.
Department of Computer
Engineering
Factory Methods Example
class InetAddressTest
{
public static void main(String args[]) throws UnknownHostException
{
InetAddress Address = InetAddress.getLocalHost();
System.out.println(Address);
Address = InetAddress.getByName("www.msbte.com");
System.out.println(Address);
InetAddress SW[] = InetAddress.getAllByName("www.gmail.com");
for (int i=0; i<SW.length; i++)
System.out.println(SW[i]);
}
}
Department of Computer
Engineering
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.
Department of Computer
Engineering
Instance Methods
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");

}Department of Computer AJP Unit-IV Mrs. Chavan P.P. 26


Engineering
Advanced Java Programming
Unit-4
Networking Basics
By
Prof. Mane D.S.
H.O.D. Computer Engineering Department
S.P.M. Polytechnic, Kumathe
Transmission Control Protocol
• A connection-based protocol that provides a reliable flow
of data between two computers.
• Provides a point-to-point channel for applications that
require reliable communications.
– The Hypertext Transfer Protocol (HTTP), File Transfer Protocol
(FTP), and Telnet are all examples of applications that require a
reliable communication channel
• Guarantees that data sent from one end of the
connection actually gets to the other end and in the
same order it was sent. Otherwise, an error is reported.

Department of Computer
Engineering
TCP/IP SOCKET PROGRAMMING
• The two key classes used in creation of server
and client programs are:
• ServerSocket
– Wait for requests to come in over the network
– Implemented by java.net.ServerSocket class

• Sockets (client)
– Used to send and receive data
– Can be thought of as a pair of input and output
streams
– Implemented by java.net.Socket class
Department of Computer
Engineering
Server vs. Client Socket
 Server socket: waiting for connection requests
 Client socket: transmission of data

server socket

connection request

client socket

Department of Computer
Engineering
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
DepartmeAnt dfo dC
ormepstusre to which th i s s o c ket bind s .
AJ P U ni I-t V M r s.
Engineering
Chavan P.P.
Client socket
The constructors used to server 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

Department of Computer
Engineering
Server
• Methods
socket
Some method defined in the Server Socket are:

Methods Description

public Socket accept() throws IOException Waits for a connection request and
returns a Socket

public void setSoTimeout(int timeout) Sets the time-out value for how long the
server socket waits for a client during the
accept().
)
public int getLocalPort() Returns the port number on which this
socket is listening

Department of Computer
Engineering
Methods used by both Server and Client Sockets
Methods Description

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


socket is bound.
public int getLocalPort() Returns the port the socket is bound to on
the local machine.

public InetAddress getInetAddress() Returns IP address to which socket are


connected.

public SocketAddress getLocalAddress() Returns local address to which socket are


connected.
public SocketAddress getRemoteSocketAddress() Returns the address of the remote socket.

public InputStream getInputStream() throws Returns an InputStream for receiving data.


IOException

public OutputStream getOutputStream() throws Returns an OutputStream to


IOException send data.

pubDliecpavtromeidntcofloCsomep(u)et trhrows IOException Closes the socket connection.


Engineering
AJP Unit-IV s. Chavan P.P. 33
Mr
A simple Server Program in Java
• The 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 client = server.accept();
3. Create I/O streams for communicating to the client
DataInputStream dis = new DataInputStream(client.getInputStream());
DataOutputStream dos = new DataOutputStream(client.getOutputStream());
4. Perform communication with client Receive from client:
String line = is.readLine();
Send to client: os.writeBytes(“Hello\n”);
5. Close socket:
client.close();
Department of Computer
Engineering
File: MyServer.java
import java.io.*;
import java.net.*;
public class MyServer
{
public static void
main(String[] args)
{
try
{
ServerSocket ss=new ServerSocket(1356);
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);
Department of Computer
}
}Engineering . 35
A simple Client Program in Java
• The 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.
dis = new DataInputStream(client.getInputStream());
dos = new DataOutputStream(client.getOutputStream());
3.Perform I/O or communication with the server:
Receive data from the server:
String line = dis.readLine();
Send data to the server:
dos.writeBytes(“Hello\n”);
4. Close the socket when done:
client.close();
Department of Computer
. 36
Engineering
MyClient.java
import java.io.*;
import java.net.*;
public class MyClient
{
public static void
main(String[]
args)
{
try
{
Socket
s=new
Socket("loc
alhost",135
6);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
Depar}tment of Computer 37
}
TCP Client: whois
• WHOIS is a TCP-based transaction-oriented
query/response protocol that is widely used to
provide information services to Internet users.
• It is used to query databases that hold information
about internet resources such as domain names and
IP address allocations.
• A WHOIS server listens on TCP port 43 for requests
from WHOIS clients. The WHOIS client makes a text
request to the WHOIS server, then the WHOIS server
replies with text content.

Department of Computer
Engineering
Advanced Java Programming
Unit-4
Networking Basics
By
Prof. Mane D.S.
H.O.D. Computer Engineering Department
S.P.M. Polytechnic, Kumathe
URL Class
Java URL Class present in java.net package,
deals with URL (Uniform Resource Locator)
which uniquely identify or locate resources on
internet.

Department of Computer
Engineering
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,
port number, 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
Department specified
c o n t e x t.
Engineering
of Co m p uet r
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.
Department of Computer
Engineering
import java.net.*;
Import java.io.*;
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.getPort());
System.out.println(hp.getFile());
System.out.println(hp.getHost());
}
}

Department of Computer
Engineering
URL Connection Class
• The abstract class is the
URLConnection
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.

Department of Computer
Engineering
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.

Department of Computer
Engineering
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.

Department of Computer
Engineering
Advanced Java Programming
Unit-4
Networking Basics
By
Prof. Mane D.S.
H.O.D. Computer Engineering Department
S.P.M. Polytechnic, Kumathe
UDP User Datagram Protocol
• A protocol that sends independent packets of data,
called datagrams, from one computer to another with
no guarantees about arrival. UDP is not connection-
based like TCP and is not reliable:
– Sender does not wait for acknowledgements
– Arrival order is not guaranteed
– Arrival is not guaranteed
• Used when speed is essential, even in cost of reliability
– e.g. streaming media, games, Internet telephony, etc.

Department of Computer
Engineering
UDP SOCKET PROGRAMMING
• algorithm for UDP client
– Find the IP address and port number of server
– Create a UDP socket
– Send/ receive data with server using the socket
– Close the connection

• algorithm for UDP server


– Find the IP address and port number of server
– Create a UDP server socket
– Bind the server socket to server IP and Port number (this is the
port to which clients will send)
– Send/ receive data with client using the client socket
– Close the connection with client

Department of Computer
Engineering
Datagram Socket class
 The Java DatagramSocket class is used to send
and receive the datagrams it is connection less
socket. That is there is no guarantee of message
delivery.
 It has following constructors
1. DatagramSocket()
2. DatagramSocket(int port)
3. DatagramSocket(int port, InetAddress address)

Department of Computer
Engineering
Datagram Packet class
 The Java DatagramPacket is class that can be
used to send the packets. If you send multiple
packet, it may arrive in any order. Additionally,
packet delivery is not guaranteed.
 It has following constructors
1. DatagramPacket(byte[] barr, int length)
2. DatagramPacket(byte[] barr, int length,
InetAddress address, int port)

Department of Computer
Engineering
The key methods of DatagramPacket class
Method Description
byte[] getData() Returns the data buffer
int getLength() Returns the length of the data to be sent or
the length of the data received.

void setData(byte[] buf) Sets the data buffer for this packet.
void setLength(int length) Sets the length for this packet

The key methods of DatagramSocket class


Method Description
void send(DatagramPacket p) Sends a datagram packet from this socket.
void receive(DatagramPacket p) Receives a datagram packet from this
socket.

Department of Computer
Engineering
import java.net.*;
public class DgramRec
{
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();
}
}
Department of Computer
Engineering
import java.net.*;
public class DGramSender
{
public static void main(String[] args) throws Exception
{
DatagramSocket ds = new DatagramSocket();
String str = "Java is Easy!!!!!";
InetAddress ip = InetAddress.getByName("127.0.0.1");
DatagramPacket dp = new DatagramPacket(str.getBytes(),
str.length(),ip, 3000);
ds.send(dp);
ds.close();
}
}

50
Example of Java Socket Programming
(Read-Write both side)

Department of Computer
Engineering
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());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

String str="",str2=""; while(!


str.equals("stop")){ str=din.readUTF();
System.out.println("client says: "+str);
str2=br.readLine();
dout.writeUTF(str2);
dout.flush();
}
din.close();
s.close();
ss.close();

}} Department of Computer
Engineering
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();
dout.writeUTF(str);
dout.flush();
str2=din.readUTF();
System.out.println("Serve
r says: "+str2);
}
dout.close();
s.close();
D}ep}artment of 54
Computer Engineering

You might also like