Url and Uri
Url and Uri
com
UNIT-VIII
NETWORKING
BASICS OF NETWORK PROGRAMMING:
DNS: Domain Naming Service is a service on internet that maps the IP addresses with
corresponding website names.
Socket Programming: is a low level way to establish connection between server and a
client with the help of a Socket.
Figure 1. The client-server models involves requests and replies: Application- server
Figure 2. The client-server models involves requests and replies: Application- server(Sql)
Figure 3. The client-server models involves requests and replies: Client-Server (Java)
One of Java's great strengths is painless networking. As much as possible, the underlying details
of networking have been abstracted away. The programming model we use is that of the file
programming model. In addition, Java's built-in multithreading is exceptionally handy when
dealing with another networking issue: handling multiple connections at once. The java.net
package includes classes that enable the programmer to easily pass data across networks.
Before plowing through the examples in the next several lessons, you should have an
understanding of some networking basics. Also, to boost your confidence, we've included a
section that reviews what you may already know about networking in Java without even
realizing it.
Sending E-Mails
Online shoping
Browsing
Chating
Downloading files
Online meeting
Data storage
Downloading remote applets
18. EchoClientSocket
In this section, we are going to explain the method to find out the hostname port number
of a local machine. This program defines the IOException for the exception handling.
19. Client Socket Information
In this section, you will learn how to get client socket information. This is a very simple
program of java network. Here, we have used the class named
ClientSocketInformation.java that implement the constructor of the Socket class
passing two arguments as hostName and TIME_PORT.
20. ReadIPAddress
Here, we are going to explore a method to retrieve the IPAddress of the local system in a
very simple example. For do for the same we have to call InetAddress class then we
need to create a object, in which we store the local host information.
21. Local Port Scanner
This is a simple program of java network. Here, we are going to define class named
"LocalPortScanner" in which we use ServerSocket class of java.net package which
takes local port number as argument.
22. Low port Scanner
In this section, you will learn how to get local port number of the local machine. Here, we
define the name of program LowPortScanner. In this we check the argument and create
a socket object.
23. URL Connection Reader
In this section, you will learn about the url connection reader. Here, first of all we are
going to define class named "URLConnectionReader". After that we make a URL
object passing a url "http://www.javajazzup.com" as string in its constructor.
24. URL Reader File
This is a simple program of java network. In this section, you will learn how to read
HTML file. Here, we create a URL object and pass a url. After that, we call the URL?s
openStream() method to get a stream from which the contents of the URL can be read.
25. RMI Client And RMI Server Implementation
The RMI application comprises of the two separate programs, a server and a client. A
typical server program creates some remote objects, makes references to these objects
accessible, and waits for clients to invoke methods on these objects.
Interface Summary
Class Summary
protocol handler.
Socket This class implements client sockets (also called just "sockets").
This class loader is used to load classes and resources from a search
URLClassLoader
path of URLs referring to both JAR files and directories.
Enum Summary
Exception Summary
Asking the question What is the Internet? may bring about a heated discussion in some circles. In
this book, the Internet is defined as the collection of all computers that are able to communicate,
using the Internet protocol suite, with the computers and networks registered with the Internet
Network Information Center (InterNIC). This definition includes all computers to which you can
directly (or indirectly through a firewall) send Internet Protocol packets.
In order for IP to send packets from a source computer to a destination computer, it must have
some way of identifying these computers. All computers on the Internet are identified using one
or more IP addresses. A computer may have more than one IP address if it has more than one
interface to computers that are connected to the Internet.
JDK 1.0). Since version 1.4 non-blocking IO through buffers and channels is also integral part of
standard Java distribution (but we are not going to go through non-blocking IO in this tutorial).
Package java.net can be divided into two parts: application layer and transport layer classes. TCP
and UDP protocols (on top of IP) are fully supported so a complete freedom while writing
network applications is guaranteed.
This part includes higher level classes which enables working with URI and URL addresses and
connections created using those addresses. The most important classes are URI, URL,
URLConnection, and HttpURLConnection. These classes can be useful if for acquiring
connections with a computer on Internet, if you want to parse HTML pages, create HTTP-based
connections etc.
This part of the java.net package is all that is needed for a basic support for application layer in
TCP/IP protocol – there is a huge number of third party classes on Internet which are not
integral part of the standard Java distribution – some of them will help you send an email,
some other will help you to contact some Web service etc.
This part of the java.net package is what distributed network programming is all about. This is
the lowest level that Java allows somebody to work on while doing network programming (TCP
& UDP) and what all other high level network and distributed programming Java toolkits are
based on. Basic three elements in this below level part of java.net are:
address
socket
interface
Address (IPv4, Ipv6) is being used as a identifier for network adapter in a network. Although two
different classes exist in this package for IPv4 and IPv6 (INet4Address and INet6Address), a
suggestion is to use base class InetAddress because Java will automatically adopt and use the
right class so a programmer does not have to worry about protocol version.
Interfaces are being used for querying network adapter and hardware for properties (through Java
interface NetworkInterface). Some of things that can be found out are which is hardware (MAC)
address of the network adapter, what is device MTU, which addresses are mapped on a network
device etc.
Socket is, basically, standardized bidirectional communication mechanism. Socket class for TCP
is Socket and socket class for UDP protocol called DatagramSocket. Both sides in UDP
communication are with same rights (client/server paradigm is not completely meaningful in this
case).
UDP protocol is much simpler and usually being used for streaming protocols (audio & video
network transmissions) because it is unsafe transportation mechanism. Being unsafe means that
it is not a good choice in network programming so usually it's best to choose TCP as a network
transportation protocol.
• IP
– raw packets
– the “Internet Layer”
• TCP
– data stream
– reliable, ordered
– the “Transport Layer”
• UDP
– user datagrams (packets)
– unreliable, unordered
– the “Transport Layer”
Hyper Text Transfer Protocol: To transfer the web pages (.html files) from one computer to
another computer on internet.
File Transfer Protocol: To download or upload files from and to the server.
Connection-oriented programming
Connectionless Programming
Connection-oriented Networking
The client and server have a communication link that is open and active from the time the
application is executed until it is closed. Using Internet jargon, the Transmission control protocol
os a connection oriented protocol. It is reliable connection - packets are guaranteed to arrive in
the order they are sent.
Connection-less Networking
The this type each instance that packets are sent, they are transmitted individually. No link to the
receiver is maintained after the packets arrive. The Internet equivalent is the User Datagram
Protocol (UDP). Connectionless communication is faster but not reliable.
URL:
Definition:
URL is an acronym for Uniform Resource Locator and is a reference (an address) to a
resource on the Internet.
You provide URLs to your favorite Web browser so that it can locate files on the Internet in the
same way that you provide addresses on letters so that the post office can locate your
correspondents.
Java programs that interact with the Internet also may use URLs to find the resources on the
Internet they wish to access. Java programs can use a class called URL in the java.net package
to represent a URL address.
Terminology Note:
The term URL can be ambiguous. It can refer to an Internet address or a URL object in a Java
program. Where the meaning of URL needs to be specific, this text uses "URL address" to mean
an Internet address and "URL object" to refer to an instance of the URL class in a program.
What Is a URL?
A URL takes the form of a string that describes how to find a resource on the Internet. URLs
have two main components: the protocol needed to access the resource and the location of the
resource.
Creating a URL
Within your Java programs, you can create a URL object that represents a URL address. The
URL object always refers to an absolute URL but can be constructed from an absolute URL, a
relative URL, or from URL components.
Parsing a URL
Gone are the days of parsing a URL to find out the host name, filename, and other information.
With a valid URL object you can call any of its accessor methods to get all of that information
from the URL without doing any string parsing!
This section shows how your Java programs can read from a URL using the openStream()
method.
Connecting to a URL
If you want to do more than just read from a URL, you can connect to it by calling
openConnection() on the URL. The openConnection() method returns a URLConnection object
that you can use for more general communications with the URL, such as reading from it,
writing to it, or querying it for content and other information.
Some URLs, such as many that are connected to cgi-bin scripts, allow you to (or even require
you to) write information to the URL. For example, a search script may require detailed query
data to be written to the URL before the search can be performed. This section shows you how to
write to a URL and how to get results back.
Protocol identifier: For the URL http://example.com, the protocol identifier is http.
Resource name: For the URL http://example.com, the resource name is example.com.
Note that the protocol identifier and the resource name are separated by a colon and two forward
slashes. The protocol identifier indicates the name of the protocol to be used to fetch the
resource. The example uses the Hypertext Transfer Protocol (HTTP), which is typically used to
serve up hypertext documents. HTTP is just one of many different protocols used to access
different types of resources on the net. Other protocols include File Transfer Protocol (FTP),
Gopher, File, and News.
The resource name is the complete address to the resource. The format of the resource name
depends entirely on the protocol used, but for many protocols, including HTTP, the resource
name contains one or more of the following components:
Host Name
The name of the machine on which the resource lives.
Filename
The pathname to the file on the machine.
Port Number
The port number to which to connect (typically optional).
Reference
A reference to a named anchor within a resource that usually identifies a specific location
within a file (typically optional).
For many protocols, the host name and the filename are required, while the port number and
reference are optional. For example, the resource name for an HTTP URL must specify a server
on the network (Host Name) and the path to the document on that machine (Filename); it also
can specify a port number and a reference.
Creating a URL
The easiest way to create a URL object is from a String that represents the human-readable form
of the URL address. This is typically the form that another person will use for a URL. In your
Java program, you can use a String containing this text to create a URL object:
The URL object created above represents an absolute URL. An absolute URL contains all of the
information necessary to reach the resource in question. You can also create URL objects from a
relative URL address.
A relative URL contains only enough information to reach the resource relative to (or in the
context of) another URL.
Relative URL specifications are often used within HTML files. For example, suppose you write
an HTML file called JoesHomePage.html. Within this page, are links to other pages,
PicturesOfMe.html and MyKids.html, that are on the same machine and in the same directory as
JoesHomePage.html. The links to PicturesOfMe.html and MyKids.html from
JoesHomePage.html could be specified just as filenames, like this:
These URL addresses are relative URLs. That is, the URLs are specified relative to the file in
which they are contained — JoesHomePage.html.
In your Java programs, you can create a URL object from a relative URL specification. For
example, suppose you know two URLs at the site example.com:
http://example.com/pages/page1.html
http://example.com/pages/page2.html
You can create URL objects for these pages relative to their common base URL:
http://example.com/pages/ like this:
This code snippet uses the URL constructor that lets you create a URL object from another URL
object (the base) and a relative URL specification. The general form of this constructor is:
The first argument is a URL object that specifies the base of the new URL. The second argument
is a String that specifies the rest of the resource name relative to the base. If baseURL is null,
then this constructor treats relativeURL like an absolute URL specification. Conversely, if
relativeURL is an absolute URL specification, then the constructor ignores baseURL.
This constructor is also useful for creating URL objects for named anchors (also called
references) within a file. For example, suppose the page1.html file has a named anchor called
BOTTOM at the bottom of the file. You can use the relative URL constructor to create a URL
object for it like this:
The URL class provides two additional constructors for creating a URL object. These
constructors are useful when you are working with URLs, such as HTTP URLs, that have host
name, filename, port number, and reference components in the resource name portion of the
URL. These two constructors are useful when you do not have a String containing the complete
URL specification, but you do know various components of the URL.
For example, suppose you design a network browsing panel similar to a file browsing panel that
allows users to choose the protocol, host name, port number, and filename. You can construct a
URL from the panel's components. The first constructor creates a URL object from a protocol,
host name, and filename. The following code snippet creates a URL to the page1.html file at the
example.com site:
This is equivalent to
new URL("http://example.com/pages/page1.html");
The first argument is the protocol, the second is the host name, and the last is the pathname of
the file. Note that the filename contains a forward slash at the beginning. This indicates that the
filename is specified from the root of the host.
The final URL constructor adds the port number to the list of arguments used in the previous
constructor:
If you construct a URL object using one of these constructors, you can get a String containing
the complete URL address by using the URL object's toString method or the equivalent
toExternalForm method.
import java.net.*;
System.out.println("Protocal:" + obj.getProtocol());
System.out.println("Port:" + obj.getPort());
System.out.println("Host:" + obj.getHost());
System.out.println("File:" + obj.getFile());
System.out.println("path:" + obj.getPath());
System.out.println("Ext:" + obj.toExternalForm());
OUTPUT:
Some URL addresses contain special characters, for example the space character. Like this:
http://example.com/hello world/
To make these characters legal they need to be encoded before passing them to the URL
constructor.
Encoding the special character(s) in this example is easy as there is only one character that needs
encoding, but for URL addresses that have several of these characters or if you are unsure when
writing your code what URL addresses you will need to access, you can use the multi-argument
constructors of the java.net.URI class to automatically take care of the encoding for you.
MalformedURLException
Each of the four URL constructors throws a MalformedURLException if the arguments to the
constructor refer to a null or unknown protocol. Typically, you want to catch and handle this
exception by embedding your URL constructor statements in a try/catch pair, like this:
try {
URL myURL = new URL(...);
}
catch (MalformedURLException e) {
// exception handler code here
// ...
}
Note: URLs are "write-once" objects. Once you've created a URL object, you cannot change any of its
attributes (protocol, host name, filename, or port number).
Parsing a URL
The URL class provides several methods that let you query URL objects. You can get the protocol,
authority, host name, port number, path, query, filename, and reference from a URL using these
accessor methods:
getProtocol
getAuthority
getHost
getPort
Returns the port number component of the URL. The getPort method returns an integer that
is the port number. If the port is not set, getPort returns -1.
getPath
getQuery
getFile
Returns the filename component of the URL. The getFile method returns the same as
getPath, plus the concatenation of the value of getQuery, if any.
getRef
Note: Remember that not all URL addresses contain these components. The URL class provides these
methods because HTTP URLs do contain these components and are perhaps the most commonly used
URLs. The URL class is somewhat HTTP-centric.
You can use these getXXX methods to get information about the URL regardless of the
constructor that you used to create the URL object.
The URL class, along with these accessor methods, frees you from ever having to parse URLs
again! Given any string specification of a URL, just create a new URL object and call any of the
accessor methods for the information you need. This small example program creates a URL from
a string specification and then uses the URL object's accessor methods to parse the URL:
import java.net.*;
import java.io.*;
After you've successfully created a URL, you can call the URL's openStream() method to get a
stream from which you can read the contents of the URL. The openStream() method returns a
java.io.InputStream object, so reading from a URL is as easy as reading from an input stream.
The following small Java program uses openStream() to get an input stream on the URL
http://www.oracle.com/. It then opens a BufferedReader on the input stream and reads from the
BufferedReader thereby reading from the URL. Everything read is copied to the standard output
stream:
import java.net.*;
import java.io.*;
When you run the program, you should see, scrolling by in your command window, the HTML
commands and textual content from the HTML file located at http://www.oracle.com/.
Alternatively, the program might hang or you might see an exception stack trace. If either of the
latter two events occurs, you may have to set the proxy host so that the program can find the
Oracle server.
Connecting to a URL
For a Java program to interact with a server-side process it simply must be able to write to a
URL, thus providing data to the server. It can do this by following these steps:
1. Create a URL.
2. Retrieve the URLConnection object.
3. Set output capability on the URLConnection.
4. Open a connection to the resource.
5. Get an output stream from the connection.
6. Write to the output stream.
7. Close the output stream.
After you've successfully created a URL object, you can call the URL object's openConnection
method to get a URLConnection object, or one of its protocol specific subclasses, e.g.
java.net.HttpURLConnection
You can use this URLConnection object to setup parameters and general request properties that
you may need before connecting. Connection to the remote object represented by the URL is
only initiated when the URLConnection.connect method is called. When you do this you are
initializing a communication link between your Java program and the URL over the network. For
example, the following code opens a connection to the site example.com:
try {
URL myURL = new URL("http://example.com/");
URLConnection myURLConnection = myURL.openConnection();
myURLConnection.connect();
}
catch (MalformedURLException e) {
// new URL() failed
// ...
}
catch (IOException e) {
// openConnection() failed
// ...
}
A new URLConnection object is created every time by calling the openConnection method of
the protocol handler for this URL.
You are not always required to explicitly call the connect method to initiate the connection.
Operations that depend on being connected, like getInputStream, getOutputStream, etc, will
implicitly perform the connection, if necessary.
Now that you've successfully connected to your URL, you can use the URLConnection object to
perform actions such as reading from or writing to the connection. The next section shows you
how.
// Demonstrate URLConnection.
import java.net.*;
import java.io.*;
import java.util.Date;
class UCDemo
int c;
// get date
long d = hpCon.getDate();
if(d==0)
else
d = hpCon.getExpiration();
if(d==0)
else
d = hpCon.getLastModified();
if(d==0)
else
if(len == -1)
else
if(len != 0) {
int i = len;
System.out.print((char) c);
input.close();
} else {
Output:
URLReadFile
This is a simple program of java network. In this section, you will learn how to read HTML file.
Here, we create a URL object and pass a url. After that, we call the URL?s openStream()
method to get a stream from which the contents of the URL can be read. The openStream()
method returns a java.io.InputStream, so reading from a URL is as easy as reading from an
input stream. The simple java program uses openStream() method to get an input stream on the
URL " file:///D:/java/AppletDemo.html" . This URL opens a BufferedReader on the input stream
and reads from the BufferedReader thereby reading from the URL. When you run the program
then the HTML code and textual content from the HTML file will be displayed on the command
line.
import java.net.*;
import java.io.*;
try{
String str;
System.out.println("\n");
System.out.println(str);
buff.close();
catch(IOException e){
System.err.println(e);
Output:
ADDRESS:
Addresses are used throughout the java.net APIs as either host identifiers, or socket endpoint
identifier. Address (IPv4, Ipv6) is being used as a identifier for network adapter in a network.
Although two different classes exist in this package for IPv4 and IPv6 (INet4Address and
INet6Address), a suggestion is to use base class InetAddress because Java will automatically
adopt and use the right class so a programmer does not have to worry about protocol version.
IP addresses are 32-bit numbers. They may be written in decimal, hexadecimal, or other formats,
but the most common format is dotted decimal notation. This format breaks the 32-bit address up
into four bytes and writes each byte of the address as unsigned decimal integers separated by
dots. For example, one of my IP addresses is 0xccD499C1. Because 0xcc = 204, 0xD4 = 212,
0x99 = 153, and 0xC1 = 193, my address in dotted decimal form is 204.212.153.193.
IP addresses are not easy to remember, even using dotted decimal notation. The Internet has
adopted a mechanism, referred to as the Domain Name System (DNS), whereby computer names
can be associated with IP addresses. These computer names are referred to as domain names.
The DNS has several rules that determine how domain names are constructed and how they
relate to one another. For the purposes of this chapter, it is sufficient to know that domain names
are computer names and that they are mapped to IP addresses.
import java.io.*;
import java.net.*;
class Address
String site=br.readLine();
try
InetAddress ip=InetAddress.getByName(site);
catch(UnknownHostException ue)
Output:
import java.net.*;
import java.io.*;
try {
System.out.println("hostname="+hostname);
} catch (UnknownHostException e) {
OUTPUT:
java.net
Class InetAddress
java.lang.Object
java.net.InetAddress
All Implemented Interfaces:
Serializable
An IP address is either a 32-bit or 128-bit unsigned number used by IP, a lower-level protocol on
which protocols like UDP and TCP are built. The IP address architecture is defined by RFC 790:
Assigned Numbers, RFC 1918: Address Allocation for Private Internets, RFC 2365:
Administratively Scoped IP Multicast, and RFC 2373: IP Version 6 Addressing Architecture. An
instance of an InetAddress consists of an IP address and possibly its corresponding host name
(depending on whether it is constructed with a host name or whether it has already done reverse
host name resolution).
Address types
Unicast An identifier for a single interface. A packet sent to a unicast address is delivered to
the interface identified by that address.
The Unspecified Address -- Also called anylocal or wildcard address. It must never be
assigned to any node. It indicates the absence of an address. One example of its use is
as the target of bind, which allows a server to accept a client connection on any
interface, in case the server host has multiple interfaces.
The unspecified address must not be used as the destination address of an IP packet.
The Loopback Addresses -- This is the address assigned to the loopback interface.
Anything sent to this IP address loops around and becomes IP input on the local host.
This address is often used when testing a client.
multicast An identifier for a set of interfaces (typically belonging to different nodes). A packet
sent to a multicast address is delivered to all interfaces identified by that address.
IP address scope
Link-local addresses are designed to be used for addressing on a single link for purposes such as
auto-address configuration, neighbor discovery, or when no routers are present.
Site-local addresses are designed to be used for addressing inside of a site without the need for a
global prefix.
For IPv4 address format, please refer to Inet4Address#format; For IPv6 address format, please
refer to Inet6Address#format.
Reverse name resolution means that for any IP address, the host associated with the IP address is
returned.
The InetAddress class provides methods to resolve host names to their IP addresses and vise
versa.
InetAddress Caching
The InetAddress class has a cache to store successful as well as unsuccessful host name
resolutions. The positive caching is there to guard against DNS spoofing attacks; while the
negative caching is used to improve performance.
By default, the result of positive host name resolutions are cached forever, because there is no
general rule to decide when it is safe to remove cache entries. The result of unsuccessful host
name resolution is cached for a very short period of time (10 seconds) to improve performance.
Under certain circumstances where it can be determined that DNS spoofing attacks are not
possible, a Java security property can be set to a different Time-to-live (TTL) value for positive
caching. Likewise, a system admin can configure a different negative caching TTL value when
needed.
Two Java security properties control the TTL values used for positive and negative host name
resolution caching:
The InetAddress class encapsulates Internet addresses. It supports both numeric IP addresses and
hostnames.
The InetAddress class has no public variables or constructors. It provides eight access methods
that support common operations on Internet addresses. Three of these methods are static.
The NSLookupApp program illustrates the use of the InetAddress class. It takes a hostname as a
parameter and identifies the primary IP address associated with that host.
The InetAddress class is the abstraction representing an IP (Internet Protocol) address, it has two
subclasses:
But, in most cases, there is no need to deal directly with the subclasses, as the InetAddress
abstraction should cover most of needed functionalities.
Textual representation of IPv4 address used as input to methods takes one of the following forms:
d.d.d.d
d.d.d
d.d
When four parts are specified, each is interpreted as a byte of data and assigned, from left to right, to the
four bytes of an IPv4 address.
When a three part address is specified, the last part is interpreted as a 16-bit quantity and placed in the
right most two bytes of the network address. This makes the three part address format convenient for
specifying Class B net- work addresses as 128.net.host.
When a two part address is supplied, the last part is interpreted as a 24-bit quantity and placed in the right
most three bytes of the network address. This makes the two part address format convenient for
specifying Class A network addresses as net.host.
When only one part is given, the value is stored directly in the network address without any byte
rearrangement.
For methods that return a textual representation as output value, the first form, i.e. a dotted-quad string, is
used.
About IPv6
Not all systems do have support for the IPv6 protocol, and while the Java networking stack will
attempt to detect it and use it transparently when available, it is also possible to disable its use
with a system property. In the case where IPv6 is not available, or explicitly disabled,
Inet6Address are not valid arguments for most networking operations any more. While methods
like java.net.InetAddress.getByName is guaranteed not to return an Inet6Address when looking
up host names, it is possible, by passing literals, to create such an object. In which case, most
methods, when called with an Inet6Address will throw an Exception.
// Demonstrate InetAddress.
import java.net.*;
class InetAddressTest
System.out.println(Address);
Address = InetAddress.getByName("www.google.com");
System.out.println(Address);
System.out.println(SW[i]);
OUTPUT:
PORT:
Understanding Ports
Generally speaking, a computer has a single physical connection to the network. All data
destined for a particular computer arrives through that connection. However, the data may be
intended for different applications running on the computer. So how does the computer know to
which application to forward the data? Through the use of ports.
Data transmitted over the Internet is accompanied by addressing information that identifies the
computer and the port for which it is destined. The computer is identified by its 32-bit IP
address, which IP uses to deliver data to the right computer on the network. Ports are identified
by a 16-bit number, which TCP and UDP use to deliver the data to the right application.
Definition:
The TCP and UDP protocols use ports to map incoming data to a particular process running on a
computer.
In datagram-based communication such as UDP, the datagram packet contains the port number
of its destination and UDP routes the packet to the appropriate application, as illustrated in this
figure:
Port numbers range from 0 to 65,535 because ports are represented by 16-bit numbers. The port
numbers ranging from 0 - 1023 are restricted; they are reserved for use by well-known services
such as HTTP and FTP and other system services. These ports are called well-known ports. Your
applications should not attempt to bind to them.
While the IP address will get the packet to the right computer, how does the packet get to the
right program? A computer might have:
The Port number is the key for organizing all of this. The packets are guided to the correct
program by the operating system according to the port number as indicated in this diagram:.
http://www.someplace.com:80/
where 80 is the default for the HTTP server. Nowadays the port number is seldom included in
the URL since the default is almost always used.
Various applications using particular protocols use standard port values as shown in tthe above
diagram. Unix machines reserve ports 1-1023 for standard services. Windows machines do not
restrict the use of these ports but to make your Java programs portable, it is wise to use port
values above 1023.
One type of firewall assigns port numbers to the machines behind its shield. Incoming packets all
go to the same IP address but with different port numbers according to the machine they are
destined for. This both reduces the exposure and accessibility to the machines and reduces the
need for universally unique IP numbers. Behind the firewall, the local addresses can be the same
as in other LANs since the LANs are isolated from each other.
This is one of the reasons that four bytes remain sufficient for the internet despite the explosion
in the number of devices with IP addresses. (Nevertheless, a sixteen byte version of IP
addressing called IPv6 will gradually take over.)
Well-Known Ports
• 20,21: FTP
• 23: telnet
• 25: SMTP
Prepared by P.VeeraGoud:M.Tech:CSE(BVRIT) Page 37
www.jntuworld.com
• 43: whois
• 80: HTTP
• 119: NNTP
• 1099: RMI
SOCKET:
Normally, a server runs on a specific computer and has a socket that is bound to a specific port
number. The server just waits, listening to the socket for a client to make a connection request.
On the client-side: The client knows the hostname of the machine on which the server is running
and the port number on which the server is listening. To make a connection request, the client
tries to rendezvous with the server on the server's machine and port. The client also needs to
identify itself to the server so it binds to a local port number that it will use during this
connection. This is usually assigned by the system.
If everything goes well, the server accepts the connection. Upon acceptance, the server gets a
new socket bound to the same local port and also has its remote endpoint set to the address and
port of the client. It needs a new socket so that it can continue to listen to the original socket for
connection requests while tending to the needs of the connected client.
On the client side, if the connection is accepted, a socket is successfully created and the client
can use the socket to communicate with the server.
The client and server can now communicate by writing to or reading from their sockets.
Definition:
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 so that the TCP layer can identify the
application that data is destined to be sent.
An endpoint is a combination of an IP address and a port number. Every TCP connection can be
uniquely identified by its two endpoints. That way you can have multiple connections between
your host and the server.
The java.net package in the Java platform provides a class, Socket, that implements one side of a
two-way connection between your Java program and another program on the network. The
Socket class sits on top of a platform-dependent implementation, hiding the details of any
particular system from your Java program. By using the java.net.Socket class instead of relying
on native code, your Java programs can communicate over the network in a platform-
independent fashion.
Additionally, java.net includes the ServerSocket class, which implements a socket that
servers can use to listen for and accept connections to clients. This lesson shows you how to use
the Socket and ServerSocket classes.
If you are trying to connect to the Web, the URL class and related classes (URLConnection,
URLEncoder) are probably more appropriate than the socket classes. In fact, URLs are a
relatively high-level connection to the Web and use sockets as part of the underlying
implementation. See Working with URLs for information about connecting to the Web via
URLs.
Class Socket
java.lang.Object
java.net.Socket
Direct Known Subclasses:
SSLSocket
This class implements client sockets (also called just "sockets"). A socket is an endpoint for
communication between two machines.
The actual work of the socket is performed by an instance of the SocketImpl class. An
application, by changing the socket factory that creates the socket implementation, can configure
itself to create sockets appropriate to the local firewall.
Constructor Summary
Socket()
Creates an unconnected socket, with the system-default type of SocketImpl.
specified IP address.
Socket(Proxy proxy)
Creates an unconnected socket, specifying the type of proxy, if any, that should
be used regardless of any other settings.
Method Summary
void close()
Closes this socket.
SocketChannel getChannel()
Returns the unique SocketChannel object associated with this socket, if
any.
InetAddress getInetAddress()
Returns the address to which the socket is connected.
InputStream getInputStream()
Returns an input stream for this socket.
boolean getKeepAlive()
Tests if SO_KEEPALIVE is enabled.
InetAddress getLocalAddress()
Gets the local address to which the socket is bound.
int getLocalPort()
Returns the local port to which this socket is bound.
SocketAddress getLocalSocketAddress()
Returns the address of the endpoint this socket is bound to, or null if it is
not bound yet.
boolean getOOBInline()
Tests if OOBINLINE is enabled.
OutputStream getOutputStream()
Returns an output stream for this socket.
int getPort()
Returns the remote port to which this socket is connected.
int getReceiveBufferSize()
Gets the value of the SO_RCVBUF option for this Socket, that is the
buffer size used by the platform for input on this Socket.
SocketAddress getRemoteSocketAddress()
Returns the address of the endpoint this socket is connected to, or null if it
is unconnected.
boolean getReuseAddress()
int getSendBufferSize()
Get value of the SO_SNDBUF option for this Socket, that is the buffer
size used by the platform for output on this Socket.
int getSoLinger()
Returns setting for SO_LINGER.
int getSoTimeout()
Returns setting for SO_TIMEOUT.
boolean getTcpNoDelay()
Tests if TCP_NODELAY is enabled.
int getTrafficClass()
Gets traffic class or type-of-service in the IP header for packets sent from
this Socket
boolean isBound()
Returns the binding state of the socket.
boolean isClosed()
Returns the closed state of the socket.
boolean isConnected()
Returns the connection state of the socket.
boolean isInputShutdown()
Returns whether the read-half of the socket connection is closed.
boolean isOutputShutdown()
Returns whether the write-half of the socket connection is closed.
discarded.
void shutdownInput()
Places the input stream for this socket at "end of stream".
void shutdownOutput()
Disables the output stream for this socket.
String toString()
Converts this socket to a String.
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
Class SocketAddress
java.lang.Object
java.net.SocketAddress
All Implemented Interfaces:
Serializable
Direct Known Subclasses:
InetSocketAddress
This class represents a Socket Address with no protocol attachment. As an abstract class, it is
meant to be subclassed with a specific, protocol dependent, implementation.
This client program is straightforward and simple because the Echo server implements a simple
protocol. The client sends text to the server, and the server echoes it back. When your client
programs are talking to a more complicated server such as an HTTP server, your client program
will also be more complicated. However, the basics are much the same as they are in this
program:
1. Open a socket.
2. Open an input stream and output stream to the socket.
3. Read from and write to the stream according to the server's protocol.
4. Close the streams.
5. Close the socket.
Only step 3 differs from client to client, depending on the server. The other steps remain largely
the same.
Code
) send to server
actionPerformed() {...}
waitForPackets() {...} packet
) receive echo
from sender packet
- Cli/Serv.: jnet/ 0
Constructors
• There are three constructors that specify the port to bind to, the queue length for
incoming connections, and the IP address to bind to:
display
packet
) echo back
packet to client
- Cli/Serv.: jnet/ 9
Socket Socket
Server
L 4.3
· When the service on the socket is changed we should change the port number.
Program : Write a program to create a server for sending some strings to the client.
import java.net.*;
import java.io.*;
class Server1
ps.println (str);
ps.println ("Bye");
//close connection
s.close ();
ss.close ();
ps.close ();
Output:
Program : Write a program to create a client which accepts all the strings sent by the server
import java.util.*;
import java.io.*;
import java.net.*;
class Client1
String str;
System.out.println (str);
//close connection
s.close ();
br.close ();
Output:
After compiling Server1.java and Client1.java, run these programs in two separate dos windows:
Program : Write a program to create a server such that the server receives data from the client
using BufferedReader and then sends reply to the client using PrintStream.
//chat server
import java.net.*;
import java.io.*;
class Server2
(s.getInputStream ()));
{ System.out.println (str);
ps.println (str1);
System.exit (0);
Output:
Program : Write a program to create a client which first connects to a server then starts the
//chat client
import java.net.*;
import java.io.*;
class Client2
(s.getInputStream ()));
System.out.println (str1);
s.close ();
Output:
A simple client and the server programs are explained for all the types of techniques. A code
samples for the connection-oriented, next for the connectionless and then for broadcasting are as
follows.
The client sends the message " Hi from client " and the server response will be " Hello from
Server ".
Server Program
import java.net.*;
import java.lang.*;
import java.io.*;
try
{
// Initialising the ServerSocket
sersock = new ServerSocket(PORT);
try
{
sock = sersock.accept();
sock.close();
}
catch(SocketException se)
{
System.out.println("Server Socket
problem "+se.getMessage());
}
catch(Exception e)
{
System.out.println("Couldn't start "
+ e.getMessage()) ;
}
} // main
} // Server class
Client Program
import java.lang.*;
import java.io.*;
import java.net.*;
import java.net.InetAddress;
class client
{
Public static void main(String args[])
{
Socket sock=null;
DataInputStream dis=null;
PrintStream ps=null;
System.out.println(" Trying to connect");
try
{
// to get the ip address of the
server by the name
InetAddress ip =InetAddress.getByName
("Hari.calsoftlabs.com");
}
0catch(SocketException e)
{
System.out.println("SocketException " + e);
}
catch(IOException e)
{
System.out.println("IOException " + e);
}
finally
{
try
{
sock.close();
}
catch(IOException ie)
{
System.out.println(" Close Error :" +
ie.getMessage());
}
} // finally
} // main
} // Class Client
After you've successfully compiled the server and the client programs, you run them. You have
to run the server program first. Just use the Java interpreter and specify the Server class name.
Once the server has started, you can run the client program. After the client sends a request and
receives a response from the server, you should see output similar to this :
On client side:
Hello from Server
On Server side:
Hi from client
Datagrams
TCP/IP-style networking is appropriate for most networking needs. It provides a serialized,
predictable, reliable stream of packet data. This is not without its cost, however. TCP includes
many complicated algorithms for dealing with congestion control on crowded networks, as well
as pessimistic expectations about packet loss. This leads to a somewhat inefficient way to
transport data. Datagrams provide an alternative.
Datagrams are bundles of information passed between machines. They are somewhat like a
hard throw from a well-trained but blindfolded catcher to the third baseman.
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.
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 the DatagramPackets. Each is examined here.
DatagramSocket:
DatagramSocket defines four public constructors. They are shown here:
DatagramPacket:
DatagramPacket defines several constructors. Four are shown here:
DatagramPacket(byte data[ ], int size)
The first constructor specifies a buffer that will receive data and the size of a packet. It is used
for receiving data over a DatagramSocket.
DatagramPacket(byte data[ ], int offset, int size)
The second form allows you to specify an offset into the buffer at which data will be stored.
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(byte data[ ], int offset, int size, InetAddress ipAddress, int port)
The fourth form transmits packets beginning at the specified offset into the data.
Think of the first two forms as building an “in box,” and the second two forms as stuffing and
addressing an envelope.
DatagramPacket defines several methods, including those shown here, that give access to the
address and port number of a packet, as well as the raw data and its length. In general, the get
methods are used on packets that are received and the set methods are used on packets that will
be sent.
A Datagram Example
The following example implements a very simple networked communications client and server.
Messages are typed into the window at the server and written across the network to the client
side, where they are displayed.
Connectionless Client and Server : (UDP)
A datagram is an independent, self-contained message sent over the network whose arrival,
arrival time, and content are not guaranteed.
The java.net package contains two classes to help you write Java programs that use datagrams to
send and receive packets over the network: DatagramSocket, DatagramPacket, and
MulticastSocket An application can send and receive DatagramPackets through a
DatagramSocket. In addition, DatagramPackets can be broadcast to multiple recipients all
listening to a MulticastSocket.
The following source code demonstrates a slightly more complex server that uses datagrams
instead of sockets. After a connection is made, It echoes back whatever is sent by the client
instead of simply hanging up the connection. It is Called as echo Server.
Server Program
import java.net.*;
import java.io.*;
DatagramPacket packet;
DatagramSocket socket;
byte[] data; // For data to be
Sent in packets
int clientPort;
InetAddress address;
String str;
for(;;){
data = new byte[packetSize];
try{
socket.receive(packet);
}catch(IOException ie)
{
System.out.println(" Could not Receive
:"+ie.getMessage());
System.exit(0);
}
address = packet.getAddress();
clientPort = packet.getPort();
try
{
// sends packet
socket.send(packet);
}
catch(IOException ex)
{
System.out.println("Could not Send
"+ex.getMessage());
System.exit(0);
}
} // for loop
} // main
} // class EchoServer
Client Program
import java.net.*;
import java.io.*;
if(args.length != 2)
{
System.out.println("Usage Error :
Java EchoClient < Server name> < Message>");
System.exit(0);
}
try
{
// sends the packet
socket.send(packet);
}
catch(IOException ie)
{
System.out.println("Could not Send :"+ie.getMessage());
System.exit(0);
}
try
{
// Receives the packet from the server
socket.receive(packet);
}
catch(IOException iee)
{
System.out.println("Could not receive :
"+iee.getMessage() );
System.exit(0);
}
} // Class EchoClient
The client side and the server side networking code looks actually very similar.This is true with
many applications that use datagrams because the java.net.DatagramSocket class is used to both
send and receive DatagramPackets.
Suppose server running on the machine named Hari.calsoftlabs.com, whereas the client running
on the xxxx.info.com. As you can see at the end of the example the server is running waiting for
the another connection, while the execution of the client has halted.
Server Side :
Java EchoServer
Output:
Message:Hello
From :xxxx.info.com
Client Side :
Output:
Multiple Clients:
• Multiple clients can connect to the same port on the server at the same time.
• Incoming data is distinguished by the port to which it is addressed and the client host and
port from which it came.
• The server can tell for which service (like http or ftp) the data is intended by inspecting
the port.
• It can tell which open socket on that service the data is intended for by looking at the
client address and port stored with the data.
Java Programming Language Basics , finished with a simple network communications example
using the Remote Method Invocation (RMI) application programming interface (API). The RMI
example allows multiple client programs to communicate with the same server program without
any explicit code to do this because the RMI API is built on sockets and threads.
This lesson presents a simple sockets-based program to introduce the concepts of sockets and
multi-threaded programming. A multi-threaded program performs multiple tasks at one time
such as fielding simultaneous requests from many client programs.
A server program typically provides resources to a network of client programs. Client programs
send requests to the server program, and the server program responds to the request.
One way to handle requests from more than one client is to make the server program multi-
threaded. A multi-threaded server creates a thread for each communication it accepts from a
client. A thread is a sequence of instructions that run independently of the program and of any
other threads.
Using threads, a multi-threaded server program can accept a connection from a client, start a
thread for that communication, and continue listening for requests from other clients.
The example in its current state works between the server program and one client program only.
To allow multiple client connections, the server program has to be converted to a multithreaded
server program.
import java.awt.Color;
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
this.client = client;
this.textArea = textArea;
String line;
BufferedReader in = null;
try{
} catch (IOException e) {
System.exit(-1);
while(true){
try{
line = in.readLine();
out.println(line);
textArea.append(line);
} catch (IOException e) {
System.out.println("Read failed");
System.exit(-1);
JPanel panel;
panel.setLayout(new BorderLayout());
panel.setBackground(Color.white);
getContentPane().add(panel);
panel.add("North", label);
panel.add("Center", textArea);
} //End Constructor
try{
} catch (IOException e) {
System.exit(-1);
while(true){
ClientWorker w;
try{
t.start();
} catch (IOException e) {
System.exit(-1);
try{
server.close();
} catch (IOException e) {
System.exit(-1);
frame.setTitle("Server Program");
System.exit(0);
};
frame.addWindowListener(l);
frame.pack();
frame.setVisible(true);
frame.listenSocket();
Program Explanation:
In this example the listenSocket method loops on the server.accept call waiting for client
connections and creates an instance of the ClientWorker class for each client connection it
accepts. The textArea component that displays the text received from the client connection is
passed to the ClientWorker instance with the accepted client connection.
The important changes in this version of the server program over the non-threaded server
program are the line and client variables are no longer instance variables of the server class, but
are handled inside the ClientWorker class.
The ClientWorker class implements the Runnable interface, which has one method, run. The run
method executes independently in each thread. If three clients request connections, three
ClientWorker instances are created, a thread is started for each ClientWorker instance, and the
run method executes for each thread.
In this example, the run method creates the input buffer and output writer, loops on the input
stream waiting for input from the client, sends the data it receives back to the client, and sets the
text in the text area.
//Constructor
ClientWorker(Socket client, JTextArea textArea) {
this.client = client;
this.textArea = textArea;
}
while(true){
try{
line = in.readLine();
//Send data back to client
out.println(line);
//Append data to text area
textArea.append(line);
}catch (IOException e) {
System.out.println("Read failed");
System.exit(-1);
}
}
}
}
JTextArea.appendJTextArea.appendtextArea.append(line)synchronizedruntextArea.
append(line)appendText(line)
public synchronized void appendText(line){
textArea.append(line);
}
synchronizedtextAreatextArea
The finalize() method is called by the Java virtual machine (JVM)* before the program exits to
give the program a chance to clean up and release resources. Multi-threaded programs should
close all Files and Sockets they use before exiting so they do not face resource starvation. The
call to server.close() in the finalize() method closes the Socket connection used by each thread in
this program.
import java.awt.Color;
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
implements ActionListener {
JButton button;
JPanel panel;
JTextField textField;
BufferedReader in = null;
button.addActionListener(this);
panel.setLayout(new BorderLayout());
panel.setBackground(Color.white);
getContentPane().add(panel);
panel.add("North", text);
panel.add("Center", textField);
panel.add("South", button);
} //End Constructor
if(source == button){
out.println(text);
textField.setText(new String(""));
try{
System.out.println("Read failed");
System.exit(1);
try{
} catch (UnknownHostException e) {
System.exit(1);
} catch (IOException e) {
System.out.println("No I/O");
System.exit(1);
frame.setTitle("Client Program");
System.exit(0);
};
frame.addWindowListener(l);
frame.pack();
frame.setVisible(true);
frame.listenSocket();
The client program presents a simple user interface and prompts for text input. When you click
the Click Me button, the text is sent to the server program. The client program expects an echo
from the server and prints the echo it receives on its standard output.
The client program establishes a connection to the server program on a particular host and port
number in its listenSocket method, and sends the data entered by the end user to the server
program in its actionPerformed method. The actionPerformed method also receives the data back
from the server and prints it to the command line.
listenSocket Method
The listenSocket method first creates a Socket object with the computer name (ex: VEER-PC)
and port number (4321) where the server program is listening for client connection requests.
Next, it creates a PrintWriter object to send data over the socket connection to the server
program. It also creates a BufferedReader object to read the text sent by the server back to the
client.
actionPerformed Method
The actionPerformed method is called by the Java platform for action events such as button
clicks. This actionPerformed method code gets the text in the Textfield object and passes it to the
PrintWriter object, which then sends it over the socket connection to the server program.
The actionPerformed method then makes the Textfield object blank so it is ready for more end
user input. Lastly, it receives the text sent back to it by the server and prints the text out.
if(source == button){
//Send data over socket
String text = textField.getText();
out.println(text);
textField.setText(new String(""));
out.println(text);
}
//Receive text from server
try{
String line = in.readLine();
System.out.println("Text received: " + line);
} catch (IOException e){
System.out.println("Read failed");
System.exit(1);
}
}
Next You can open your desired number of command Windows for clients.
Fig:Client3 Fig:Client1
Fig:Client2
Good idea when constructing a server application in a classic client/server architecture (when
multiple client connections towards a single server are needed) is to implement one-thread-per-
connection technique, where every inbound connection is being delegated to a thread that will
take care of every aspect of that connection independently from all other connections. Not only
that entire processing is being encapsulated inside that thread, but also normal processing of the
main serverâs thread is being enabled because it can (after you delegate the connection to a
independent thread) continue waiting for the next inbound connection, and thus not lose any
time.
Programmer should think, though, about an efficient number of active thread at one time “ if the
server encounters heavy traffic it should stop enabling connections (maybe it as better to deny a
service than to give a bad service which may fail at any time).
One more thing programmer should be aware of is the logging process. It is almost impossible to
imagine any kind of serious distributed programming without using some logger. Numeroud
loggers are available in the market, in Java a wide freeware selection is present (Avalon,
JDK>=1.4 has integrated logging), but a definite industry standard for years already is the
Apache log4j logger because of its ease of use and wide specter of implemented abilities.
Loggers are used primarily because debugging does not help when dealing with distributed
applications and also because it allows software specialists to see in details how application
worked for example a day or two before when some error occurred. Often program use logging
even after development “ when they are put on production servers.
Finally, we should also say a couple of words concerning thread pools. Thread pools are
extremely helpful because they help you to work with a number of threads without any risk of
having a host thread• (it as a thread that is out of control), and also they help you to control all
threads active in the program at every moment “ new threads can be added to the pool and
removed when they are not useful any more, schedule tasks can be added also (Java TimerTask
is not a good solution) and a lot of other things. Since Java 5.0 a very powerful mechanism called
Executor framework is integral part of standard Java “ it is a very flexible collection of classes
and powerful enough for most of real-life situations.
Object serialization
One more thing deeply integrated into Java is serialization. Every object which implements
interface java.io.Serializable is said to be exactly that “ serializable. It means that that object can
be represented like a stream of bytes which can completely describe it. This interface serves just
as a sign to the Java compiler “ it does not have any methods in it.
Why is the serialization a good thing? Because it allows complete object representation (not only
description, but also values of data inside the object) as a unique series of bytes and it allows, at
the same time, to reinterpret original object using that serialized byte data.
Basically, because a specific kind of streams can be used to hold serialized objects data, you may
save a serialized object into a file, and also (which is much more interesting for us, network
programmers) send that stream of bytes to another computer, using TCP for example, so a
program that accepts data can make a reverse action on data stream and create an object which
will afterwards be in the same state as it was on the source side of the connection. But, keep in
mind that the other side (acceptors side) must have a definition of the object so it can have
information how to reinterpret the object byte stream (basically, if you wish to send instantiated
MyClass object you need the same MyObject.class file on both side of the connection). One
more thing which that should be kept in mind all the time is that serialization is a Java specific
thing (non-portable) which is very dependable on JDK version (the same Java object may have
completely different object stream signature in JDK 1.4 and JDK 6.0).
Object is serialized from memory into a byte stream using ObjectOutputStream class, and object
of type ObjectInputStream is used to reinterpret object from a byte data stream. When these
object streams are lined to the socket’s underlying data streams you will be able to “send
objects†through the network – which is, you must agree, a very powerful programming
technique (RMI uses serialization as a transport mechanism).
}
catch(IOException e) {
...
}
finally {
...
}
And a simple on-thread server which can receive and reinterpret sent object is:
doSomethingWithTheObject(myObject);
}
catch(Exception e) {
...
}
finally {
...
}
Conclusion
In this paper introduction to full spectrum of techniques in java networking are explained. We
have seen techniques for programming clients and servers using both TCP and UDP services. If
you have previous experience of network programming, you will probably agree that java makes
network programming much easier than do most other languages. Thus, one of Java's great
strengths is painless networking. As much as possible, the underlying details of networking have
been abstracted away.
EXTRA INFO:
Multicasting Through Java
Introduction
Most high-level network protocols only provide a unicast transmission service. That is, nodes of
the network only have the ability to send to one other node at a time. All transmission with a
unicast service is inherently point-to-point. If a node wants to send the same information to many
destinations using a unicast transport service, it must perform a replicated unicast, and send N
copies of the data to each destination in turn.
A better way to transmit data from one source to many destinations is to provide a multicast
transport service. With a multicast transport service, a single node can send data to many
destinations by making just a single call on the transport service:
For those applications which involve a single node sending to many recipients, a multicast
facility is clearly a more natural programming paradigm than unicast. When a multicast service
is implemented over such a network, there is a huge improvement in performance. If the
hardware supports multicast, A packet which is destined for N recipients can be sent as just a
single packet!
Multicast Groups
There are three types of IPv4 addresses: unicast, broadcast, and multicast.
Unicast addresses are used for transmitting a message to a single destination node.
Broadcast addresses are used when a message is supposed to be transmitted to all nodes in a
subnetwork.
For delivering a message to a group of destination nodes which are not necessarily in the same
subnetwork,multicast addresses are used.
Class A, B, and C IP addresses are used for unicast messages, whereas as class D IP address,
those in the range 224.0.0.1 to 239.255.255.255, inclusive, and by a standard UDP port number
are used for multicast messages.
Bit no. 0 1 2 3 4 5 6 7 8 16 24 31
Class D addresses are identified by a one in bit 0,1 and 2 and a zero in bit 3 of the address. This
means that 6.25% of all available IP addresses are of this class.
The range of Class D addresses are in dotted decimal notation from 224.h.h.h.h to 239.h.h.h,
where h is a number from 0 to 255. Address 224.0.0.0 is reserved and can not be used, while
address 224.0.0.1 is used to address all hosts that take part in IP multicasting.
Class D addresses are used for multicasting and does not have a network part and hosts part. IP
multicasting makes it possible to send IP datagrams to a group of hosts, which may be spread
across many networks.
Broadcast packets need to have a finite life inorder to avoid bouncing of the packets around the
network forever. Each packet has a time to live (TTL) value, a counter that is decremented every
time the packet passes through an hop i.e a router between the network. Because of TTLs, each
multicast packet is a ticking time bomb.
Take for example, a TV station where TTLs would be the station's signal area -- the limitation of
how far the information can travel. As the packet moved around the company's internal network,
its TTL would be notched down every time it passed through an router. When the packet's TTL
reached 0, the packet would die and not be passed further. Generally multicast with long TTLs --
perhaps 200 - to guarantee that the information will reach around the world
Java's Support
Java makes the programmer easier by implementing classes in java.net package that facilitates
our need i.e multicasting. java.net includes a class called MulticastSocket. This kind of socket is
used on the client-side to listen for packets that the server broadcasts to multiple clients. The
multicast datagram socket class is useful for sending and receiving IP multicast packets. Thus,
java.net.MulticastSocket. and java.net.DatagramPacket together used to implement multicasting
in java and makes programming easier.
Methods:Methods other than the joinGroup(addr) and leaveGroup(addr), this class also provides
functions, that set and gets the time-to-live for multicast packets sent out on the socket. The TTL
sets the IP time-to-live for DatagramPackets sent to a MulticastGroup, which specifies how
many "hops" that the packet will be forwarded on the network before it expires. They are
setTTl(ttl) and getTTl(ttl). The parameter 'ttl' is an unsigned 8-bit quantity.
The Following source code is an simple example for broadcasting. It broadcast date and time to
its multiple clients.
Server Program
import java.net.*;
import java.io.*;
import java.util.*;
public class BroadcastServer
{
Client program
import java.net.*;
import java.io.*;
MulticastSocket socket;
DatagramPacket packet;
InetAddress address;
address = InetAddress.getByName(args[0]);
socket = new MulticastSocket(BroadcastServer.PORT);
socket.joinGroup(address);
byte[] data = null;
packet = new DatagramPacket(data,data.length);
for(;;)
{
// receive the packets
socket.receive(packet);
String str = new String(packet.getData());
System.out.println(" Time signal received from"+
packet.getAddress() + " Time is : " +str);
} // for
} // main
} // class Broadcast
First you will need to ensure that a name is associated with a suitable multi-cast address. This
requires access to - and understanding of your system's configuration. Add a suitable name, such
as BroadTest and assign it the address between 224.0.0.1 to 239.255.255.255.
You will see a message "Sending " appear at one-second intervals. This suggests that a server is
running.
You should now see the date and time printed at regular intervals on the client machine
Advantages of Multicasting
In many cases the multicasting capability is desirable because of some following advantages.
The first major advantage of using multicasting is the decrease of the network load. There are
many applications like stock ticker applications which are required to transmit packets to
hundreds of stations. The packets sent to these stations share a group of links on their paths to
their destinations. Since multicasting requires the transmission of only a single packet by the
source and replicates this packet only if it is necessary multicast transmission can conserve the so
much needed network bandwidth.
Another place where multicasting can be very helpful is in resource discovery. There are many
applications in which a host needs to find out whether a certain type of service is available or
not. Using multicast messages and sending the query to those hosts which are potentially capable
of providing this service would be of great help. Although some applications use multicast
messages to transmit a packet to a group of hosts residing on the same network, there is no
reason to impose this limitation. The scope of multicast packets can be limited by using the time-
to-live (TTL) field of these packets.
Another important feature of multicasting is its support for datacasting applications. In recent
years, multimedia transmission has become more and more popular. The audio and video signals
are captured, compresses and transmitted to a group of receiving stations. Instead of using a set
of point-to-point connections between the participating nodes, multicasting can be used for
distribution of the multimedia data to the receivers. In real world stations may join or leave an
audio-cast or a video-cast at any time.
Today, the MBONE is a critical piece of the technology that's needed to make multiple person
data voice, and video conferencing on the Internet -- in fact, sharing any digital information --
cheap and convenient. Unfortunately, the majority of the routers on the Internet today don't know
how to handle multicasting. Most routers are set up to move traditional Internet Protocol (IP)
unicast packets -- information that has a single, specific destination. Most routers today are
unicast routers: They are designed to move information from a specific place to another
specific place. However, routers that include multicasting capabilities are becoming more
common.
So in order to facilitate multicasting MBONE network was created. It's a "virtual network" - a
network that runs on top of the Internet and it allows multicast packets to traverse the Net. The
MBONE is called a virtual network because it shares the same physical media -- wires, routers
and other equipment -- as the Internet.
The MBONE allows multicast packets to travel through routers that are set up to handle only
unicast traffic. Software that utilizes the MBONE hides the multicast packets in traditional
unicast packets so that unicast routers can handle the information.The scheme of moving
multicast packets by putting them in regular unicast packets is called tunneling. In the future,
most commercial routers will support multicasting, eliminating the headaches of tunneling
information through unicast routers.
Machines (workstations or routers) that are equipped to support multicast IP are called mrouters
(multicast routers). Mrouters are either commercial routers that can handle multicasting or (more
commonly) dedicated workstations running special software that works in conjunction with
standard routers. Multicasting is a network routing facility -- a method of sending packets to
more than one site at a time. The MBONE is a loose confederation of sites that currently
implement IP multicasting.
MBONE Advantages
In the future, the MBONE may make it possible for you to do the following:
Conclusion
In this paper, we first reviewed why and for what applications multicasting is important. Then,
the essential concept of group membership was discussed. Here a sample program in java for
broadcasting shows the easiness to implement such a complex muticasting. Thus java with it's
MulticastSocket class and methods provides the easier way to implement the multicasting by
abstracting the underlying details of networking. It also introduces the concept of MBONE and
its advantages.