java获取本地ip地址

2019-11-12  本文已影响0人  0小水瓶0

使用java的InetAddress可以很简单的获取本地的ip地址

package Test;
import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.management.StringValueExp;
public class GetIP {
/**
 * 获取本地ip
 * @param args
 * @throws UnknownHostException
 */
    public static void main(String[] args) throws UnknownHostException {
        String localIPAddress = GetIP.getLocalIP();
        System.out.println(localIPAddress);
    }
    public static String getLocalIP() {
        String hostAddress=null;
        try {
            hostAddress = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            System.out.println("由于各种奇怪的原因获取不到IP");
            e.printStackTrace();
        }
        return hostAddress;
    }
}
结果
上一篇 下一篇

猜你喜欢

热点阅读