获取当前服务器的ip

报错的类自行去百度下载导入

import java.util.Enumeration;

import java.net.NetworkInterface;

import java.net.SocketException;

import java.net.InetAddress;

import java.net.Inet4Address;


public String getIPAddress() {

    String ip = "0.0.0.0";
    Enumeration allNetInterfaces = null;
    try {
        allNetInterfaces = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
        return ip;
    }
    InetAddress address = null;
    while (allNetInterfaces.hasMoreElements()) {
        NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
        Enumeration addresses = netInterface.getInetAddresses();
        while (addresses.hasMoreElements()) {
            address = (InetAddress) addresses.nextElement();
            if (address != null && address instanceof Inet4Address && address.getHostAddress().indexOf(".") != -1) {
                ip = address.getHostAddress();
                break;
            }
        }
    }
    return ip;
}

你可能感兴趣的:(java,web)