Thursday 13 September 2012

Networking with Java


There are several communications mechanisms that we can use to provide network services. We could use UDP (unreliable datagram protocol), or TCP (transfer-control protocol). For the purposes of this tutorial, we'll choose TCP, because it makes life much easier. TCP guarantees that messages will arrive at their destination. UDP is unreliable, and your application isn't notified if the message is lost in transit. Also, many protocols (such as HTTP, SMTP, POP & FTP) use TCP, so it's important that you are familiar with it for networking in Java.

Internet Addressing with Java

Handling internet addresses (domain names, and IP addresses) is made easy with Java. Internet addresses are represented in Java by the InetAddress class. InetAddress provides simple methods to convert between domain names, and numbered addresses.
We start by importing the java.net package, which contains a set of pre-written networking routines (including InetAddress).
import java.net.*;
Next, we declare a new variable of type InetAddress, which we assign the value of the local host machine (for machines not connected to a network, this should represent 127.0.0.1). Due to the fact that InetAddresses can generate exceptions, we must place this code between a try .. catch UnknownHostException block.
// Obtain the InetAddress of the computer on which this program is running
InetAddress localaddr = InetAddress.getLocalHost();
The InetAddress class has methods that return the IP address as an array of bytes (which can be easily converted into a string), as well as a string representation of its domain name (e.g. mydomain.org ). We can print out the InternetAddress, as well as the domain name of the local address.
System.out.println ("Local IP Address : " + localaddr );
System.out.println ("Local hostname : " + localaddr.getHostName());