How to Get Host Name from the InetAddress in Java


In this example we will show how to get the name of the host from the InetAddress.

Source Code

package com.beginner.examples;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class GetHostNameByInetAddress {

	public static void main(String[] args) {
		
		try {

			//Get the InetAddress of the current host
			InetAddress address = InetAddress.getLocalHost();
			
			//Gets and host name from the InetAddress object
			
			String hostName = address.getHostName();
			
			System.out.println(hostName);
			
			
		} catch (UnknownHostException e) {
			
			e.printStackTrace();
		}

	}

}

Output:

SC-201812101404

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments