You are on page 1of 49

METHODS IN JAVA

 Looking Up Internet Addresses:


 The InetAddress Class,
 Inet4Address and Inet6Address,
 The Network Interface Class,
 URLs: The URL class,
 URL encoder and URL decoder Classes,
 Proxies,
 Communicating with Server Side through GET.

Network Programming 1
Internet Address
Devices connected to the Internet are called nodes.
Nodes that are computers are called hosts.
Each node or host is identified by at least one unique
number called an Internet address .
IPv4 addresses are 4-byte-long
IPv6 addresses are 16-byte-long.
An IPv4 address is written as four unsigned bytes, each
ranging from 0 to 255, with the most significant byte first.
An IPv6 address is normally written as eight blocks of four
hexadecimal digits separated by colons.

Network Programming 2
Internet Address
Every computer connected to the Internet should have
access to a machine called a domain name server.
Most domain name servers only know the addresses of
the hosts on their local network, plus the addresses of a
few domain name servers at other sites.
If a client asks for the address of a machine outside the
local domain, the local domain name server asks a
domain name server at the remote location and relays the
answer to the requester.

Network Programming 3
InetAddress Class
InetAddress Class

The java.net.InetAddress class is Java’s high-


level representation of an IP address, both IPv4
and IPv6.
Other networking classes, including Socket,
ServerSocket, URL, DatagramSocket,
DatagramPacket. Usually, it includes both a
hostname and an IP address.

Network Programming 5
InetAddress Class
• Represents IP address of a node

• No public constructor

• Consists of 4 category of methods:


1. Object creation methods
2. Getter methods
3. Address type identification methods
4. Object methods
1. OBJECT CREATION
METHODS
• Returns the initialized InetAddress object

• Methods include:
getByName
getAllByName
getLocalHost
getByAddress
getByName
• Returns InetAddress object for the host whose
hostname is specified in the argument

• Argument could either be hostname or IP


address

public static InetAddress getByName(String


hostName) throws UnknownHostException
getByName - hostname
• Lookup DNS

If (host found) then

return object

Else

throw UnknownHostException
getByName - hostname
EXAMPLE:
import java.net.*;
public class OReillyByName{
public static void main (String[] args){
try {
InetAddress addr=InetAddress.getByName("www.oreilly.com");
System.out.println(addr);
}
catch (UnknownHostException ex) {
System.out.println("Could not find www.oreilly.com");
}
}
}
OUTPUT:
www.oreilly.com/208.201.239.36
getByName – IP address
• Doesn’t lookup DNS
• Lookup DNS only if implicitly(toString) /
explicitly(getHostName) specified to.
• If (host found) then
Return object
• Else
hostname = ipaddress
Throw no exception
getByName – IP address
EXAMPLE
import java.net.*;
public class OReillyByAddress{
public static void main (String[] args) {
try {
InetAddress address =
InetAddress.getByName("208.201.239.37");
System.out.println(address);
}
catch (UnknownHostException ex) {
System.out.println("Could not find 208.201.239.37");
}
}
}
OUTPUT
www.oreilly.com/208.201.239.37
getAllByName
• Returns all IP address for the given hostname
• If (host found)
Return object containing all IP address
• Else
Throw UnKnownHostException

public static InetAddress[] getAllByName(String


hostName) throws UnknownHostException
getAllByName
EXAMPLE
import java.net.*;
public class AllAddressesOfMicrosoft {
public static void main (String[] args) {
try {
InetAddress[] addresses =
InetAddress.getAllByName("www.microsoft.com");
for (int i = 0; i < addresses.length; i++) {
System.out.println(addresses[i]);
}
}
catch (UnknownHostException ex) {
System.out.println("Could not find www.microsoft.com");
}
}
}
getAllByName
RESULT
www.microsoft.com/63.211.66.123
www.microsoft.com/63.211.66.124
www.microsoft.com/63.211.66.131
www.microsoft.com/63.211.66.117
www.microsoft.com/63.211.66.116
www.microsoft.com/63.211.66.107
www.microsoft.com/63.211.66.118
www.microsoft.com/63.211.66.115
www.microsoft.com/63.211.66.110
getLocalHost
• Returns InetAddress object for the local
machine

public static InetAddress getLocalHost()


throws UnknownHostException
getLocalHost
EXAMPLE
import java.net.*;
public class MyAddress {
public static void main (String[] args) {
try {
InetAddress address = InetAddress.getLocalHost();
System.out.println(address);
}
catch (UnknownHostException ex) {
System.out.println("Could not find this computer's address.");
}
}
}
OUTPUT
titan.oit.unc.edu/152.2.22.1
getByAddress
• DNS lookup is not performed
• If (not IPv4 or IPv6) then UnknownHostException
• Can be used if DNS in not available
• Faster – NO string to byte conversion
• Could retrieve conflicted InetAddress object
(unavailable IP address)

public static InetAddress getByAddress(byte[] address) throws


UnknownHostException

public static InetAddress getByAddress(String hostName, byte[]


address) throws UnknownHostException
getByAddress
Java InetAddress .getByAddress (byte[] addr)
Syntax
public static InetAddress getByAddress(byte[] addr) throws
UnknownHostException
import java.net.InetAddress;
public class Main { public static void main(String[] argv) throws
Exception {
byte[] ipAddr = new byte[] { 127, 0, 0, 1 };
InetAddress addr = InetAddress.getByAddress(ipAddr);
String hostnameCanonical = addr.getCanonicalHostName();
}
}
getByAddress
Java InetAddress .getByAddress (String host, byte[] addr)
SYNTAX
public static InetAddress getByAddress(String host, byte[] addr)
throws UnknownHostException
public class Main {
public static void main(String[] argv) throws Exception {
byte[] ipAddr = new byte[] { 127, 0, 0, 1 };
InetAddress addr = InetAddress.getByAddress("Localhost",ipAddr);
System.out.println(Arrays.toString(addr.getAddress()));
}
}
getByName / getAllByName /
getLocalHost
• Lookup DNS

• Cache the result of lookups

• System properties
Networkaddress.cache.ttl
No. of seconds, a successful DNS result will be in cache
Networkaddress.cache.negative.ttl
No. of seconds, a unsuccessful DNS result will be in cache
Security
1. Untrusted code cannot lookup for arbitrary 3 rd
party host. Can only lookup for:
Codebase
Localhost
Only 127.0.0.1 (not actual hostname & IP address)
2. Test whether a host can be resolved
public void checkConnect(String hostname, int
port)
Port = (-1 / positive integer)
2. GETTER METHODS
• InetAddress class -> 3 methods
• Return hostname as string & IP address as
both string and byte array.
• Retrieve information from InetAddressObject
• Getter methods
A)getHostName
B) getAddress
C) getHostAddress
A) getHostName

• If (host_name available)
Return (String)host_name
• Else
Return (String)(host_name = IP address)

InetAddress machine = InetAddress.getLocalHost();


String localhost = machine.getHostName();
getHostName
EXAMPLE given the address find the host name
import java.net.*;
public class ReverseTest {
public static void main (String[] args) {
try {
InetAddress ia = InetAddress.getByName("208.201.239.37");
System.out.println(ia.getHostName());
}
catch (Exception ex) {
System.err.println(ex);
}
}
}
RESULT
www.oreillynet.com
getHostAddress
• Return IP address of InetAddress object as String
EXAMPLE
import java.net.*;
public class MyAddress {
public static void main(String[] args) {
try {
InetAddress me = InetAddress.getLocalHost();
String dottedQuad = me.getHostAddress();
System.out.println("My address is " + dottedQuad);
}
catch (UnknownHostException ex) {
System.out.println("I'm sorry. I don't know my own address.");
}
}
}
RESULT
My address is 152.2.22.14
B)getAddress
• Return IP addr of InetAddress object as Byte array
EXAMPLE
import java.net.*;
import java.util.*;
import java.lang.*;
public class ver
{
public static void main(String args[]) throws UnknownHostException
{
InetAddress Address=InetAddress.getLocalHost();
System.out.println(Address.getHostAddress());
if(Address instanceof InetAddress)
System.out.println(".............IPV4 Address");
else
System.out.println(".............IPV6 Address");
}
}
RESULT
IP : 152.2.22.14 O/P: IPV4 Address
3. ADDRESS TYPE
• public boolean isAnyLocalAddress()

Return TRUE if InetAddressObject belongs to


local host

• public boolean isLoopbackAddress()

Return TRUE if it is loopback address


Contd..
• public boolean isLinkLocalAddress()
IP address that is intended only for
communications within the segment of a local
network
Return TRUE if InetAddressObject belongs to
above category
• public boolean isSiteLocalAddress()
IP address that is intended only for
communications within a site of a local network
Return TRUE if InetAddressObject belongs to
above category
Contd..
• public boolean isMulticastAddress()

