我不太确定如何获取机器的外部IP地址,因为网络之外的计算机会看到它。
下面的IPAddress类只获取机器的本地IP地址。
public class IPAddress {
private InetAddress thisIp;
private String thisIpAddress;
private void setIpAdd() {
try {
InetAddress thisIp = InetAddress.getLocalHost();
thisIpAddress = thisIp.getHostAddress().toString();
} catch (Exception e) {
}
}
protected String getIpAddress() {
setIpAdd();
return thisIpAddress;
}
}
发布于 2013-01-27 04:41:57
@stivlo的其中一条评论值得一提:
您可以使用亚马逊服务http://checkip.amazonaws.com
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
public class IpChecker {
public static String getIp() throws Exception {
URL whatismyip = new URL("http://checkip.amazonaws.com");
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(
whatismyip.openStream()));
String ip = in.readLine();
return ip;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
发布于 2010-05-30 23:33:24
事实是:从你提出问题的意义上说,“你不能”。NAT发生在协议之外。您的机器内核无法知道您的NAT盒是如何从外部IP地址映射到内部IP地址的。这里的其他答案提供了一些技巧,包括与外部网站交谈的方法。
发布于 2012-07-30 20:09:33
正如@Donal Fellows所写的,你必须查询网络接口而不是机器。javadocs中的这段代码对我很有效:
以下示例程序列出了计算机上的所有网络接口及其地址:
import java.io.*;
import java.net.*;
import java.util.*;
import static java.lang.System.out;
public class ListNets {
public static void main(String args[]) throws SocketException {
Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
for (NetworkInterface netint : Collections.list(nets))
displayInterfaceInformation(netint);
}
static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
out.printf("Display name: %s\n", netint.getDisplayName());
out.printf("Name: %s\n", netint.getName());
Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
for (InetAddress inetAddress : Collections.list(inetAddresses)) {
out.printf("InetAddress: %s\n", inetAddress);
}
out.printf("\n");
}
}
以下是示例程序的示例输出:
Display name: TCP Loopback interface
Name: lo
InetAddress: /127.0.0.1
Display name: Wireless Network Connection
Name: eth0
InetAddress: /192.0.2.0
https://stackoverflow.com/questions/2939218
复制相似问题