简单的方法
InetAddress addr = InetAddress.getLocalHost(); ip=addr.getHostAddress().toString;//获得本机IP address=addr.getHostName()toString;//获得本机名称
但是这个方法有局限性,在Linux下获取的地址一直为/etc/hosts文件中与本机hostname绑定的那个地址(ubuntu 9.04下默认是127.0.1.1)。
另一种方法是通过直接获取操作系统网络接口的方式来获得ip地址,代码如下:
Enumeration allNetInterfaces = null; try { allNetInterfaces = NetworkInterface.getNetworkInterfaces(); } catch (java.net.SocketException e) { e.printStackTrace(); } InetAddress ip = null; while (allNetInterfaces.hasMoreElements()) { NetworkInterface netInterface = (NetworkInterface) allNetInterfaces .nextElement(); System.out.println(netInterface.getName()); Enumeration addresses = netInterface.getInetAddresses(); while (addresses.hasMoreElements()) { ip = (InetAddress) addresses.nextElement(); if (ip != null && ip instanceof Inet4Address) { System.out.println("/u672c/u673a/u7684IP = " + ip.getHostAddress()); } } }
【windows xp, ubuntu 9.04下测试通过】