在Java中获取本机hostname的方法有以下几种:
InetAddress.getLocalHost().getHostName()
方法:InetAddress localHost = InetAddress.getLocalHost();
String hostname = localHost.getHostName();
System.getenv("COMPUTERNAME")
方法:String hostname = System.getenv("COMPUTERNAME");
System.getProperty("user.name")
方法:String hostname = System.getProperty("user.name");
在Java中获取外网IP地址的方法有以下几种:
InetAddress.getLocalHost().getHostAddress()
方法:InetAddress localHost = InetAddress.getLocalHost();
String ip = localHost.getHostAddress();
String url = "http://api.ipify.org";
BufferedReader in = new BufferedReader(new InputStreamReader(new URL(url).openStream()));
String ip = in.readLine();
HttpURLConnection
访问外部IP查询服务:URL url = new URL("http://ip.42.pl/raw");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
String ip = new BufferedReader(new InputStreamReader(con.getInputStream())).readLine();