Code:
import java.net.InetAddress; import java.net.UnknownHostException; /** * 获取本机的真实IP地址。<br> * 注意:在Linux下,必须修改主机名(不能使用默认的localhost作为主机名,否则获取到的是127.0.0.1),然后在/etc/hosts下将新主机名绑定为本机IP,方可获得。<br> * 以下两个方法都可以。 * * @author nathan.yuhm */ public class Cluster { private static String getHostIp() { String localhost = ""; try { InetAddress localHost2 = InetAddress.getLocalHost(); System.out.println("InetAddress.getLocalHost()=" + localHost2); localhost = localHost2.getHostAddress(); } catch (Exception e) { e.printStackTrace(); } return localhost; } private static String getHostIp2() { try { String hostName = InetAddress.getLocalHost().getHostName(); System.out.println("InetAddress.getLocalHost().getHostName()=" + hostName); InetAddress byName = InetAddress.getByName(hostName); System.out.println("InetAddress.getByName(hostName)=" + byName); return byName.getHostAddress(); } catch (UnknownHostException e) { e.printStackTrace(); } return null; } public static void main(String[] args) { System.out.println(getHostIp()); System.out.println(getHostIp2()); } }
output:
InetAddress.getLocalHost()=hy-yhm/10.249.196.28 10.249.196.28 InetAddress.getLocalHost().getHostName()=hy-yhm InetAddress.getByName(hostName)=hy-yhm/10.249.196.28 10.249.196.28
reference:
http://www.cnblogs.com/lidp/archive/2010/02/03/1696471.html
http://blog.sina.com.cn/s/blog_5a08b1780100ceqc.html