0% found this document useful (0 votes)
0 views

Networking in Java

jaava networking
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Networking in Java

jaava networking
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

NETWORKING IN

JAVA
Ø Basics Socket overview, client/server, reserved sockets,
proxy servers, internet addressing.
Ø Java & the Net: The networking classes & interfaces
Ø InetAddress class: Factory methods, instance method
Ø TCP/IP Client Sockets,
Ø TCP/IP Server Sockets
Ø URL Format
Ø URLConnection class
Ø Data grams Data gram packets, Data gram server & Client
SOCKET OVERVIEW
 A network socket is a lot like an electrical socket.
 The same idea applies to network sockets,except we talk
about TCP/IP packets and IP addresses .
 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) is a higher-level
protocol that manages to robustly string together these
packets, sorting and re-transmitting them as necessary
to reliably transmit our data.
 A third protocol, User DatagramProtocol (UDP), sits
next to TCP and can be used directly to support fast,
connectionless, unreliable transport of packets.
CLIENT/SERVER
 A server is anything that has some resource that can be
shared.
 There are compute servers, which provide computing
power; print servers, which manage a collection of
printers; disk servers, which provide networked disk
space; and web servers, which store web pages.
 A client is simply any other entity that wants to gain
access to a particular server. The interaction between
client and server is just like the interaction between a
lamp and an electrical socket.
 The server is a permanently available resource, while the
client is free to unplug after it is has been served.
 To manage multiple client connections, a server process
must be multithreaded or have some other means of
multiplexing the simultaneous I/O.
RESERVED SOCKETS
 Once connected, a higher-level protocol ensues, which
is dependent on which port we are using.
 TCP/IP reserves the lower 1,024 ports for specific
protocols. Many of these will seem familiar to us if we
have spent any time surfing the Internet. Port
number 21 is for FTP, 23 is for Telnet, 25 is for e-mail,
79 is for finger, 80 is for HTTP, 119 is for net-news
and the list goes on.
PROXY SERVERS

 A proxy server speaks the client side of a protocol to


another server.
 This is often required when clients have certain
restrictions on which servers they can connect to.
 Thus, a client would connect to a proxy server, which did
not have such restrictions, and the proxy server would
in turn communicate for the client.
 A proxy server has the additional ability to filter certain
requests or cache the results of those requests for future
use.
 A caching proxy HTTP server can help reduce the
bandwidth demands on a local network’s connection to
the Internet.
INTERNET ADDRESSING
 An Internet address is a number that uniquely identifies
each computer on the Net.
 Originally, all Internet addresses consisted of 32-bit
values. This address type was specified by IPv4
(Internet Protocol, version 4). However, a new
addressing scheme,called IPv6 (Internet Protocol,
version 6) has come into play.
 IPv6 uses a 128- bit value to represent an address.
Although there are several reasons for and advantages
to IPv6, the main one is that it supports a much larger
address space than does IPv4. Fortunately, IPv6 is
downwardly compatible with IPv4.
 Currently, IPv4 is by far the most widely used scheme,
but this situation is likely to change over time.
 There are 32 bits in an IPv4 IP address, and we often refer
to them as a sequence of four numbers between 0 and 255
separated by dots (.).
 This makes them easier to remember; because they are
not randomly assigned they are hierarchically assigned.
 The first few bits define which class of network, lettered A,
B, C, D, or E, the address represents.
 Most Internet users are on a class C network, since there
are over two million networks in class C.
 The first byte of a class C network is between 192 and 224,
with the last byte actually identifying an individual
computer among the 256 allowed on a single class C
network.
 This scheme allows for half a billion devices to live on class
C network.
DOMAIN NAMING SERVICE (DNS)
The Internet wouldn’t be a very friendly place to
navigate if everyone had to refer to their addresses as
numbers. For example, it is difficult to imagine seeing
http://192.9.9.1/ at the bottom of an advertisement.
Thankfully, a clearing house exists for a parallel
hierarchy of names to go with all these numbers. It is
called the Domain Naming Service (DNS).
 Just as the four numbers of an IP address describe a