Return TRUE if InetAddressObject belongs to


multicast address

• public boolean isMCGlobal()

Return TRUE if InetAddressObject belongs to global


multicast address
Contd..
• public boolean isMCNodeLocal()

Return TRUE if InetAddressObject belongs to


interface-local multicast address

• public boolean isMCLinkLocal()

Return TRUE if InetAddressObject belongs to link-


local multicast address
Contd..
• public boolean isMCSiteLocal()

Return TRUE if InetAddressObject belongs to


site-wide multicast address

• public boolean isMCOrgLocal()

Return TRUE if InetAddressObject belongs to


organization-wide multicast address
LINK
isReachable
• Test whether that address is reachable.
• Echo port
 public boolean isReachable(int timeout) throws
IOException
 If (host responds within timeout) return TRUE
 Else return FALSE + IOException
 public boolean isReachable(NetworkInterface
interface, int ttl, int timeout)throws IOException
4.OBJECT METHODS
• 3 METHODS

a. equals

b. Hashcode

c. toString
equals
• If ((InetAddress Object) && (IP addr are
equal))

Return TRUE

• Else

Return FALSE
import java.net.*;
public class IBiblioAliases {
equals
public static void main (String args[]) {
try {
InetAddress ibiblio = InetAddress.getByName("www.ibiblio.org");
InetAddress helios =
InetAddress.getByName("helios.metalab.unc.edu");
if (ibiblio.equals(helios)) {
System.out.println("www.ibiblio.org is the same as
helios.metalab.unc.edu");
}
else {
System.out.println("www.ibiblio.org is not the same as
helios.metalab.unc.edu");
}
}
catch (UnknownHostException ex) {
System.out.println("Host lookup failed.");
}}}
RESULT www.ibiblio.org is the same as helios.metalab.unc.edu
hashCode
• Returns hash value of the object

• Used for indexing

• 2 hostname, 1 ip address => same hash code


toString
• Returns short text representation of the object

• EXAMPLE
InetAddress thisComputer = InetAddress.getLocalHost();
String address = thisComputer.toString();

• RESULT
hostname/dotted quad address
THE NETWORKINTERFACE
CLASS
NetworkInterface Class
• Represents the network interface

• Methods include:
1. Factory

2. Getter

3. Object
1. FACTORY METHODS
• Used for creating & initializing the objects

• 3 methods
getByName

getByInetAddress

getNetworkInterfaces
getByName
• Retrieves NetworkInterface object based on
interface name
try {
NetworkInterface ni = NetworkInterface.getByName("eth0");
if (ni == null) {
System.err.println("No such interface: eth0" );
}
}
catch (SocketException ex) {
System.err.println("Could not list sockets." );
}
getByInetAddress
• Retrieves NetworkInterface object based on IP address
try {
InetAddress local = InetAddress.getByName("127.0.0.1");
NetworkInterface ni = NetworkInterface.getByInetAddress(local);
if (ni == null) {
System.err.println("That's weird. No local loopback address.");
}
}
catch (SocketException ex) {
System.err.println("Could not list sockets." );
}
catch (UnknownHostException ex) {
System.err.println("That's weird. No local loopback address.");
}
getNetworkInterfaces
• Retrieves NetworkInterface object for all interfaces
import java.net.*;
import java.util.*;
public class InterfaceLister {
public static void main(String[] args) throws Exception {
Enumeration interfaces = NetworkInterface.getNetworkInterfaces( );
while (interfaces.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) interfaces.nextElement( );
System.out.println(ni);
}
}
}
getNetworkInterfaces
OUTPUT

name:eth1 (eth1) index: 3 addresses:


/192.168.210.122;

name:eth0 (eth0) index: 2 addresses:


/152.2.210.122;

name:lo (lo) index: 1 addresses:


/127.0.0.1;
2. GETTER METHODS
public Enumeration getInetAddresses( )

• Return all the associated IP address

NetworkInterface eth0 = NetworkInterrface.getByName("eth0");


Enumeration addresses = eth0.getInetAddresses();
while (addresses.hasMoreElements()) {
System.out.println(addresses.nextElement());
}
Contd..
public String getName( )

• Returns identity name of the NetworkInterface


object

public String getDisplayName( )

• Returns human friendly display name of the


NetworkInterface object
3.OBJECT METHODS
a. public boolean equals()

b. public int hashCode()

c. public String toString()

You might also like