java获取当前电脑的ip_使用Java获取当前计算机的IP地址

问题

我正在尝试开发一个系统,其中有不同的节点在不同的系统上或在同一系统上的不同端口上运行。

现在所有节点都创建一个Socket,其目标IP作为称为自举节点的特殊节点的IP。然后节点创建自己的ServerSocket并开始侦听连接。

引导节点维护一个节点列表,并在被查询时返回它们。

现在我需要的是节点必须将其IP注册到自举节点。我尝试使用cli.getInetAddress(),因为客户端连接到引导节点的ServerSocket,但这不起作用。

我需要客户端注册其PPP IP(如果可用);

否则LAN IP(如果有);

否则它必须注册127.0.0.1,假设它是同一台计算机。

使用代码:

System.out.println(Inet4Address.getLocalHost().getHostAddress());

要么

System.out.println(InetAddress.getLocalHost().getHostAddress());

我的PPP连接IP地址是:117.204.44.192,但上面的返回值为192.168.1.2

编辑

我使用以下代码:

Enumeration e = NetworkInterface.getNetworkInterfaces();

while(e.hasMoreElements())

{

NetworkInterface n = (NetworkInterface) e.nextElement();

Enumeration ee = n.getInetAddresses();

while (ee.hasMoreElements())

{

InetAddress i = (InetAddress) ee.nextElement();

System.out.println(i.getHostAddress());

}

}

我能够获得所有与NetworkInterface相关的IP地址,但我如何区分它们呢?这是我得到的输出:

127.0.0.1

192.168.1.2

192.168.56.1

117.204.44.19

#1 热门回答(233 赞)

在最一般的情况下,这可能有点棘手。

从表面上看,InetAddress.getLocalHost()应该为你提供该主机的IP地址。问题是主机可能有很多网络接口,接口可能绑定到多个IP地址。最重要的是,并非所有IP地址都可以在你的计算机或LAN之外访问。例如,它们可以是虚拟网络设备的IP地址,专用网络IP地址等。

这意味着InetAddress.getLocalHost()返回的IP地址可能不适合使用。

你怎么处理这个?

一种方法是使用NetworkInterface.getNetworkInterfaces()获取主机上的所有已知网络接口,然后迭代每个NI的地址。

另一种方法是(以某种方式)获取主机的外部广告FQDN,并使用InetAddress.getByName()来查找主IP地址。 (但是你如何得到它,以及如何处理基于DNS的负载均衡器?)

前一个版本的变体是从配置文件或命令行参数中获取首选FQDN。

另一种变体是从配置文件或命令行参数中获取首选IP地址。

总之,InetAddress.getLocalHost()通常可以工作,但是你可能需要为在"复杂"网络环境中运行代码的情况提供替代方法。

我能够获得与所有网络接口相关的所有IP地址,但我如何区分它们?

127.xxx.xxx.xxx范围内的任何地址都是"环回"地址。它只对"这个"主机可见。

192.168.xxx.xxx范围内的任何地址都是私有(即本地站点)IP地址。这些保留在组织内使用。这同样适用于10.xxx.xxx.xxx地址,172.16.xxx.xxx到172.31.xxx.xxx。

169.254.xxx.xxx范围内的地址是链路本地IP地址。这些保留用于单个网段。

224.xxx.xxx.xxx到239.xxx.xxx.xxx范围内的地址是多播地址。

地址255.255.255.255是广播地址。

其他任何东西都应该是有效的公共点对点IPv4地址。

事实上,InetAddress API提供了测试环回,链接本地,站点本地,多播和广播地址的方法。你可以使用这些来排序你获得的哪个IP地址是最合适的。

#2 热门回答(49 赞)

这里发布的测试IP歧义解决方法代码来自https://issues.apache.org/jira/browse/JCS-40(InetAddress.getLocalHost()在Linux系统上不明确):

/**

* Returns an InetAddress object encapsulating what is most likely the machine's LAN IP address.

*

* This method is intended for use as a replacement of JDK method InetAddress.getLocalHost, because

* that method is ambiguous on Linux systems. Linux systems enumerate the loopback network interface the same

* way as regular LAN network interfaces, but the JDK InetAddress.getLocalHost method does not

* specify the algorithm used to select the address returned under such circumstances, and will often return the

* loopback address, which is not valid for network communication. Details

* here.

*

* This method will scan all IP addresses on all network interfaces on the host machine to determine the IP address

* most likely to be the machine's LAN address. If the machine has multiple IP addresses, this method will prefer

* a site-local IP address (e.g. 192.168.x.x or 10.10.x.x, usually IPv4) if the machine has one (and will return the

* first site-local address if the machine has more than one), but if the machine does not hold a site-local

* address, this method will return simply the first non-loopback address found (IPv4 or IPv6).

*

* If this method cannot find a non-loopback address using this selection algorithm, it will fall back to

* calling and returning the result of JDK method InetAddress.getLocalHost.

*

*

* @throws UnknownHostException If the LAN address of the machine cannot be found.

*/

