获取Linux和Window本机服务器IP的方法

1,获取linux服务器本机IP

package com.test;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * 得到本机ip地址
 * @author WangSl
 */
public class NetUtil {

	/**
	 * 得到本机地址,非127.0.0.1这样的
	 */
	private static String firstIPWithoutLocalhost = null;

	/**
	 * 得到所有本机地址
	 * 
	 * @return List<InetAddress>
	 */
	public static List<InetAddress> getAllHostAddress() {
		try {
			Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
			List<InetAddress> addresses = new ArrayList<InetAddress>();

			while (networkInterfaces.hasMoreElements()) {
				NetworkInterface networkInterface = networkInterfaces.nextElement();
				Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
				while (inetAddresses.hasMoreElements()) {
					InetAddress inetAddress = inetAddresses.nextElement();
					addresses.add(inetAddress);
				}
			}
			return addresses;
		} catch (SocketException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	/**
	 * 得到第一个非127.0.0.1的,实际的ip地址
	 * @return String ip地址
	 */
	public static String getFirstIPWithoutLocalhost() {
		if (firstIPWithoutLocalhost == null) {
			List<InetAddress> colInetAddress = getAllHostAddress();
			for (InetAddress address : colInetAddress) {
				if (!address.isLoopbackAddress()&& address.getAddress().length == 4) {
					firstIPWithoutLocalhost = address.getHostAddress();
					break;
				}
			}
		}
		return firstIPWithoutLocalhost;

	}

	public static void main(String[] args) {
		System.out.println(NetUtil.getFirstIPWithoutLocalhost());
	}
}


2,获取Windows服务器本机IP

package com.test;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class InetAddressObtainment_Windows {
	String hostname;
	String hostaddress;

	void initialize() {
		try {
			InetAddress ia = InetAddress.getLocalHost(); // 获得本机网络地址对象
			hostname = ia.getHostName(); // 获得对应主机名
			hostaddress = ia.getHostAddress(); // 获得对应主机地址
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		InetAddressObtainment_Windows o1 = new InetAddressObtainment_Windows();
		System.out.println(o1.hostname);
		System.out.println(o1.hostaddress);
		o1.initialize();
		System.out.println(o1.hostname);
		System.out.println(o1.hostaddress);
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值