Networking Basics
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
Department of Computer
AJP Unit-IV Mrs. Chavan P.P. 2
Engineering
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. [Link], into the IP
addresses, e.g. [Link], that networking
equipment needs to deliver information.
• It also stores other information such as the list of mail
exchange servers that accept email for a given domain.
Department of Computer
AJP Unit-IV Mrs. Chavan P.P. 3
Engineering
Proxy Server
• Proxy servers are related to firewalls. If a
firewall prevents hosts on a network from
making direct connections to the outside
world, a proxy server can act as a go-between.
• Thus, a machine that is prevented from
connecting to the external network by a
firewall would make a request for a web page
from the local proxy server instead of
requesting the web page directly from the
remote web server.
Department of Computer
AJP Unit-IV Mrs. Chavan P.P. 4
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
AJP Unit-IV Mrs. Chavan P.P. 5
Engineering
Java Networking Terminology
• IP Address
• Protocol
• Port Number
• MAC Address
• Connection-oriented and connection-less
protocol
• Socket
Department of Computer
AJP Unit-IV Mrs. Chavan P.P. 6
Engineering
IP Address
• IP address is a unique number assigned to a
node of a network e.g. [Link] . It is
composed of octets that range from 0 to
255.
• It is a logical address that can be changed.
Department of Computer
AJP Unit-IV Mrs. Chavan P.P. 7
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
AJP Unit-IV Mrs. Chavan P.P. 8
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
AJP Unit-IV Mrs. Chavan P.P. 9
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
AJP Unit-IV Mrs. Chavan P.P. 10
Engineering
Connection-oriented and
connection-less protocol
• In 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
AJP Unit-IV Mrs. Chavan P.P. 11
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
AJP Unit-IV Mrs. Chavan P.P. 12
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
[Link]
80 1567
Server Client
[Link] [Link]
5488
Client
[Link]
Department of Computer
AJP Unit-IV Mrs. Chavan P.P. 13
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
AJP Unit-IV Mrs. Chavan P.P. 14
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
AJP Unit-IV Mrs. Chavan P.P. 15
Engineering
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.
Department of Computer
AJP Unit-IV Mrs. Chavan P.P. 16
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 [Link].
• Key classes, interfaces, and exceptions in
[Link] package simplifying the complexity
involved in creating client and server
programs are:
Department of Computer
AJP Unit-IV Mrs. Chavan P.P. 17
Engineering
The Classes in [Link] Package
• ContentHandler • ServerSocket
• DatagramPacket • Socket
• DatagramSocket • SocketImpl
• DatagramSocketImpl • URL
• HttpURLConnection • URLConnection
• InetAddress • URLEncoder
• MulticastSocket • URLStreamHandler
Department of Computer
AJP Unit-IV Mrs. Chavan P.P. 18
Engineering
The Interfaces in [Link] package
• ContentHandlerFactory
• FileNameMap
• SocketImplFactory
• URLStreamHandlerFactory
Department of Computer
AJP Unit-IV Mrs. Chavan P.P. 19
Engineering
Exceptions in [Link] package
• BindException
• ConnectException
• MalformedURLException
• NoRouteToHostException
• ProtocolException
• SocketException
• UnknownHostException
• UnknownServiceException
Department of Computer
AJP Unit-IV Mrs. Chavan P.P. 20
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
AJP Unit-IV Mrs. Chavan P.P. 21
Engineering
InetAddress class
• static methods you can use to create new
InetAddress objects.
– getByName(String host)
– getAllByName(String host)
– getLocalHost()
InetAddress x = [Link](
“[Link]”);
Throws UnknownHostException
Department of Computer
Engineering
AJP Unit-IV Mrs. Chavan P.P. 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
AJP Unit-IV Mrs. Chavan P.P. 23
Engineering
Factory Methods Example
class InetAddressTest
{
public static void main(String args[]) throws UnknownHostException
{
InetAddress Address = [Link]();
[Link](Address);
Address = [Link]("[Link]");
[Link](Address);
InetAddress SW[] = [Link]("[Link]");
for (int i=0; i<[Link]; i++)
[Link](SW[i]);
}
}
Department of Computer
AJP Unit-IV Mrs. Chavan P.P. 24
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
AJP Unit-IV Mrs. Chavan P.P. 25
Engineering
Instance Methods
class InetAddressTest1
public static void main(String args[])throws UnknownHostException
InetAddress Address = [Link]("[Link]");
[Link]([Link]());
[Link]([Link]());
if([Link]())
[Link]("It is multicast address");
}Department of Computer
AJP Unit-IV Mrs. Chavan P.P. 26
Engineering
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
AJP Unit-IV Mrs. Chavan P.P. 27
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 [Link] class
• Sockets (client)
– Used to send and receive data
– Can be thought of as a pair of input and output
streams
– Implemented by [Link] class
Department of Computer
AJP Unit-IV Mrs. Chavan P.P. 28
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
AJP Unit-IV Mrs. Chavan P.P. 29
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
Address
Department of Computer to which this socket binds.
AJP Unit-IV Mrs. Chavan P.P. 30
Engineering
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
AJP Unit-IV Mrs. Chavan P.P. 31
Engineering
Server socket
• Methods
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
AJP Unit-IV Mrs. Chavan P.P. 32
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.
public void close()
Department throws IOException
of Computer Closes the socket connection.
AJP Unit-IV Mrs. Chavan P.P. 33
Engineering
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 = [Link]();
3. Create I/O streams for communicating to the client
DataInputStream dis = new DataInputStream([Link]());
DataOutputStream dos = new DataOutputStream([Link]());
4. Perform communication with client Receive from client:
String line = [Link]();
Send to client: [Link](“Hello\n”);
5. Close socket:
[Link]();
Department of Computer
AJP Unit-IV Mrs. Chavan P.P. 34
Engineering
File: [Link]
import [Link].*;
import [Link].*;
public class MyServer
{
public static void main(String[] args)
{
try
{
ServerSocket ss=new ServerSocket(1356);
Socket s=[Link]();//establishes connection
DataInputStream dis=new DataInputStream([Link]());
String str=(String)[Link]();
[Link]("message= "+str);
[Link]();
}
catch(Exception e)
{
[Link](e);
}
}
Department of Computer
AJP Unit-IV Mrs. Chavan P.P. 35
}
Engineering
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([Link]());
dos = new DataOutputStream([Link]());
3. Perform I/O or communication with the server:
Receive data from the server:
String line = [Link]();
Send data to the server:
[Link](“Hello\n”);
4. Close the socket when done:
[Link]();
Department of Computer
AJP Unit-IV Mrs. Chavan P.P. 36
Engineering
[Link]
import [Link].*;
import [Link].*;
public class MyClient
{
public static void main(String[] args)
{
try
{
Socket s=new Socket("localhost",1356);
DataOutputStream dout=new DataOutputStream([Link]());
[Link]("Hello Server");
[Link]();
[Link]();
[Link]();
}
catch(Exception e)
{
[Link](e);
}
} of Computer
Department
AJP Unit-IV Mrs. Chavan P.P. 37
}
Engineering
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
AJP Unit-IV Mrs. Chavan P.P. 38
Engineering
URL Class
Java URL Class present in [Link] package,
deals with URL (Uniform Resource Locator)
which uniquely identify or locate resources on
internet.
Department of Computer
AJP Unit-IV Mrs. Chavan P.P. 39
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 specified
Department context.
of Computer
AJP Unit-IV Mrs. Chavan P.P. 40
Engineering
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
AJP Unit-IV Mrs. Chavan P.P. 41
Engineering
import [Link].*;
class Test
{
public static void main(String[] arg) throws MalFormedURLException
{
URL hp = New URL("[Link]
[Link]([Link][]);
[Link]([Link][]);
}
}
Department of Computer
AJP Unit-IV Mrs. Chavan P.P. 42
Engineering
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.
Department of Computer
AJP Unit-IV Mrs. Chavan P.P. 43
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
AJP Unit-IV Mrs. Chavan P.P. 44
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
AJP Unit-IV Mrs. Chavan P.P. 45
Engineering
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
AJP Unit-IV Mrs. Chavan P.P. 46
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
AJP Unit-IV Mrs. Chavan P.P. 47
Engineering
• Java supports datagram communication through
the following classes:
– DatagramPacket
– DatagramSocket
The class DatagramPacket contains several constructors
that can be used for creating packet object. One of
them is:
DatagramPacket(byte[] buf, int length, InetAddress address, int port);
Department of Computer
AJP Unit-IV Mrs. Chavan P.P. 48
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
AJP Unit-IV Mrs. Chavan P.P. 49
Engineering
// Client side
import [Link].*;
import [Link].*;
import [Link].*;
public class udpClient
{
public static void main(String args[]) throws IOException
{
Scanner sc = new Scanner([Link]);
DatagramSocket ds = new DatagramSocket();
InetAddress ip = [Link]();
byte buf[] = null;
// loop while user not enters "bye"
while (true)
{
String inp = [Link]();
buf = [Link]();
DatagramPacket DpSend = new DatagramPacket(buf, [Link], ip, 1234);
[Link](DpSend);
if ([Link]("bye"))
break;
}
}
Department of Computer
AJP Unit-IV Mrs. Chavan P.P. 50
}Engineering
// Server side
import [Link].*;
import [Link].*;
public class udpServer
{
public static void main(String[] args) throws IOException
{
DatagramSocket ds = new DatagramSocket(1234);
byte[] receive = new byte[20];
DatagramPacket DpReceive = null;
while (true)
{
DpReceive = new DatagramPacket(receive, [Link]);
[Link](DpReceive);
String msg=new String(receive);
[Link]("Client:-" + msg);
}
}
}
Department of Computer
AJP Unit-IV Mrs. Chavan P.P. 51
Engineering
Example of Java Socket Programming
(Read-Write both side)
Department of Computer
AJP Unit-IV Mrs. Chavan P.P. 52
Engineering
[Link]
import [Link].*;
import [Link].*;
class MyServer{
public static void main(String args[])throws Exception{
ServerSocket ss=new ServerSocket(3333);
Socket s=[Link]();
DataInputStream din=new DataInputStream([Link]());
DataOutputStream dout=new DataOutputStream([Link]());
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
String str="",str2="";
while(){
str=[Link]();
[Link]("client says: "+str);
str2=[Link]();
[Link](str2);
[Link]();
}
[Link]();
[Link]();
[Link]();
}} Department of Computer AJP Unit-IV Mrs. Chavan P.P. 53
Engineering
[Link]
import [Link].*;
import [Link].*;
class MyClient{
public static void main(String args[])throws Exception{
Socket s=new Socket("localhost",3333);
DataInputStream din=new DataInputStream([Link]());
DataOutputStream dout=new DataOutputStream([Link]());
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
String str="",str2="";
while(){
str=[Link]();
[Link](str);
[Link]();
str2=[Link]();
[Link]("Server says: "+str2);
}
[Link]();
[Link]();
}}
Department of Computer
AJP Unit-IV Mrs. Chavan P.P. 54
Engineering