private static InetAddress getLocalHostLANAddress() throws UnknownHostException {

try {

InetAddress candidateAddress = null;

// Iterate all NICs (network interface cards)...

for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();) {

NetworkInterface iface = (NetworkInterface) ifaces.nextElement();

// Iterate all IP addresses assigned to each card...

for (Enumeration inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) {

InetAddress inetAddr = (InetAddress) inetAddrs.nextElement();

if (!inetAddr.isLoopbackAddress()) {

if (inetAddr.isSiteLocalAddress()) {

// Found non-loopback site-local address. Return it immediately...

return inetAddr;

}

else if (candidateAddress == null) {

// Found non-loopback address, but not necessarily site-local.

// Store it as a candidate to be returned if site-local address is not subsequently found...

candidateAddress = inetAddr;

// Note that we don't repeatedly assign non-loopback non-site-local addresses as candidates,

// only the first. For subsequent iterations, candidate will be non-null.

}

}

}

}

if (candidateAddress != null) {

// We did not find a site-local address, but we found some other non-loopback address.

// Server might have a non-site-local address assigned to its NIC (or it might be running

// IPv6 which deprecates the "site-local" concept).

// Return this non-loopback candidate address...

return candidateAddress;

}

// At this point, we did not find a non-loopback address.

// Fall back to returning whatever InetAddress.getLocalHost() returns...

InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();

if (jdkSuppliedAddress == null) {

throw new UnknownHostException("The JDK InetAddress.getLocalHost() method unexpectedly returned null.");

}

return jdkSuppliedAddress;

}

catch (Exception e) {

UnknownHostException unknownHostException = new UnknownHostException("Failed to determine LAN address: " + e);

unknownHostException.initCause(e);

throw unknownHostException;

}

}

#3 热门回答(40 赞)

你可以使用java'sInetAddressclass来实现此目的。

InetAddress IP=InetAddress.getLocalHost();

System.out.println("IP of my system is := "+IP.getHostAddress());

我系统的输出= IP of my system is := 10.100.98.228

返回文本演示文稿中的IP地址字符串。

或者你也可以

InetAddress IP=InetAddress.getLocalHost();

System.out.println(IP.toString());

输出= IP of my system is := RanRag-PC/10.100.98.228

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/500691.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

两千块钱带来的 希望

几年以前,我参加过一个全国 “软件学院” 的评审,得到两千块现金和一些希望。我后来把钱和希望都还给同学们了,现在说明一下。 [这是个人回忆,不代表任何组织,也不确保所有信息的完全准确] 我先…

java 内部变量_java 中的内置数据类型

1, 基本数据类型Java是强类型语言, 对于每一种数据都定义了类型,基本数据类型分为数值型,字符型,布尔型。数值型又分为了整型和浮点型。整型又分为byte, int, short long.浮点型又分为了float 和double.字符型是char 类型&#x…

DG导入mysql依赖包_MySql导入导出数据库(含远程导入导出)

1、先运行cmd,cd 到mysql安装目录中的bin文件夹2、mysqldump -u root -p 数据库名 > 导出文件名.sql其他情况下:1.导出整个数据库mysqldump -u 用户名 -p 数据库名 > 导出的文件名mysqldump -u wcnc -p smgp_apps_wcnc > wcnc.sql2.导出一个表m…

java线程的优点_Java使用多线程的优势

Java使用多线程的优势如果使用得当,线程可以有效地降低程序的开发和维护等成本,同时提升复杂应用程序的性能。那么Java使用多线程的优势具体有哪些呢,一起来了解一下!1、发挥多处理器的强大能力现在,多处理器系统正日益盛行&#…

开发软件不是闭卷考试

有人问我这个问题: “你正在做一个项目,这个项目有一项关键的feature需要实现,这个feature有一定的技术难度,你调试了很久,都没找到实现的途径,这时你已经在这个feature上花了很多时间了,而且无…

go语言mysql删除记录_MySQL数据库删除操作-Go语言中文社区

删除数据库DROP DATABASE [IF EXISTS] 数据库名;例如:删除school数据库IF EXISTS 为可选,判断是否存在,如果不存在则会抛出异常删除数据表DROP TABLE [IF EXISTS] 表名;例如:删除student表注意:删除具有主外键关系的表…

java csv下载_java 生成csv文件,弹出下载对话框。。。

1.最直接最简单的,方式是把文件地址直接放到html页面的一个链接中。这样做的缺点是把文件在服务器上的路径暴露了,并且还无法对文件下载进行其它的控制(如权限)。这个就不写示例了。2.在服务器端把文件转换成输出流,写…

中科大在50年代的教学理念

给中科大的学生上课, 得了解这个学校的教学理念,我从网上找到了一篇: 中国科学技术大学里的基础课中国科学技术大学力学和力学工程系系主任 钱学森中国科学技术大学是为我国培养尖端科学研究技术干部的,因此学生必需在学校里打下将来作研究工作的基础。…

