概述
代码:
public class logTest {
private static String localAddress;
private static String hostName;
public static void main(String[] args) throws UnknownHostException, SocketException {
// InetAddress ip = InetAddress.getLocalHost();
// String hostName = ip.getHostName();
// String hostAddress = ip.getHostAddress();
// System.out.println("ip:"+ip+"n"+"hostname:"+hostName+"n"+"hostAddress:"+hostAddress);
System.out.println("=========================");
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
ArrayList<String> ips = new ArrayList<String>();
ArrayList<String> hostnames = new ArrayList<>();
while (interfaces.hasMoreElements()) {
NetworkInterface networkInterface = interfaces.nextElement();
//获取网络接口的InetAddresses信息
Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress address = addresses.nextElement();
if (!address.isLoopbackAddress()&& !address.isLinkLocalAddress() && address instanceof Inet4Address) {
//获取ip地址字符串
ips.add(address.getHostAddress());
hostnames.add(address.getHostName());
}
}
}
System.out.println("ips:"+ips+"n hostnames:"+hostnames);
if (!ips.isEmpty()) {
for (String ip : ips) {
if (!ip.startsWith("127.0") && !ip.startsWith("192.168")) {
localAddress = ip;
break;
}
}
if (localAddress == null) {
// 取第一个
localAddress = ips.get(0);
}
} else {
localAddress = InetAddress.getLocalHost().getHostAddress();
}
System.out.println("====================");
System.out.println(localAddress);
}
}
运行结果
最后
以上就是可爱季节为你收集整理的动态获取本机的ip地址和hostName的全部内容,希望文章能够帮你解决动态获取本机的ip地址和hostName所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复