使用Java获取当前计算机的IP地址
我正在尝试开发一个系统,其中有不同的节点运行在不同的系统上或同一系统上的不同端口上 现在,所有节点都创建了一个套接字,其中目标IP是一个称为引导节点的特殊节点的IP。然后节点创建自己的使用Java获取当前计算机的IP地址,java,sockets,ip,Java,Sockets,Ip,我正在尝试开发一个系统,其中有不同的节点运行在不同的系统上或同一系统上的不同端口上 现在,所有节点都创建了一个套接字,其中目标IP是一个称为引导节点的特殊节点的IP。然后节点创建自己的ServerSocket,并开始侦听连接 引导节点维护一个节点列表,并在查询时返回它们 现在我需要的是节点必须将其IP注册到引导节点。当客户端连接到引导节点的ServerSocket时,我尝试使用cli.getInetAddress(),但没有成功 我需要客户注册其PPP IP(如果可用) 否则,请选择LAN IP
ServerSocket
,并开始侦听连接
引导节点维护一个节点列表,并在查询时返回它们
现在我需要的是节点必须将其IP注册到引导节点。当客户端连接到引导节点的ServerSocket
时,我尝试使用cli.getInetAddress()
,但没有成功
System.out.println(Inet4Address.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
s关联的所有IP地址,但如何区分它们?这是我得到的输出:
127.0.0.1
192.168.1.2
192.168.56.1
117.204.44.19
您可以使用
java.net.InetAddress
API。
试试这个:
InetAddress.getLocalHost().getHostAddress();
为此,可以使用java的类
InetAddress IP=InetAddress.getLocalHost();
System.out.println("IP of my system is := "+IP.getHostAddress());
我的系统的输出=我的系统的IP为:=10.100.98.228
返回
以文本形式返回IP地址字符串
或者你也可以这样做
InetAddress IP=InetAddress.getLocalHost();
System.out.println(IP.toString());
输出=我的系统的IP是:=RanRag PC/10.100.98.228
用于获取本地地址
import java.net.InetAddress;
try {
InetAddress addr = InetAddress.getLocalHost();
System.out.println(addr.getHostAddress());
} catch (UnknownHostException e) {
}
在大多数情况下,这可能有点棘手 从表面上看,
InetAddress.getLocalHost()
应该为您提供此主机的IP地址。问题是主机可能有很多网络接口,并且一个接口可能绑定到多个IP地址。最重要的是,并非所有的IP地址都能在您的机器或LAN之外访问。例如,它们可以是虚拟网络设备的IP地址、专用网络IP地址等等
这意味着InetAddress.getLocalHost()
返回的IP地址可能不是正确的
你怎么处理这件事
- 一种方法是使用
获取主机上的所有已知网络接口,然后迭代每个NI的地址NetworkInterface.getNetworkInterfaces()
- 另一种方法是(以某种方式)获取主机的外部播发FQDN,并使用
查找主IP地址。(但是您如何获得它,以及如何处理基于DNS的负载平衡器?)InetAddress.getByName()
- 前一种方法的一个变体是从配置文件或命令行参数获取首选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地址中哪一个最合适。编辑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";
}
}
}
在此发布测试的IP歧义解决方案代码(Linux系统上的InetAddress.getLocalHost()歧义): scala中的示例(在sbt文件中很有用):
import collection.JavaConverters_
导入java.net_
def getIpAddress:字符串={
val枚举=NetworkInterface.getNetworkInterfaces.asScala.toSeq
val ipaddress=enumeration.flatMap(p=>
p、 getInetAddresses.asScala.toSeq
)
val address=ipaddress.find{address=>
val host=address.getHostAddress
host.contains(“.”&!address.isLoopbackAddress
}.getOrElse(InetAddress.getLocalHost)
address.getHostAddress
}
导入java.net.InetAddress;
导入java.net.NetworkInterface;
导入java.util.Enumeration;
公共类IP地址{
网络接口ifcfg;
枚举地址;
字符串地址;
公共字符串getIpAddress(字符串主机){
试一试{
ifcfg=NetworkInterface.getByName(主机);
addresses=ifcfg.getInetAddresses();
while(addresses.hasMoreElements()){
address=addresses.nextElement().toString();
地址=地址。替换(“/”,“”);
}
}捕获(例外e){
e、 printStackTrace();
}
返回ifcfg.toString();
}
}
首先导入类
import java.net.InetAddress;
课堂上
InetAddress iAddress = InetAddress.getLocalHost();
String currentIp = iAddress.getHostAddress();
System.out.println("Current IP address : " +currentIp); //gives only host address
private静态InetAddress getLocalAddress(){
试一试{
枚举b=NetworkInterface.getNetworkInterfaces();
而(b.hasmorelem)
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();
}
}
import java.net.InetAddress;
InetAddress iAddress = InetAddress.getLocalHost();
String currentIp = iAddress.getHostAddress();
System.out.println("Current IP address : " +currentIp); //gives only host address
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;
}
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();
}
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
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
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();
}
Socket socket = new Socket();
socket.connect(new InetSocketAddress("google.com", 80));
System.out.println(socket.getLocalAddress());
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 ;
}
Socket socket = new Socket();
socket.connect(new InetSocketAddress("google.com", 80));
System.out.println(socket.getLocalAddress());
socket.close();
try {
System.out.println(InetAddress.getLocalHost().getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
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.