• Skip to main content
  • Skip to primary sidebar

CodeBlogMoney

Make Money using Coding and Blogging

You are here: Home / Java / Java get Hostname

Java get Hostname

June 8, 2020 by Jimmy

Java get Hostname

This blog helps you to get the hostname and IP address of where the program is running. It uses the InetAddress class of Java which uses the Internet Protocol address.

While development and testing most developer uses own computer or laptop to run the program. so the program will provide the hostname of the system where this code is executed.

This code uses java.net library of java to get the Hostname.

Here is the code which get hostname using Java.

package com.cbm.hostnamejava;

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

public class JavaGetHostName {
	
public static void main(String[] args) throws UnknownHostException{
		 
       InetAddress inetAddress = InetAddress.getLocalHost();
  
       String hostname = inetAddress.getHostName();
          
       System.out.println("Hostname of current host: " + hostname);
            
       System.out.println("IP address of current host: " + inetAddress);
 
    }

}

Output:

Hostname of current host: DESKTOP-TTSBKDU
IP address of current host: DESKTOP-TTSBKDU/192.168.0.110

InetAddress getLocalHost()

getLocalHost() of InetAddress return the local host It get the name from the system and assigned to InetAddress.

This method throws UnknownHostException incase if system is not able to retrieve the hostname or not able to associate with IP address.

Code with Exception Handling

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

public class JavaGetHostName {

	public static void main(String[] args) {

		try {

			InetAddress inetAddress = InetAddress.getLocalHost();

			String hostname = inetAddress.getHostName();

			System.out.println("Hostname of current host: " + hostname);

			System.out.println("IP address of current host: " + inetAddress);
			
		} catch (UnknownHostException exception) {

			System.out.println("Exception:->" + exception.getMessage());
		}

	}

}

More article to read:

String to Char Array Java

Useful tool to https://codebeautify.org/hostname-to-ip

Filed Under: Java

Primary Sidebar

Categories

  • Blogging
  • HTML
  • Java
  • JavaScript
  • jQuery
  • JSON
  • MySql
  • Performance
  • PHP
  • Problem Solving
  • Python
  • Testing
  • XML

Copyright © 2021 · Metro Pro on Genesis Framework · WordPress · Log in