Add

Java Language - Host Specific IP Address

 

Solution

Following example shows how to change the host name to its specific IP address with the help of InetAddress.getByName() method of net.InetAddress class.

import java.net.InetAddress;

import java.net.UnknownHostException;

public class GetIP {

   public static void main(String[] args) {

      InetAddress address = null;

      try {

         address = InetAddress.getByName("www.learnkro.com");

      } catch (UnknownHostException e) {

         System.exit(2);

      }

      System.out.println(address.getHostName() + "=" + address.getHostAddress());

      System.exit(0);

   }

}

Result

http://www.learnkro.com = 123.14.2.35

The following is an another example of getHostAddress() and getHostName() in Java.

import java.net.InetAddress;

import java.net.UnknownHostException;

public class Demo {

   public static void main(String[] args) {

      InetAddress ipadd;

      String hostname;

      try {

         ipadd = InetAddress.getLocalHost();

         hostname = ipadd.getHostName();

         System.out.println("Your IP address : " + ipadd);

         System.out.println("Your Hostname : " + hostname);

      } catch (UnknownHostException e) {

      }

   }

}

 Result.

Your IP address : 4d623edc62d4/172.17.0.2

Your Hostname : 4d623edc62d4

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.