How to Get Server IP Address in Java


In this example, we will use the static method getLocalHost() in the InetAddress class to get the current host address.

Source Code

package com.beginner.examples;

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

public class GetMyMachineIp {

	public static void main(String[] args) {
		
		try {
			//Get the current host address
			InetAddress myId = InetAddress.getLocalHost();
			
			System.out.println(myId.getHostAddress());
			
		} catch (UnknownHostException e) {
			
			e.printStackTrace();
		}
		

	}

}

Output:

192.168.1.9

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments