现在,所有节点都将创建一个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
EDIT
我我正在使用以下代码:
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 楼
import java.net.DatagramSocket;
import java.net.InetAddress;
try(final DatagramSocket socket = new DatagramSocket()){
socket.connect(InetAddress.getByName("8.8.8.8"), 10002);
ip = socket.getLocalAddress().getHostAddress();
}
当存在多个网络接口时,这种方法效果很好。它总是返回首选的出站IP。目的地
8.8.8.8
不需要是可访问的。 UDP套接字上的
Connect
具有以下效果:它设置发送/接收的目的地,丢弃来自其他地址的所有数据包,并且-我们使用的是-将套接字转换为“已连接”状态,设置其适当的字段。这包括根据系统的路由表检查到目的地的路由是否存在,并相应地设置本地端点。最后一部分似乎没有正式记录,但它看起来像是Berkeley套接字API的一个固有特征(UDP“已连接”状态的副作用),可以在Windows和Linux的各个版本和发行版中可靠地工作。 因此,此方法将提供用于连接到指定远程主机的本地地址。没有建立真正的连接,因此指定的远程IP可能无法访问。
编辑:
如@macomgil所说,对于MacOS,您可以这样做:
Socket socket = new Socket();
socket.connect(new InetSocketAddress("google.com", 80));
System.out.println(socket.getLocalAddress());
评论
它在Linux上对我有用,但在OsX上我得到:“ 0.0.0.0”
–拉杜·图德(Radu Toader)
17年9月10日在22:09
@Jeef,答案已更新。如果它在OsX上不起作用,则需要选择另一种方法。
–隔壁的王先生
18年3月20日在10:50
辉煌!仅供参考,在处理封闭的内部网络时,只需将8.8.8.8替换为每个主机可以到达的内容
–墨菲
18年8月3日在7:23
在Windows上工作;我们可以确认OSX是否仍然存在问题吗?
–三部曲
18-10-2在14:31
@trilogy我仍然在OSX上获得0.0.0.0
– Peter Tutervai
19年3月12日在16:02
#2 楼
在最一般的情况下,这可能会有些棘手。表面上,
InetAddress.getLocalHost()
应该为您提供此主机的IP地址。问题在于主机可能具有许多网络接口,并且一个接口可能绑定到多个IP地址。最重要的是,并非所有IP地址都可以在您的计算机或LAN外部访问。例如,它们可以是虚拟网络设备的IP地址,专用网络IP地址等等。这意味着
InetAddress.getLocalHost()
返回的IP地址可能不是正确的使用地址。 如何处理?
一种方法是使用
NetworkInterface.getNetworkInterfaces()
获取主机上所有已知的网络接口,然后在每个接口上进行迭代。 NI的地址。另一种方法是(以某种方式)获取主机的外部广告FQDN,并使用
InetAddress.getByName()
查找主IP地址。 (但是,如何获得它,以及如何使用基于DNS的负载均衡器?)前一种方法是从配置文件或命令行参数中获得首选的FQDN。
另一种变化是从配置文件或命令行参数中获取首选的IP地址。
总而言之,
InetAddress.getLocalHost()
通常可以使用,但是对于您的情况,您可能需要提供一种替代方法代码在具有“复杂”网络的环境中运行。我可以获取与所有网络接口关联的所有IP地址,但是如何区分它们呢? br />
范围为127.xxx.xxx.xxx的任何地址都是“回送”地址。仅对“此”主机可见。
192.168.192.168..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地址。
评论
万一有人好奇,getLocalHost本质上会对服务器的主机名进行DNS查找。如果它从该查找中获得IP地址,则它将搜索可用的接口以查看哪个接口具有该IP地址,并返回该接口。这意味着getLocalHost将倾向于在“服务器”环境中工作,在该环境中,传出IP是映射到服务器主机名的IP。
–步伐
14年7月16日在7:30
在Ubuntu 14.04上,即使ifconfig仅报告两个接口(我想要的一个接口(可公开访问的IP地址)和回送接口(127.0.0.1)),此api仍返回127.0.1.1。奇怪的是它返回了不同的回送别名。
–ctpenrose
15年3月24日在21:14
我还要补充一点,如果您使用getLocalHost()。getHostAddress()发布某些内容,则从网络上的另一台计算机查看时可能会看到0.0.0.0。这是在这里解释的这是当我在两台计算机上使用Gazebo时发生的事情
– Peter Mitrano
15年7月6日在23:50
#3 楼
从https://issues.apache.org/jira/browse/JCS-40(在Linux系统上,InetAddress.getLocalHost()模棱两可)上发布经过测试的IP歧义解决方法代码:/**
* Returns an <code>InetAddress</code> object encapsulating what is most likely the machine's LAN IP address.
* <p/>
* This method is intended for use as a replacement of JDK method <code>InetAddress.getLocalHost</code>, 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 <code>InetAddress.getLocalHost</code> 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
* <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4665037">here</a>.
* <p/>
* 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).
* <p/>
* 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 <code>InetAddress.getLocalHost</code>.
* <p/>
*
* @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;
}
}
评论
必须注意的是,如果主机具有多个相似的网络接口,这仍然不能解决歧义。
–Vadzim
2013年12月7日在8:53
波纹管的答案更好-stackoverflow.com/questions/9481865/…获取用作默认网关的src的本地IP地址
–拉杜·图德(Radu Toader)
17年6月27日在14:47
为什么IP地址加上斜杠..?像/10.39.0.17 ..?,是否总是应该以这种方式修剪..?
–卡纳加韦卢·苏古玛(Kanagavelu Sugumar)
17年9月11日在5:08
#4 楼
您可以为此目的使用Java的InetAddress类。InetAddress IP=InetAddress.getLocalHost();
System.out.println("IP of my system is := "+IP.getHostAddress());
我的系统的输出=
IP of my system is := 10.100.98.228
getHostAddress()返回
以文本形式返回IP地址字符串。
或者您也可以做
InetAddress IP=InetAddress.getLocalHost();
System.out.println(IP.toString());
输出=
IP of my system is := RanRag-PC/10.100.98.228
评论
请注意,10.x.x.x是一个专用地址,表示您的系统位于NAT网络上。与外界联系时,它将显示为其他地址。如果您确实需要外部IP地址,则必须联系许多站点之一,这些站点将回显您所来自的IP地址。这可能对您有用,也可能没有用。无论如何,几乎肯定无法从外部访问您的系统。
–爱德华·福克
13年4月19日在0:04
天哪,这是挽救我的生命。上一个我使用clientSocket.getInetAddress()。getHostName();
–NM Naufaldo
8月15日18:39
#5 楼
当您寻找“本地”地址时,应注意,每台计算机不仅具有单个网络接口,而且每个接口都可以具有自己的本地地址。这意味着您的计算机始终拥有多个“本地”地址。连接到不同端点时,将自动选择要使用的不同“本地”地址。例如,当您连接到
google.com
时,您使用的是“外部”本地地址。但是当您连接到localhost
时,您的本地地址始终是localhost
本身,因为localhost只是一个环回。下面显示了如何与
google.com
通信时查找您的本地地址:Socket socket = new Socket();
socket.connect(new InetSocketAddress("google.com", 80));
System.out.println(socket.getLocalAddress());
评论
太棒了!! - 太简单 :)
–笑脸
17年4月18日在13:18
在末尾添加socket.close():)
– M.C.
17年9月26日在16:37
#6 楼
scala中的示例(在sbt文件中有用): import collection.JavaConverters._
import java.net._
def getIpAddress: String = {
val enumeration = NetworkInterface.getNetworkInterfaces.asScala.toSeq
val ipAddresses = enumeration.flatMap(p =>
p.getInetAddresses.asScala.toSeq
)
val address = ipAddresses.find { address =>
val host = address.getHostAddress
host.contains(".") && !address.isLoopbackAddress
}.getOrElse(InetAddress.getLocalHost)
address.getHostAddress
}
#7 楼
编辑1:自从上一个链接以来,更新的代码已不存在import java.io.*;
import java.net.*;
public class GetMyIP {
public static void main(String[] args) {
URL url = null;
BufferedReader in = null;
String ipAddress = "";
try {
url = new URL("http://bot.whatismyipaddress.com");
in = new BufferedReader(new InputStreamReader(url.openStream()));
ipAddress = in.readLine().trim();
/* IF not connected to internet, then
* the above code will return one empty
* String, we can check it's length and
* if length is not greater than zero,
* then we can go for LAN IP or Local IP
* or PRIVATE IP
*/
if (!(ipAddress.length() > 0)) {
try {
InetAddress ip = InetAddress.getLocalHost();
System.out.println((ip.getHostAddress()).trim());
ipAddress = (ip.getHostAddress()).trim();
} catch(Exception exp) {
ipAddress = "ERROR";
}
}
} catch (Exception ex) {
// This try will give the Private IP of the Host.
try {
InetAddress ip = InetAddress.getLocalHost();
System.out.println((ip.getHostAddress()).trim());
ipAddress = (ip.getHostAddress()).trim();
} catch(Exception exp) {
ipAddress = "ERROR";
}
//ex.printStackTrace();
}
System.out.println("IP Address: " + ipAddress);
}
}
希望该代码段可能会有所帮助您可以实现以下目标:
// Method to get the IP Address of the Host.
private String getIP()
{
// This try will give the Public IP Address of the Host.
try
{
URL url = new URL("http://automation.whatismyip.com/n09230945.asp");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String ipAddress = new String();
ipAddress = (in.readLine()).trim();
/* IF not connected to internet, then
* the above code will return one empty
* String, we can check it's length and
* if length is not greater than zero,
* then we can go for LAN IP or Local IP
* or PRIVATE IP
*/
if (!(ipAddress.length() > 0))
{
try
{
InetAddress ip = InetAddress.getLocalHost();
System.out.println((ip.getHostAddress()).trim());
return ((ip.getHostAddress()).trim());
}
catch(Exception ex)
{
return "ERROR";
}
}
System.out.println("IP Address is : " + ipAddress);
return (ipAddress);
}
catch(Exception e)
{
// This try will give the Private IP of the Host.
try
{
InetAddress ip = InetAddress.getLocalHost();
System.out.println((ip.getHostAddress()).trim());
return ((ip.getHostAddress()).trim());
}
catch(Exception ex)
{
return "ERROR";
}
}
}
评论
如果我总是连接到互联网,则该解决方案将起作用,但我不能保证。此外,当系统未连接到Internet时,我需要返回系统的LAN IP地址(如果有),否则返回本地主机。所以对我来说不是一个可行的选择。还有其他办法吗?
– sasidhar
2012年2月28日17:34
@sasidhar:当您连接到Internet时,我想只有您拥有公用IP,如果没有连接,则此方法将为您提供本地IP或LAN IP,并提供您指定的最后一种条件您可以返回“ 127.0.0.1”,而不是返回Error。
– nICE COW
2012-2-28 17:40
我喜欢您的方法,但是该链接似乎不再起作用!我可以在我自己的系统上放置一个控制器来代替该外部链接来工作,以便更可靠吗?
–azerafati
2014年8月27日在12:23
@Bludream:非常感谢您,据我所知,该链接不再起作用。我已经更新了帖子,并添加了一些新内容。希望它适用于您的用户案例。关于您的问题,我真的不知道如何在自己的系统上设置控制器以使其正常工作。因此,我将无法就这个话题提供见识,我的坏。再次感谢,并保持微笑:-)
– nICE COW
2014年8月27日在15:48
尽管这是一个很酷的解决方案,但它绝对不可靠。如果您要阻止主线程(说什么),并且无论什么原因whatismyip.com都关闭了一段时间,您的应用程序也将关闭:(。否则它将返回垃圾数据并导致意外行为。此外,这返回whatismyip.com可检测到的最外层IP地址,不一定返回您所使用的计算机的IP地址。
–解码
17年3月13日在22:39
#8 楼
首先导入类import java.net.InetAddress;
在类中
InetAddress iAddress = InetAddress.getLocalHost();
String currentIp = iAddress.getHostAddress();
System.out.println("Current IP address : " +currentIp); //gives only host address
评论
即使没有使用,它也只给出第一个IP地址!
– Yahya
17 Mar 5 '17 at 20:28
#9 楼
private static InetAddress getLocalAddress(){
try {
Enumeration<NetworkInterface> b = NetworkInterface.getNetworkInterfaces();
while( b.hasMoreElements()){
for ( InterfaceAddress f : b.nextElement().getInterfaceAddresses())
if ( f.getAddress().isSiteLocalAddress())
return f.getAddress();
}
} catch (SocketException e) {
e.printStackTrace();
}
return null;
}
评论
请考虑添加一些有关代码功能的解释。
– HCarrasko
16年1月15日在13:02
#10 楼
您可以使用java.net.InetAddress
API。请尝试以下操作:
InetAddress.getLocalHost().getHostAddress();
评论
它只会返回127.0.0.1
– HCarrasko
16年1月15日在13:02
#11 楼
这是上面“已接受”答案的一个有效示例!此NetIdentity类将存储内部主机ip和本地环回。如上所述,如果您使用的是基于DNS的服务器,则可能需要添加一些其他检查,或者可能要执行配置文件路由。
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
/**
* Class that allows a device to identify itself on the INTRANET.
*
* @author Decoded4620 2016
*/
public class NetIdentity {
private String loopbackHost = "";
private String host = "";
private String loopbackIp = "";
private String ip = "";
public NetIdentity(){
try{
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while(interfaces.hasMoreElements()){
NetworkInterface i = interfaces.nextElement();
if(i != null){
Enumeration<InetAddress> addresses = i.getInetAddresses();
System.out.println(i.getDisplayName());
while(addresses.hasMoreElements()){
InetAddress address = addresses.nextElement();
String hostAddr = address.getHostAddress();
// local loopback
if(hostAddr.indexOf("127.") == 0 ){
this.loopbackIp = address.getHostAddress();
this.loopbackHost = address.getHostName();
}
// internal ip addresses (behind this router)
if( hostAddr.indexOf("192.168") == 0 ||
hostAddr.indexOf("10.") == 0 ||
hostAddr.indexOf("172.16") == 0 ){
this.host = address.getHostName();
this.ip = address.getHostAddress();
}
System.out.println("\t\t-" + address.getHostName() + ":" + address.getHostAddress() + " - "+ address.getAddress());
}
}
}
}
catch(SocketException e){
}
try{
InetAddress loopbackIpAddress = InetAddress.getLocalHost();
this.loopbackIp = loopbackIpAddress.getHostName();
System.out.println("LOCALHOST: " + loopbackIp);
}
catch(UnknownHostException e){
System.err.println("ERR: " + e.toString());
}
}
public String getLoopbackHost(){
return loopbackHost;
}
public String getHost(){
return host;
}
public String getIp(){
return ip;
}
public String getLoopbackIp(){
return loopbackIp;
}
}
当我运行此代码,我实际上得到了这样的打印输出:
Software Loopback Interface 1
-127.0.0.1:127.0.0.1 - [B@19e1023e
-0:0:0:0:0:0:0:1:0:0:0:0:0:0:0:1 - [B@7cef4e59
Broadcom 802.11ac Network Adapter
-VIKING.yourisp.com:192.168.1.142 - [B@64b8f8f4
-fe80:0:0:0:81fa:31d:21c9:85cd%wlan0:fe80:0:0:0:81fa:31d:21c9:85cd%wlan0 - [B@2db0f6b2
Microsoft Kernel Debug Network Adapter
Intel Edison USB RNDIS Device
Driver for user-mode network applications
Cisco Systems VPN Adapter for 64-bit Windows
VirtualBox Host-Only Ethernet Adapter
-VIKING:192.168.56.1 - [B@3cd1f1c8
-VIKING:fe80:0:0:0:d599:3cf0:5462:cb7%eth4 - [B@3a4afd8d
LogMeIn Hamachi Virtual Ethernet Adapter
-VIKING:25.113.118.39 - [B@1996cd68
-VIKING:2620:9b:0:0:0:0:1971:7627 - [B@3339ad8e
-VIKING:fe80:0:0:0:51bf:994d:4656:8486%eth5 - [B@555590
Bluetooth Device (Personal Area Network)
-fe80:0:0:0:4c56:8009:2bca:e16b%eth6:fe80:0:0:0:4c56:8009:2bca:e16b%eth6 - [B@3c679bde
Bluetooth Device (RFCOMM Protocol TDI)
Intel(R) Ethernet Connection (2) I218-V
-fe80:0:0:0:4093:d169:536c:7c7c%eth7:fe80:0:0:0:4093:d169:536c:7c7c%eth7 - [B@16b4a017
Microsoft Wi-Fi Direct Virtual Adapter
-fe80:0:0:0:103e:cdf0:c0ac:1751%wlan1:fe80:0:0:0:103e:cdf0:c0ac:1751%wlan1 - [B@8807e25
VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0000
VirtualBox Host-Only Ethernet Adapter-WFP Native MAC Layer LightWeight Filter-0000
VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0001
VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0002
VirtualBox Host-Only Ethernet Adapter-VirtualBox NDIS Light-Weight Filter-0000
VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0003
VirtualBox Host-Only Ethernet Adapter-QoS Packet Scheduler-0000
VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0004
VirtualBox Host-Only Ethernet Adapter-WFP 802.3 MAC Layer LightWeight Filter-0000
VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0005
Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0000
Intel(R) Ethernet Connection (2) I218-V-WFP Native MAC Layer LightWeight Filter-0000
Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0001
Intel(R) Ethernet Connection (2) I218-V-Shrew Soft Lightweight Filter-0000
Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0002
Intel(R) Ethernet Connection (2) I218-V-VirtualBox NDIS Light-Weight Filter-0000
Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0003
Intel(R) Ethernet Connection (2) I218-V-QoS Packet Scheduler-0000
Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0004
Intel(R) Ethernet Connection (2) I218-V-WFP 802.3 MAC Layer LightWeight Filter-0000
Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0005
Broadcom 802.11ac Network Adapter-WFP Native MAC Layer LightWeight Filter-0000
Broadcom 802.11ac Network Adapter-Virtual WiFi Filter Driver-0000
Broadcom 802.11ac Network Adapter-Native WiFi Filter Driver-0000
Broadcom 802.11ac Network Adapter-HHD Software NDIS 6.0 Filter Driver-0003
Broadcom 802.11ac Network Adapter-Shrew Soft Lightweight Filter-0000
Broadcom 802.11ac Network Adapter-HHD Software NDIS 6.0 Filter Driver-0004
Broadcom 802.11ac Network Adapter-VirtualBox NDIS Light-Weight Filter-0000
Broadcom 802.11ac Network Adapter-HHD Software NDIS 6.0 Filter Driver-0005
Broadcom 802.11ac Network Adapter-QoS Packet Scheduler-0000
Broadcom 802.11ac Network Adapter-HHD Software NDIS 6.0 Filter Driver-0006
Broadcom 802.11ac Network Adapter-WFP 802.3 MAC Layer LightWeight Filter-0000
Broadcom 802.11ac Network Adapter-HHD Software NDIS 6.0 Filter Driver-0007
Microsoft Wi-Fi Direct Virtual Adapter-WFP Native MAC Layer LightWeight Filter-0000
Microsoft Wi-Fi Direct Virtual Adapter-Native WiFi Filter Driver-0000
Microsoft Wi-Fi Direct Virtual Adapter-HHD Software NDIS 6.0 Filter Driver-0002
Microsoft Wi-Fi Direct Virtual Adapter-Shrew Soft Lightweight Filter-0000
Microsoft Wi-Fi Direct Virtual Adapter-HHD Software NDIS 6.0 Filter Driver-0003
Microsoft Wi-Fi Direct Virtual Adapter-VirtualBox NDIS Light-Weight Filter-0000
Microsoft Wi-Fi Direct Virtual Adapter-HHD Software NDIS 6.0 Filter Driver-0004
Microsoft Wi-Fi Direct Virtual Adapter-QoS Packet Scheduler-0000
Microsoft Wi-Fi Direct Virtual Adapter-HHD Software NDIS 6.0 Filter Driver-0005
Microsoft Wi-Fi Direct Virtual Adapter-WFP 802.3 MAC Layer LightWeight Filter-0000
Microsoft Wi-Fi Direct Virtual Adapter-HHD Software NDIS 6.0 Filter Driver-0006
就我的使用而言,我正在设置Upnp服务器,它有助于理解“模式”我正寻找。返回的一些对象是以太网适配器,网络适配器,虚拟网络适配器,驱动程序和VPN客户端适配器。并非所有内容都具有地址。因此,您将希望跳过不存在的接口对象。
还可以将其添加到当前
NetworkInterface i
的循环中while(interfaces.hasMoreElements()){
Enumeration<InetAddress> addresses = i.getInetAddresses();
System.out.println(i.getDisplayName());
System.out.println("\t- name:" + i.getName());
System.out.println("\t- idx:" + i.getIndex());
System.out.println("\t- max trans unit (MTU):" + i.getMTU());
System.out.println("\t- is loopback:" + i.isLoopback());
System.out.println("\t- is PPP:" + i.isPointToPoint());
System.out.println("\t- isUp:" + i.isUp());
System.out.println("\t- isVirtual:" + i.isVirtual());
System.out.println("\t- supportsMulticast:" + i.supportsMulticast());
}
而且您会在输出中看到如下所示的信息:
Software Loopback Interface 1
- name:lo
- idx:1
- max trans unit (MTU):-1
- is loopback:true
- is PPP:false
- isUp:true
- isVirtual:false
- supportsMulticast:true
-ADRESS: [127.0.0.1(VIKING-192.168.56.1)]127.0.0.1:127.0.0.1 - [B@19e1023e
-ADRESS: [0:0:0:0:0:0:0:1(VIKING-192.168.56.1)]0:0:0:0:0:0:0:1:0:0:0:0:0:0:0:1 - [B@7cef4e59
Broadcom 802.11ac Network Adapter
- name:wlan0
- idx:2
- max trans unit (MTU):1500
- is loopback:false
- is PPP:false
- isUp:true
- isVirtual:false
- supportsMulticast:true
-ADRESS: [VIKING.monkeybrains.net(VIKING-192.168.56.1)]VIKING.monkeybrains.net:192.168.1.142 - [B@64b8f8f4
-ADRESS: [fe80:0:0:0:81fa:31d:21c9:85cd%wlan0(VIKING-192.168.56.1)]fe80:0:0:0:81fa:31d:21c9:85cd%wlan0:fe80:0:0:0:81fa:31d:21c9:85cd%wlan0 - [B@2db0f6b2
Microsoft Kernel Debug Network Adapter
- name:eth0
- idx:3
- max trans unit (MTU):-1
- is loopback:false
- is PPP:false
- isUp:false
- isVirtual:false
- supportsMulticast:true
#12 楼
使用InetAddress.getLocalHost()获取本地地址import java.net.InetAddress;
try {
InetAddress addr = InetAddress.getLocalHost();
System.out.println(addr.getHostAddress());
} catch (UnknownHostException e) {
}
评论
我的PPP连接IP地址是:117.204.44.192但是上面返回了我192.168.1.2
– sasidhar
2012年2月28日在12:54
您需要对所有可用的InetAddress实例进行爬网,并找出哪个是合适的。
–解码
17年3月13日在22:40
#13 楼
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
public class IpAddress {
NetworkInterface ifcfg;
Enumeration<InetAddress> addresses;
String address;
public String getIpAddress(String host) {
try {
ifcfg = NetworkInterface.getByName(host);
addresses = ifcfg.getInetAddresses();
while (addresses.hasMoreElements()) {
address = addresses.nextElement().toString();
address = address.replace("/", "");
}
} catch (Exception e) {
e.printStackTrace();
}
return ifcfg.toString();
}
}
#14 楼
一种似乎很有效的简单方法...String getPublicIPv4() throws UnknownHostException, SocketException{
Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
String ipToReturn = null;
while(e.hasMoreElements())
{
NetworkInterface n = (NetworkInterface) e.nextElement();
Enumeration<InetAddress> ee = n.getInetAddresses();
while (ee.hasMoreElements())
{
InetAddress i = (InetAddress) ee.nextElement();
String currentAddress = i.getHostAddress();
logger.trace("IP address "+currentAddress+ " found");
if(!i.isSiteLocalAddress()&&!i.isLoopbackAddress() && validate(currentAddress)){
ipToReturn = currentAddress;
}else{
System.out.println("Address not validated as public IPv4");
}
}
}
return ipToReturn;
}
private static final Pattern IPv4RegexPattern = Pattern.compile(
"^(([01]?\d\d?|2[0-4]\d|25[0-5])\.){3}([01]?\d\d?|2[0-4]\d|25[0-5])$");
public static boolean validate(final String ip) {
return IPv4RegexPattern.matcher(ip).matches();
}
#15 楼
如果您的计算机是网络的一部分,则将获取网络的IP地址。try {
System.out.println(InetAddress.getLocalHost().getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
#16 楼
通常,当我尝试查找cmyip.com或www.iplocation.net之类的公共IP地址时,我会使用以下方式:public static String myPublicIp() {
/*nslookup myip.opendns.com resolver1.opendns.com*/
String ipAdressDns = "";
try {
String command = "nslookup myip.opendns.com resolver1.opendns.com";
Process proc = Runtime.getRuntime().exec(command);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String s;
while ((s = stdInput.readLine()) != null) {
ipAdressDns += s + "\n";
}
} catch (IOException e) {
e.printStackTrace();
}
return ipAdressDns ;
}
#17 楼
由于我的系统(像许多其他系统一样)具有各种网络接口。InetAddress.getLocalHost()
或Inet4Address.getLocalHost()
只是返回了我不想要的。因此,我不得不使用这种幼稚的方法。
InetAddress[] allAddresses = Inet4Address.getAllByName("YourComputerHostName");
InetAddress desiredAddress;
//In order to find the desired Ip to be routed by other modules (WiFi adapter)
for (InetAddress address :
allAddresses) {
if (address.getHostAddress().startsWith("192.168.2")) {
desiredAddress = address;
}
}
// Use the desired address for whatever purpose.
请小心,在这种方法中,我已经知道我想要的IP地址在
192.168.2
子网中。
评论
Inet4Address.getLocalHost()应该正确吗?在循环中,如果我添加n.isPointToPoint()会起作用吗?我的想法是,如果找不到“点对点”网络,则返回“ 127.0.0.1”。那行得通吗?
@sasidhar:请不要发布您的真实IP地址。请为私有IP写117.xxx.xxx.xxx。
@GagandeepBali感谢您的建议,但是我的IP是动态IP,每次断开连接并连接到Internet时,我都会获得一个新IP。我想这应该不是问题。
相关:stackoverflow.com/questions/6064510/…