在我的java RMI应用程序中,我可以拥有在本地和不同主机上充当服务器的实例。在后一种情况下,如何获取我的传出IP地址,以便将其设置为系统属性java.rmi.server.hostName的参数?
现在它很难接线,但这不是一个理想的解决方案。
答案 0 :(得分:0)
您可以使用经典的Java方式:
try {
InetAddress addr = InetAddress.getLocalHost();
// Get IP Address
byte[] ipAddr = addr.getAddress();
// Get hostname
String hostname = addr.getHostName();
} catch (UnknownHostException e) {
}
答案 1 :(得分:0)
我不明白为什么你认为你需要这个。传出存根中的源地址自动设置为主机的IP地址。您需要设置此属性的唯一时间是默认设置不正确:例如如果您有多个NIC并且只想通过一个NIC导出,或者您的Linux配置错误将主机名映射到127.0.0.1而不是您的IP地址。
答案 2 :(得分:0)
以下内容将显示主机上所有可用的非环回IPv4地址。您也可以轻松地对其进行调整以获取IPv6地址。
public static void main(String...args) {
List<InetAddress> addresses = getNonLocalIPV4Addresses();
for (InetAddress addr: addresses) {
System.out.println("address: " + addr.getHostAddress());
}
}
/**
* Get a list of all known non-local IP v4 addresses for the current host.
* @return a List of <code>InetAddress</code>, may be empty but never null.
*/
public static List<InetAddress> getNonLocalIPV4Addresses() {
return getIPAddresses(new InetAddressFilter() {
public boolean accepts(InetAddress addr) {
return (addr instanceof Inet4Address)
&& !(addr.isLoopbackAddress()) || "localhost".equals(addr.getHostName()));
}
});
}
/**
* Get a list of all known IP addresses for the current host,
* according to the specified filter.
* @param filter filters out unwanted addresses.
* @return a List of <code>InetAddress</code>, may be empty but never null.
*/
public static List<InetAddress> getIPAddresses(InetAddressFilter filter) {
List<InetAddress> list = new ArrayList<InetAddress>();
try {
Enumeration<NetworkInterface> interfaces =
NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface ni = interfaces.nextElement();
Enumeration<InetAddress> addresses = ni.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress addr = addresses.nextElement();
if ((filter == null) || filter.accepts(addr)) list.add(addr);
}
}
} catch(Exception e) {
e.printStackTrace();
}
return list;
}
/**
* Filter interface for the methods discovering available IP addresses.
*/
public interface InetAddressFilter {
/**
* Determine whether the specified address is accepted.
* @param addr the address to check.
* @return true if the address is accepted, false otherwise.
*/
boolean accepts(InetAddress addr);
}