Networking in Java
Networking in Java
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
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.
URL(String urlSpecifier)