IP Address
In this chapter you will learn:
- Get IP address for local host
- Get Host name from InetAddress
- Getting the IP Address of a Hostname
- Get all IP addresses
- Compare two InetAddresses
IP address for local host
import java.net.InetAddress;
/*from j a v a 2 s . c o m*/
public class MainClass {
public static void main(String[] args) {
try {
InetAddress me = InetAddress.getLocalHost();
String dottedQuad = me.getHostAddress();
System.out.println("My address is " + dottedQuad);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
The code above generates the following result.
Get Host name from InetAddress
import java.net.InetAddress; import java.net.UnknownHostException; public class Main{ public static void main(String[] args) { try { InetAddress address = InetAddress.getLocalHost(); System.out.println("My name is " + address.getHostName()); } catch (UnknownHostException e) { System.out.println("I'm sorry. I don't know my own name."); } } }Getting the IP Address of a Hostname
import java.net.InetAddress;
// ja va 2 s. com
public class Main {
public static void main(String[] argv) throws Exception {
InetAddress addr = InetAddress.getByName("www.google.com");
System.out.println(addr.getHostAddress());
}
}
The code above generates the following result.
Get all IP addresses
Get all IP address for a host name.
import java.net.InetAddress;
/*from j ava 2 s . co m*/
public class Main {
public static void main(String[] args) throws Exception {
InetAddress[] addresses = InetAddress.getAllByName("www.google.com");
for (int i = 0; i < addresses.length; i++) {
System.out.println(addresses[i]);
}
}
}
The code above generates the following result.
Compare two InetAddresses
import java.net.InetAddress;
// j a v a 2 s . co m
public class MainClass {
public static void main(String args[]) throws Exception {
InetAddress ca = InetAddress.getByName("www.google.ca");
InetAddress com = InetAddress.getByName("www.google.com");
if (ca.equals(com)) {
System.out.println("same");
} else {
System.out.println("not the same");
}
}
}
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » URL URI