All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.gitee.yanfanvip.util.IPHelp Maven / Gradle / Ivy

The newest version!
package com.gitee.yanfanvip.util;

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

public class IPHelp {
	
	private static InetAddress address;
	
	static{
		try {
			Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces();
			while (netInterfaces.hasMoreElements()) {
				NetworkInterface network = (NetworkInterface) netInterfaces.nextElement();
				Enumeration addresss = network.getInetAddresses();
				while(addresss.hasMoreElements()){
					InetAddress address = addresss.nextElement();
					if(!address.isAnyLocalAddress() && !address.isLinkLocalAddress()
							&& !address.isLoopbackAddress() && address.isSiteLocalAddress() && 
							address.getHostAddress().indexOf(":") == -1){
						IPHelp.address = address;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(-1);
		}
	}

	/**
	 * 获取本机IP地址
	 * @return 本机IP地址
	 */
	public static String getIP() {
		return IPHelp.address.getHostAddress().toLowerCase();
	}
	
	public static InetAddress getAddress(){
		return IPHelp.address;
	}

	/**
	 * 获取本机机器名
	 * @return 本机机器名
	 */
	public static String getHostname() {
		return IPHelp.address.getHostName();
	}
	
	public static String getIPPorts(int... port){
		List buffer =  new ArrayList<>();
		for (int i : port) {
			buffer.add(getIP() + ":" + i);
		}
		return String.join(",", buffer);
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy