方式一:通过java.net.InetAddress类获取

1
2
3
4
5
6
7
8
public void test1() {
 try {
  InetAddress addr = InetAddress.getLocalHost();
  System.out.println("IP地址:" + addr.getHostAddress() + ",主机名:" + addr.getHostName());
 } catch (UnknownHostException e) {
  e.printStackTrace();
 }
}

输出:

IP地址:192.168.153.1,主机名:DESKTOP-338UP3E

这种方式获取到的主机名没啥问题,这种方式获取的主机名没啥问题,但获取到的IP地址却有待考量,如果一台机器有多个网卡,

他获取的IP是谁的呢?事实上,上面输出的IP是我虚拟机IP地址,既不是我有线网卡的地址,也不是我无线网卡的地址。

方式二:利用java.net.NetworkInterface获取

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public void test2() {
 try {
  Enumeration<NetworkInterface> faces = NetworkInterface.getNetworkInterfaces();
  while (faces.hasMoreElements()) { // 遍历网络接口
   NetworkInterface face = faces.nextElement();
   if (face.isLoopback() || face.isVirtual() || !face.isUp()) {
    continue;
   }
   System.out.print("网络接口名:" + face.getDisplayName() + ",地址:");
   Enumeration<InetAddress> address = face.getInetAddresses();
   while (address.hasMoreElements()) { // 遍历网络地址
    InetAddress addr = address.nextElement();
    if (!addr.isLoopbackAddress() && addr.isSiteLocalAddress() && !addr.isAnyLocalAddress()) {
     System.out.print(addr.getHostAddress() + " ");
    }
   }
   System.out.println("");
  }
 } catch (SocketException e) {
  e.printStackTrace();
 }
}

输出:

网络接口名:VMware Virtual Ethernet Adapter for VMnet8,地址:192.168.153.1
网络接口名:TAP-Windows Adapter V9,地址:10.8.0.30
网络接口名:VMware Virtual Ethernet Adapter for VMnet1,地址:192.168.46.1
网络接口名:Intel(R) Dual Band Wireless-AC 8265,地址:172.16.78.27

疑问?:第一、三行为VM虚拟机网络地址,不知为何还在。

工具类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
 
/**
 * 本地主机工具类
 *
 * @author zhi
 * @since 2019年11月13日09:04:36
 *
 */
public class LocalHostUtil {
 
 /**
  * 获取主机名称
  *
  * @return
  * @throws UnknownHostException
  */
 public static String getHostName() throws UnknownHostException {
  return InetAddress.getLocalHost().getHostName();
 }
 
 /**
  * 获取系统首选IP
  *
  * @return
  * @throws UnknownHostException
  */
 public static String getLocalIP() throws UnknownHostException {
  return InetAddress.getLocalHost().getHostAddress();
 }
 
 /**
  * 获取所有网卡IP,排除回文地址、虚拟地址
  *
  * @return
  * @throws SocketException
  */
 public static String[] getLocalIPs() throws SocketException {
  List<String> list = new ArrayList<>();
  Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
  while (enumeration.hasMoreElements()) {
   NetworkInterface intf = enumeration.nextElement();
   if (intf.isLoopback() || intf.isVirtual()) { //
    continue;
   }
   Enumeration<InetAddress> inets = intf.getInetAddresses();
   while (inets.hasMoreElements()) {
    InetAddress addr = inets.nextElement();
    if (addr.isLoopbackAddress() || !addr.isSiteLocalAddress() || addr.isAnyLocalAddress()) {
     continue;
    }
    list.add(addr.getHostAddress());
   }
  }
  return list.toArray(new String[0]);
 }
 
 /**
  * 判断操作系统是否是Windows
  *
  * @return
  */
 public static boolean isWindowsOS() {
  boolean isWindowsOS = false;
  String osName = System.getProperty("os.name");
  if (osName.toLowerCase().indexOf("windows") > -1) {
   isWindowsOS = true;
  }
  return isWindowsOS;
 }
 
