对如何用Java检索多个IP地址(如果我有多个网卡)有一些疑问?
在检索客户端的ip时,我遇到以下两个问题.
I have the following 2 problems in retrieving the ip of a client.
我已经在一个类中创建了以下代码:
I have create the following code inside a class:
private static InetAddress thisIp;
static{
try {
thisIp = InetAddress.getLocalHost();
System.out.println("MyIp is: " + thisIp);
} catch(UnknownHostException ex) {
}
}
我的问题是:
1)前面的代码应该检索客户端的IP地址,当我执行它时,它会显示以下消息:
1) The previous code should retrieve the IP address of a client, when I execute it it print the following message:
MyIP是:andrea-virtual-machine/127.0.1.1
为什么以 andrea-virtual-machine/开头? (我正在虚拟机上进行开发),这有问题吗?
Why it begin with andrea-virtual-machine/ ? (I am developing on a virtual machine), is it a problem?
2)这样,我只能检索单个IP地址,但是我可以拥有多个网卡,因此可以拥有多个IP地址,但多个IP地址
2) In this way I can retrieve only a single IP address but I could have more than a single network card so I could have more than a single IP address but multiple IP addresses
我该如何处理这种情况?我想将所有多个IP地址放入ArrayList
What can I do to handle this situation? I want put all the multiple IP addresses into an ArrayList
Tnx
安德里亚
-
不,这不是问题,它只是由主机名和IP(
hostname/ip
)组成的输出.您可能需要阅读的详细信息:实现了类InetAddress
中的方法toString()
以返回此格式.
No, it's not a problem, it's simply an output that consists of hostname and IP (
hostname/ip
). A detail that you might want to read up: The methodtoString()
in the classInetAddress
is implemented to return this format.
以下代码将列出系统中每个接口的所有IP地址(并将它们存储在列表中,然后您可以继续传递等等):
The following code will list all IP addresses for each of the interfaces in your system (and also stores them in a list that you could then pass on etc...):
public static void main(String[] args) throws InterruptedException, IOException
{
List<String> allIps = new ArrayList<String>();
Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
while (e.hasMoreElements())
{
NetworkInterface n = e.nextElement();
System.out.println(n.getName());
Enumeration<InetAddress> ee = n.getInetAddresses();
while (ee.hasMoreElements())
{
InetAddress i = ee.nextElement();
System.out.println(i.getHostAddress());
allIps.add(i.getHostAddress());
}
}
}
方法boolean isLoopbackAddress()
允许您过滤可能不需要的回送地址.
The method boolean isLoopbackAddress()
allows you to filter the potentially unwanted loopback addresses.
返回的InetAddress
是Inet4Address
或Inet6Address
,使用instanceof
您可以确定返回的IP是IPv4还是IPv6格式.
The returned InetAddress
is either a Inet4Address
or a Inet6Address
, using the instanceof
you can figure out if the returned IP is IPv4 or IPv6 format.