手机版 收藏 导航

Java获取本机hostname的方法_Java获取外网IP地址的方法

原创   www.link114.cn   2024-03-17 17:59:01

Java获取本机hostname的方法_Java获取外网IP地址的方法

在Java中获取本机hostname的方法有以下几种:

  1. 使用InetAddress.getLocalHost().getHostName()方法:
  2. InetAddress localHost = InetAddress.getLocalHost();
    String hostname = localHost.getHostName();
  3. 使用System.getenv("COMPUTERNAME")方法:
  4. String hostname = System.getenv("COMPUTERNAME");
  5. 使用System.getProperty("user.name")方法:
  6. String hostname = System.getProperty("user.name");

在Java中获取外网IP地址的方法有以下几种:

  1. 使用InetAddress.getLocalHost().getHostAddress()方法:
  2. InetAddress localHost = InetAddress.getLocalHost();
    String ip = localHost.getHostAddress();
  3. 使用第三方API获取:
  4. String url = "http://api.ipify.org";
    BufferedReader in = new BufferedReader(new InputStreamReader(new URL(url).openStream()));
    String ip = in.readLine();
  5. 使用HttpURLConnection访问外部IP查询服务:
  6. URL url = new URL("http://ip.42.pl/raw");
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    String ip = new BufferedReader(new InputStreamReader(con.getInputStream())).readLine();