java如何获取本机IP
java如何获取本机IP
1 import java.net.*; 2 3 public class Test6 { 4 5 public static void main(String[] args) { 6 // TODO Auto-generated method stub 7 InetAddress ia=null; 8 try { 9 ia=ia.getLocalHost(); 10 11 String localname=ia.getHostName(); 12 String localip=ia.getHostAddress(); 13 System.out.println("本机名称是:"+ localname); 14 System.out.println("本机的ip是 :"+localip); 15 } catch (Exception e) { 16 // TODO Auto-generated catch block 17 e.printStackTrace(); 18 } 19 } 20 21 }
获取所有IPv4的IP地址:
1 public static List<String> getLocalIPList() { 2 List<String> ipList = new ArrayList<String>(); 3 try { 4 Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); 5 NetworkInterface networkInterface; 6 Enumeration<InetAddress> inetAddresses; 7 InetAddress inetAddress; 8 String ip; 9 while (networkInterfaces.hasMoreElements()) { 10 networkInterface = networkInterfaces.nextElement(); 11 inetAddresses = networkInterface.getInetAddresses(); 12 while (inetAddresses.hasMoreElements()) { 13 inetAddress = inetAddresses.nextElement(); 14 if (inetAddress != null && inetAddress instanceof Inet4Address) { // IPV4 15 ip = inetAddress.getHostAddress(); 16 ipList.add(ip); 17 } 18 } 19 } 20 } catch (SocketException e) { 21 e.printStackTrace(); 22 } 23 return ipList; 24 }