java获取服务器IP地址

java获取服务器IP地址

下面展示一些 内联代码片

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

public class test {
	public static void main(String[] args) {

		System.out.println("本机IP:" + getIpAddress());

	}

	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 = (InetAddress) addresses.nextElement();

						if (ip != null && ip instanceof Inet4Address) {

							return ip.getHostAddress();

						}

					}

				}

			}

		} catch (Exception e) {

			System.err.println("IP地址获取失败" + e.toString());

		}

		return "";

	}
}

你可能感兴趣的:(java,服务器,tcp/ip)