软件工程 团队博客作业 如何评价个人在团队中的绩效

在现实社会中有很多团队合作的项目, 他们是如何评价个人在团队中的绩效呢? 例如下面的情况:•一群人把一堆砖头从A地搬到B地•一个剧组排演话剧•一群队员在职业球队踢球•医生和护士做手术•计算机系的一群老师教课•一群学生做软工项目 (PM, Dev, Test) (这是重点)如何衡量…

java中的位移运算符_java中的移位运算符(, , )

java中有3种移位运算符<>> : 右移运算符&#xff0c;不改变符号位&#xff0c;num >> n 表示二进制右移n位&#xff0c;结果相当于 num / (2的n次方)>>> : 无符号右移&#xff0c;长度扩展为4字节&#xff0c;最高位都为0&#xff0c;但正数扩展位补…

现代软件工程系列 软件 = 程序 + 软件工程

软件随想: 软件 程序 软件工程 最近和几个同道谈论了一些程序&#xff0c;架构&#xff0c;软件的问题&#xff0c;大家身在此山中&#xff0c;绕来绕去&#xff0c;始终没有能有明确清晰的结论。我把一些想法写在这里&#xff0c;供专家指正。 几乎所有程序员都知道“程序…

java 参数代替所有类_Java中的常用类

1 常用类NO13【Int Intergershort Shortbyte Bytedouble Doublefloat FloatBoolean BooleanChar Character】封装类都是引用类型&#xff0c;并且也具有对应基本数据类型的数学运算特征装箱&#xff1a;将基本数据类型的值装进封装类对象中去&#xff0c;也可以…

现代软件工程系列 学生和老师都不容易

老师的难处 - V2.0 的困难 有笑话说某人请客, 客人无论是坐轿或是步行前来, 主人都能奉承一番。 有客人说自己是爬着来的&#xff0c; 主人奉承说 - 稳妥之至! 据说有些学校的有些课还是沿用 N 年前的教案和教材, 这当然稳妥之至。我看到学校用很多年前的稳妥教材把学生…

现代软件工程系列 学生的精彩文章 (1)

讲了很多课, 碰到了很多学生, 他们教给我不少东西, 下面是一些我印象中的精彩文章: http://teamkingofcsharp.spaces.live.com/blog/cns!59FC2D3DD66822AA!188.entry December 26“大教堂”与“市集” 软件项目的管理者总是无比艳羡传统行业&#xff0c;无论是工业的流水线还是…

jpa mysql存储过程_(原)springbootjpa调用服务器mysql数据库的存储过程方法-Go语言中文社区...

一、springboot jpa项目文件配置#----------------------------------------------------------###########################################################datasource 配置MYSQL数据源&#xff1b;########################################################## 数据库sprin…

现代软件工程系列 学生的精彩文章 (3) 如何在Bug 不断的情况下还能保持平常心...

from: http://teamkingofcsharp.spaces.live.com/blog/cns!59FC2D3DD66822AA!222.entry 感想 平常心 初中的数学老师常常和我说&#xff1a;“你要学会保持一颗平常心”。我是一个不那么豁达开朗的人&#xff0c;对很多事情都会很看重&#xff0c;GPA&#xff0c;排名&#x…

mysql 不需要@的变量_mysql参数变量

mysql服务器的系统变量,mysql server system viriables&#xff0c;其实我更愿意叫它为“系统参数”&#xff01;每一个系统变量都有一个默认值&#xff0c;这个默认值是在编译mysql系统的时候确定的。对系统变量的指定&#xff0c;一般可以在server启动的时候在命令行指定选项…

mysql 快速导出_mysql 快速导入导出

随着数据库的数据越来越大&#xff0c;采用mysqldump 越来越慢&#xff0c;测试环境的机器配置不高&#xff0c;2G左右的数据导入进入像蜗牛一般&#xff0c;非常影响效率&#xff0c;这里采用一些改进的方法来比以前导入的速度提高好几倍&#xff0c;但日常配备应有更好的策略…

现代软件工程系列 学生读后感 梦断代码

from:http://ttcs.spaces.live.com/blog/cns!C3759CC6FCEEBDD7!121.entry?sa147831050November 10梦断代码读后介绍 一&#xff0c;这本书讲了什么&#xff1f;软件是人们自以为最有把握&#xff0c;实则最难掌握的技术。作者罗森伯格对OSAF主持的Chandler项目进行长期调查&am…

现代软件工程系列 学生读后感 梦断代码 DTSlob (1)

1As you see, I’ve marked this post Number 1. Let’s leave the last post on “Dreaming in code” Number 0 :) This time, I will focus on the issue of PEOPLE, partly based on Chapter 0 and 1 in that book.Why focus on PEOPLE? Think about our group, think abo…