 public static void main(String[] args) {
  try {
   System.out.println("主机是否为Windows系统:" + LocalHostUtil.isWindowsOS());
   System.out.println("主机名称:" + LocalHostUtil.getHostName());
   System.out.println("系统首选IP:" + LocalHostUtil.getLocalIP());
   System.out.println("系统所有IP:" + String.join(",", LocalHostUtil.getLocalIPs()));
  } catch (UnknownHostException e) {
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}
 

基于Java实现获取本地IP地址和主机名的更多相关文章

  1. Java获取本地IP地址和主机名

    方式一:通过java.net.InetAddress类获取 public void test1() { try { InetAddress addr = InetAddress.getLocalHos ...

  2. Java如何获取本地计算机的IP地址和主机名?

    在Java编程中,如何获取本地计算机的IP地址和主机名? 以下示例显示如何使用InetAddress类的getLocalAddress()方法获取系统的本地IP地址和主机名. package com. ...

  3. 获取本地IP地址信息

    2012-06-05    /// <summary>         /// 获取本地IP地址信息         /// </summary>         void G ...

  4. C# — 动态获取本地IP地址及可用端口

    1.在VS中动态获取本地IP地址,代码如下: 2.获取本机的可用端口以及已使用的端口:

  5. .net获取本地ip地址

    整理代码,.net获取本地ip地址,代码如下: string name = Dns.GetHostName(); IPHostEntry IpEntry = Dns.GetHostEntry(name ...

  6. 获取本地IP地址的vc代码

    作者:朱金灿 来源:http://blog.csdn.net/clever101 获取本地IP地址有两种做法.一种是使用gethostname函数,代码如下: bool CSocketComm::Ge ...

  7. Linux C 网络编程 - 获取本地 ip 地址,mac,通过域名获取对应的 ip

    获取本地 ip 地址,mac,通过域名获取对应的 ip, 是网络编程可能遇到的比较常见的操作了,所以总结如下(封装了3个函数), 直接上代码: #include <stdio.h> #in ...

  8. 获取本地ip地址 C#

    与ipconfig获取的所有信息一致的方法: private void GetIp() { System.Diagnostics.Process cmdp= new System.Diagnostic ...

  9. Linux下编程获取本地IP地址的常见方法

    转载于:http://blog.csdn.net/k346k346/article/details/48231933 在进行linux网络编程时,经常用到本机IP地址.本文罗列一下常见方法,以备不时之 ...

  10. Java 实例 - 获取本机ip地址及主机名

    package guyu.day0824; import java.net.InetAddress; /** * @Author: Fred * @Date: 2020/8/24 09:39 */ p ...

随机推荐

  1. 关于BarchNorm的一些学习

    <Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift> ...

  2. uniapp电子签名盖章实现详解

    项目开发中用到了电子签名.签好名的图片需要手动实现横竖屏旋转.并将绘制的签名图片放到pdf转换后的base64的图片上,可以手动拖动签名到合适的位置,最后合成签名和合同图片并导出.和以往一样,先发一下 ...

  3. 默认nginx.conf

    user nginx; worker_processes auto; error_log /var/log/nginx/error.log notice; pid /var/run/nginx.pid ...

  4. 后台管理系统的setting.js

    // 修改了此处要重新启动 module.exports = { // 网页的标题 title: "人力资源系统", /** * @type {boolean} true | fa ...

  5. flink同步MySQL数据的时候出现内存溢出

    flink同步MySQL数据的时候出现内存溢出 背景:需要将1000w的某类型数据同步到别的数据源里面,使用公司的大数据平台可以很快处理完毕,而且使用的内存只有很少很少量(公司的大数据平台的底层是fl ...

  6. KubeSphere 后端源码深度解析

    这篇文章我们将学习在 vscode 上的 ssh remote 插件基础上,尝试 debug 和学习 KubeSphere 后端模块架构. 前提 安装好 vscode 以及 ssh remote co ...

  7. 业务上线在即,ODBC应用程序性能频频掉线怎么搞?

  8. Visual Studio使用DotFuscator Community在Release时自动混淆并自动打包

    DotFuscator Community并不支持通过项目文件定义自动混淆文件,PRO当然可以. 为了简单使用DotFuscator Community自动混淆文件,并自动打包,通过四处打听,总结了一 ...

  9. TypeError: add_triangle_mesh(): incompatible function arguments. The following argument types are supported: 问题终于解决了!!!!

    1 2024.10.12 14:52 Traceback (most recent call last): File "terrain_creation.py", line 119 ...

  10. 2-4 C++ const限定词

    目录 2.4.1 const之于基本类型(base type) 含义 编译过程 2.4.2 const之于引用 含义 作用 注意点 2.4.3 const之于指针 含义[两类] 变量定义的读法:从左往 ...