java获取本地ip地址(Windows和Linux通用)

package com.trs.web2frame.start;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 * 获取本地ip地址的方法(Linux环境和Java通用)
 * @version:1.0 
 * @description: 
 * @author: lxz
 * @email:
 * @date:
 */
public class Start {
    public static void main(String[] args) throws Exception {
        String localIp = getIpAddress();
        System.out.println("本地ip地址为: "+ localIp);
    }
    
    public static String getIpAddress() {
        try {
          Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
          InetAddress ip = null;
          while (allNetInterfaces.hasMoreElements()) {
            NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
            if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
              continue;
            } else {
              Enumeration addresses = netInterface.getInetAddresses();
              while (addresses.hasMoreElements()) {
                ip = addresses.nextElement();
                if (ip != null && ip instanceof Inet4Address) {
                  return ip.getHostAddress();
                }
              }
            }

          }
        } catch (Exception e) {
            System.err.println("IP地址获取失败" + e.toString());
        }
        return "";
      }    

    
}
 

你可能感兴趣的:(tools)