Java获取本机IP地址

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

public class Test {
    public static void main(String[] args) {
        try{
            InetAddress localHost = InetAddress.getLocalHost();
            System.out.println("主机名:"+localHost.getHostName());
            System.out.println("本地ip地址:"+localHost.getHostAddress());
        }
        catch(UnknownHostException e)
        {
            e.printStackTrace();
        }
    }
}

注意:

  • InetAddress.getLocalHost():必须要通过try的方式使用

你可能感兴趣的:(Java,java,tcp/ip)