java InetAddress.getLocalHost(); 返回 127.0.0.1 ... 如何获得真实 IP?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2381316/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java InetAddress.getLocalHost(); returns 127.0.0.1 ... how to get REAL IP?
提问by gotch4
I'm writing a simple networking app... I need to know the real ip of my machine on the network, like 192.168.1.3 . getLocalHost returns 127.0.0.1 (on Linux, dunno if it is the same on windows) how to do it?;
我正在编写一个简单的网络应用程序......我需要知道我的机器在网络上的真实 IP,比如 192.168.1.3 。getLocalHost 返回 127.0.0.1(在 Linux 上,不知道在 Windows 上是否相同)怎么做?;
回答by Paul Tomblin
Your computer may have multiple IPs. How do you know which one? The way I do it is to have a very simple CGI running on another machine that reports back the IP it's seen, and I hit that when I need to know what my IP looks like to the outside world.
您的计算机可能有多个 IP。你怎么知道是哪一个?我这样做的方法是在另一台机器上运行一个非常简单的 CGI,它会报告它看到的 IP,当我需要知道我的 IP 对外界的看法时,我点击了它。
回答by sfussenegger
As the machine might have multiple addresses, it's hard to determine which one is the one for you. Normally, you want the system to assign an IP based on its routing table. As the result depends on the IP you'd like to connect to, there is a simple trick: Simply create a connection and see what address you've got from the OS:
由于机器可能有多个地址,因此很难确定哪一个适合您。通常,您希望系统根据其路由表分配 IP。由于结果取决于您要连接的 IP,因此有一个简单的技巧:只需创建一个连接并查看您从操作系统获得的地址:
// output on my machine: "192.168.1.102"
Socket s = new Socket("192.168.1.1", 80);
System.out.println(s.getLocalAddress().getHostAddress());
s.close();
// output on my machine: "127.0.1.1"
System.out.println(InetAddress.getLocalHost().getHostAddress());
I'm not sure whether it's possible to do this without establishing a connection though. I think I've once managed to do it with Perl (or C?), but don't ask me about Java. I think it might be possible to create a UDP socket (DatagramSocket) without actually connecting it.
我不确定是否可以在不建立连接的情况下执行此操作。我想我曾经设法用 Perl(或 C?)做到这一点,但不要问我 Java。我认为可以在不实际连接的情况下创建 UDP 套接字(DatagramSocket)。
If there is a NAT router on the way you won't be able to get the IP that remote hosts will see though. However, as you gave 192.* as an example, I think you don't care.
如果途中有 NAT 路由器,您将无法获得远程主机将看到的 IP。但是,正如您以 192.* 为例,我认为您不在乎。
回答by Eric
If you actually want to work with all of the IP addresses on the machine you can get those with the NetworkInterface class. Of course, then you need to which one you actually want to use, but that's going to be different depending on what you're using it for, or you might need to expand the way you're using it to account for multiple addresses.
如果您真的想使用机器上的所有 IP 地址,您可以使用 NetworkInterface 类获取这些地址。当然,然后您需要实际想要使用哪个,但这取决于您使用它的目的,或者您可能需要扩展您使用它的方式来解释多个地址。
import java.net.*;
import java.util.*;
public class ShowInterfaces
{
public static void main(String[] args) throws Exception
{
System.out.println("Host addr: " + InetAddress.getLocalHost().getHostAddress()); // often returns "127.0.0.1"
Enumeration<NetworkInterface> n = NetworkInterface.getNetworkInterfaces();
for (; n.hasMoreElements();)
{
NetworkInterface e = n.nextElement();
System.out.println("Interface: " + e.getName());
Enumeration<InetAddress> a = e.getInetAddresses();
for (; a.hasMoreElements();)
{
InetAddress addr = a.nextElement();
System.out.println(" " + addr.getHostAddress());
}
}
}
}
回答by boom boom
To fix it:
要解决这个问题:
Find your host name. Type:
hostname
. For example, you find your hostname ismycomputer.xzy.com
Put your host name in your hosts file.
/etc/hosts
. Such as10.50.16.136 mycomputer.xzy.com
找到您的主机名。类型:
hostname
。例如,您发现您的主机名是mycomputer.xzy.com
将您的主机名放在您的主机文件中。
/etc/hosts
. 如10.50.16.136 mycomputer.xzy.com
回答by boly38
Here is a way to avoid IPv6 and Loopback results.
这是一种避免 IPv6 和环回结果的方法。
public InetAddress getCurrentIp() {
try {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface
.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) networkInterfaces
.nextElement();
Enumeration<InetAddress> nias = ni.getInetAddresses();
while(nias.hasMoreElements()) {
InetAddress ia= (InetAddress) nias.nextElement();
if (!ia.isLinkLocalAddress()
&& !ia.isLoopbackAddress()
&& ia instanceof Inet4Address) {
return ia;
}
}
}
} catch (SocketException e) {
LOG.error("unable to get current IP " + e.getMessage(), e);
}
return null;
}
回答by Eleven
Get the current request from the current instance
从当前实例获取当前请求
HttpServletRequest httpServletRequest = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
then get the address from the request
然后从请求中获取地址
ip = httpServletRequest.getRemoteAddr();
回答by Origamer7
In case you want to get the IP address of your PC, you have to use the "InetAddress" object, which exists in "java.net.InetAddress" library.
如果要获取 PC 的 IP 地址,则必须使用“java.net.InetAddress”库中存在的“InetAddress”对象。
The following method returns your IP:
以下方法返回您的 IP:
public String getIp() {
String myIp = "";
InetAddress ip;
try {
ip = InetAddress.getLocalHost();
myIp = ip.getHostAddress(); // This method returns the IP.
} catch (UnknownHostException e) {
e.printStackTrace();
}
return myIp;
}
回答by Ken Lin
Instead of using InetAddress.getHostAddress(), I call the getHost4Address routine that I wrote to get the first non-loopback address...
我没有使用 InetAddress.getHostAddress(),而是调用我编写的 getHost4Address 例程来获取第一个非环回地址......
/**
* Returns this host's non-loopback IPv4 addresses.
*
* @return
* @throws SocketException
*/
private static List<Inet4Address> getInet4Addresses() throws SocketException {
List<Inet4Address> ret = new ArrayList<Inet4Address>();
Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
for (NetworkInterface netint : Collections.list(nets)) {
Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
for (InetAddress inetAddress : Collections.list(inetAddresses)) {
if (inetAddress instanceof Inet4Address && !inetAddress.isLoopbackAddress()) {
ret.add((Inet4Address)inetAddress);
}
}
}
return ret;
}
/**
* Returns this host's first non-loopback IPv4 address string in textual
* representation.
*
* @return
* @throws SocketException
*/
private static String getHost4Address() throws SocketException {
List<Inet4Address> inet4 = getInet4Addresses();
return !inet4.isEmpty()
? inet4.get(0).getHostAddress()
: null;
}
回答by joseluisbz
I wrote this code:
我写了这段代码:
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
private String[] getHostAddresses() {
Set<String> HostAddresses = new HashSet<>();
try {
for (NetworkInterface ni : Collections.list(NetworkInterface.getNetworkInterfaces())) {
if (!ni.isLoopback() && ni.isUp() && ni.getHardwareAddress() != null) {
for (InterfaceAddress ia : ni.getInterfaceAddresses()) {
if (ia.getBroadcast() != null) { //If limited to IPV4
HostAddresses.add(ia.getAddress().getHostAddress());
}
}
}
}
} catch (SocketException e) { }
return HostAddresses.toArray(new String[0]);
}
Check it!
核实!
For me:
为了我:
- Must be not LoopBack!
- Must be UP!
- Must have MAC Address (is not null)
- 一定不是LoopBack!
- 必须UP!
- 必须有 MAC 地址(不为空)
回答by Pradeep Kumar Dhara
Get the ip address of the current box matching a pattern:
获取匹配某个模式的当前框的 ip 地址:
import java.io.*;
import java.util.*;
import java.util.regex.Pattern;
String ipPattern = "(192.1.200.)(\d){1,3}"; //your organization pattern
try{
Enumeration en = NetworkInterface.getNetworkInterfaces();
while (en.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) en.nextElement();
Enumeration ee = ni.getInetAddresses();
while (ee.hasMoreElements()) {
InetAddress ia = (InetAddress) ee.nextElement();
String ip = ia.getHostAddress();
System.out.println("ip: '" + ip + "'\n");
boolean matched = Pattern.matches(ipPattern, ip);
if (matched) {
System.out.println("matched\n");
}
}
}
}
catch(Exception e){ }
Result:
结果:
ip: 'fe80:0:0:0:510a:528b:7204:39d0%enp0s25'
ip: '192.1.200.3'
matched
ip: '0:0:0:0:0:0:0:1%lo'
ip: '127.0.0.1'