network hierarchy from left to right, the name of an
Internet address, called its domain name, describes a
machine’s location in a name space, from right to left.
INETADDRESS
Whether we are making a phone call, sending
mail, or establishing a connection across the
Internet, addresses are fundamental.
 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.
As of Java 2, version 1.4, InetAddress can handle
both IPv4 and IPv6 addresses.
FACTORY METHODS
 The InetAddress class has no visible constructors.
 To create an InetAddress object, we have to use one of the
available factory methods.
 Factory methods are merely a convention whereby static
methods in a class return an instance of that class. This
is done in lieu of overloading a constructor with various
parameter lists when having unique method names
makes the results much clearer.
 Three commonly used InetAddress factory methods are
shown here.
static InetAddress getLocalHost( ) throws
UnknownHostException
static InetAddress getByName(String hostName) throws
UnknownHostException
static InetAddress[ ] getAllByName(String hostName)
throws UnknownHostException
 import java.net.*;
 class InetAddressTest
 {
 public static void main(String args[])
 throws UnknownHostException
 {
 InetAddress Address = InetAddress.getLocalHost();
 System.out.println(Address);
 Address = InetAddress.getByName("google.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]); }}

Output:-
itdept-server/192.168.1.75
google.com/209.85.171.100
www.yahoo.com/87.248.113.14
INSTANCE METHODS
 The InetAddress class also has several other methods, which
can be used on the objects returned by the methods
 boolean equals(Object other):-It returns true if this object has
the same Internet address as other.
 byte[ ] getAddress( ):-It returns a byte array that represents
the object’s Internet address in network byte order.
 String getHostAddress( ):-It returns a string that represents
the host address associated with the InetAddress object.
 String getHostName( ):-It returns a string that represents the
host name associated with theInetAddress object.
 boolean isMulticastAddress( ):-It returns true if this Internet
address is a multicast address. Otherwise, it returns false.
 String toString( ):-It returns a string that lists the host name
and the IP address for convenience.
TCP/IP CLIENT SOCKETS
TCP/IP sockets are used to implement,reliable,
bidirectional, persistent, point-to-point, and 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.
 Applets may only establish socket connections back to
the host from which the applet was downloaded. This
restriction exists because it would be dangerous for
applets loaded through a firewall to have access to any
arbitrary machine.
 There are two kinds of TCP sockets in Java. One is for
servers, and the other is for clients. The ServerSocket
class is designed to be a listener, which waits for clients
to connect before doing anything.
 The Socket class is designed to connect to server sockets
and initiate protocol exchanges.
 The creation of a Socket object implicitly establishes a
connection between the client and server.
Ø Socket(String hostName, int port) throws
UnknownHostException,IOException :- Creates a socket
connecting the local host to the named host and port; can
throw an UnknownHostException or an IOException.
Ø Socket(InetAddress ipAddress, int port)throws
UnknownHostException,IOException :-Creates a socket
using a preexisting InetAddress object and a port; can
throw an IOException
Ø InetAddress getInetAddress( ) :-It returns the
InetAddress associated with the Socket object.
Ø int getPort( ):-It returns the remote port to which this
Socket object is connected.
Ø int getLocalPort( ):-It returns the local port to which this
Socket object is connected.
Ø InputStream getInputStream( ):-This returns the
InputStream associated with the invoking socket.
Ø OutputStream getOutputStream( ):-This returns the
OutputStream associated with the invoking socket.
 Find out which of the first 1,024 ports seem to be hosting TCP servers on a
specified host
import java.net.*;
import java.io.*;
public class LowPortScanner{
public static void main(String[] args){
String host = "localhost";
for (int i = 1; i < 1024; i++){
try {
Socket s = new Socket(host, i);
system.out.println("There is a server on port " + i+ " of " + host);}
catch (UnknownHostException ex){
System.err.println(ex);
Break;
}catch
(IOException ex){}}}}
Output:-
java LowPortScanner
There is a server on port 21 of localhost
There is a server on port 80 of localhost
There is a server on port 110 of localhost
There is a server on port 135 of localhost
There is a server on port 443 of localhost
A DAYTIME PROTOCOL CLIENT
import java.net.*; import java.io.*;
public class DaytimeClient{
public static void main(String[] args){
String hostname;
try{
Socket theSocket = new Socket(“localhost”, 13);
InputStream timeStream = theSocket.getInputStream( );
StringBuffer time = new StringBuffer( );
int c;
while ((c = timeStream.read( )) != -1) time.append((char) c);
String timeString = time.toString( ).trim( );
System.out.println("It is " + timeString + " at “+ hostname);} // end try
catch (UnknownHostException ex){
System.err.println(ex);}
catch (IOException ex){
System.err.println(ex);}
} // end main
} // end DaytimeClient

 java DaytimeClient
 It is 52956 03-11-13 04:45:28 00 0 0 706.3 UTC(NIST) * at
 time.nist.gov
WHOIS
 The very simple example that follows opens a
connection to a whois port on the InterNIC server,
sends the command-line argument down the
socket, and then prints the data that is returned.
 InterNIC will try to lookup the argument as a
registered Internet domain name, then send back
the IP address and contact information for that
site
import java.net.*;
import java.io.*;
class Whois {
public static void main(String args[]) throws Exception {
int c;
Socket s = new Socket("internic.net", 43);
InputStream in = s.getInputStream();
OutputStream out = s.getOutputStream();
String str=(args.length==0? "osborne.com":args[0])+"\n";
byte buf[] = str.getBytes();
out.write(buf);
while ((c = in.read()) != -1)
System.out.print((char) c);
s.close();}}
 Whois Server Version 1.3
 Domain names in the .com, .net, and .org domains can now be
 registered with many different competing registrars. Go to
 http://www.internic.net for detailed information.
 Domain Name: OSBORNE.COM
 Registrar: NETWORK SOLUTIONS, INC.
 Whois Server: whois.networksolutions.com
 Referral URL: http://www.networksolutions.com
 Name Server: NS1.EPPG.COM
 Name Server: NS2.EPPG.COM
 Updated Date: 16-jan-2002
 >> Last update of whois database: Thu, 25 Apr 2002 05:05:52
EDT <<
 The Registry database contains
ONLY .COM, .NET, .ORG, .EDU domains
 and Registrars.
TCP/IP SERVER SOCKETS
 Java has a different socket class that must be used for
creating server applications.
 The ServerSocket class is used to create servers that listen
for either local or remote client programs to connect to
them on published ports.
 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 .
 The ServerSocket class contains everything needed to
write servers in Java.
 It has constructors that create new ServerSocket objects,
methods that listen for connections on a specified port,
methods that configure the various
 server socket options, and the usual miscellaneous
methods such as toString().
IN JAVA, THE BASIC LIFE CYCLE OF A SERVER PROGRAM IS:
 A new ServerSocket is created on a particular port using a
ServerSocket()
 The ServerSocket listens for incoming connection attempts
on that port using its accept( ) method. accept( ) blocks until
a client attempts to make a connection, at which point
accept( ) returns a Socket object connecting the client and the
server.
 Depending on the type of server, either the Socket's
getInputStream() method, getOutputStream( ) method, or
both are called to get input and output streams that
communicate with the client.
 The server and the client interact according to an agreed-
upon protocol until it is time to close the connection.
 The server, the client, or both close the connection.
 The server returns to step 2 and waits for the next
connection.
 ServerSocket(int port) throws BindException, IOException:-
It creates server socket on the specified port with a queue
length of 50.
 ServerSocket(int port, int maxQueue) throws BindException,
IOException:-This creates a server socket on the specified
port with a maximum queue length of maxQueue.
 ServerSocket(int port, int maxQueue, InetAddress
localAddress) throws IOException :-It creates a server socket
on the specified port with a maximum queue length of
maxQueue.
import java.net.*;
import java.io.*;
public class LocalPortScanner{
public static void main(String[] args){
for (int port = 1; port <= 65535; port++){
try{
ServerSocket server = new ServerSocket(port);}
catch (IOException ex){
System.out.println("There is a server on port " + port
+ ".");} // end catch
}}}
Accepting and Closing Connections
Accept() & Close()
URL & FORMAT
 The Uniform Resource Locator (URL) does exactly that.
 The URL provides a reasonably intelligible form to
uniquely identify or address information on the
Internet.
 URLs are ubiquitous; every browser uses them to
identify information on the Web.
 Within Java’s network class library, the URL class
provides a simple, concise API to access information
across the Internet using URLs.
 A URL specification is based on four components.

 The first is the protocol to use, separated from the rest


of the locator by a colon (:). Common protocols are http,
ftp, gopher, and file, although these days almost
everything is being done via HTTP
 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 (:).
 The 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; thus:80 is
redundant.)
 The fourth part is the actual file path.

 URL(String urlSpecifier)

 URL(String protName, String hostName, int port,


String path)
 URL(String protName, String hostName, String path)
import java.net.*;
class URLDemo
{
public static void main(String args[])
throws MalformedURLException{
URL hp = new URL("http://content-
ind.cricinfo.com/ci/content/current/story/news.html");
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());}
}
Output
Protocol: http
Port: -1
Host: content-ind.cricinfo.com
File: /ci/content/current/story/news.html
Ext:http://content-
ind.cricinfo.com/ci/content/current/story/news.html
URLCONNECTION
 URLConnection is an abstract class that represents an
active connection to a resource specified by a URL.
 Construct a URL object.

 Invoke the URL object's openConnection( ) method to


retrieve a URLConnection object for that URL.
 Configure the URLConnection.

 Read the header fields.

 Get an input stream and read data.

 Get an output stream and write data.

 Close the connection


import java.net.*;
class URLDemo
{
public static void main(String args[])
throws MalformedURLException
{
URL hp = new URL("http://content-
ind.cricinfo.com/ci/content/current/story/news.html");
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());
}
}
Output
Protocol: http
Port: -1
Host: content-ind.cricinfo.com
File: /ci/content/current/story/news.html
Ext:http://content-
ind.cricinfo.com/ci/content/current/story/news.html
DATAGRAMS
 Datagrams provide an alternative.
 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 tocatch 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.
 Java implements datagrams on top of the UDP protocol by
using two classes: The DatagramPacket object is the data
container, while the DatagramSocket is the mechanism
used to send or receive theDatagramPackets.
DATAGRAMPACKET
 DatagramPacket uses different constructors depending on
whether the packet will be used to send data or to receive
data. This is a little unusual.
 All constructors take as arguments a byte array that holds
the datagram's data and the number of bytes in that array
to use for the datagram's data.
 When we want to receive a datagram, these are the only
arguments we provide; in addition, the array should be
empty.
 When the socket receives a datagram from the network, it
stores the datagram's data in the DatagramPacket object's
buffer array, up to the length we specified.
import java.net.*;
public class DatagramExample1{
public static void main(String[] args){
String s = "This is a test.";
byte[] data = s.getBytes( );
try{
InetAddress ia = InetAddress.getByName("www.ibiblio.org");
int port = 7;
DatagramPacket dp
= new DatagramPacket(data, data.length, ia, port);
System.out.println("This packet is addressed to "
+ dp.getAddress( ) + " on port " + dp.getPort( ));
System.out.println("There are " + dp.getLength( )
+ " bytes of data in the packet");
System.out.println(
new String(dp.getData( ), dp.getOffset( ), dp.getLength( )));}
catch (UnknownHostException e){
System.err.println(e);}}}
 Output:
 This packet is addressed to www.ibiblio.org/152.2.254.81 on port 7
 There are 15 bytes of data in the packet
 This is a test.
DATAGRAMSOCKET
 For sending or receiving a DatagramPacket, we must
open a datagram socket. In Java, a datagram socket is
created and accessed through the DatagramSocket class.
The constructors are listed below:
Ø public DatagramSocket( ) throws SocketException
Ø public DatagramSocket(int port) throws SocketException
Ø public DatagramSocket(int port, InetAddress
interface)throws SocketException

You might also like