Java获取本地IP
我正在尝试获取本地IP。它应该与Java获取本地IP,java,ip,local,Java,Ip,Local,我正在尝试获取本地IP。它应该与 System.out.println(Inet4Address.getLocalHost().getHostAddress()); 或 但它总是返回192.168.178.154,而不是192.168.178.119(这是我真正的本地IP(终端-->ifconfig) 我该怎么办?听起来你有两个IP地址 在具有一个网络适配器的计算机上,选择的IP地址是计算机中网络适配器的主IP地址。但是,在多主机计算机上,堆栈必须首先做出选择。堆栈在知道连接的目标IP地址之前
System.out.println(Inet4Address.getLocalHost().getHostAddress());
或
但它总是返回192.168.178.154
,而不是192.168.178.119
(这是我真正的本地IP(终端-->ifconfig
)
我该怎么办?听起来你有两个IP地址 在具有一个网络适配器的计算机上,选择的IP地址是计算机中网络适配器的主IP地址。但是,在多主机计算机上,堆栈必须首先做出选择。堆栈在知道连接的目标IP地址之前无法做出智能选择 当程序向目标IP地址发送connect()调用,或向UDP数据报发送send()调用时,堆栈引用目标IP地址,然后检查IP路由表,以便选择发送数据包的最佳网络适配器。选择此网络适配器后,堆栈读取与该网络适配器关联的主IP地址,并将该IP地址用作出站数据包的源IP地址
如果您想激活第二个IP及其示例LAN,请将其拔下,10秒后重新插入。其他IP可能被选为路由表中的主机IP 您可以从
getNetworkInterfaces
获得第二个IP
尝试运行以下代码:
public static void main(String[] args) throws Exception
{
System.out.println("Your Host addr: " + InetAddress.getLocalHost().getHostAddress()); // often returns "127.0.0.1"
Enumeration<NetworkInterface> n = NetworkInterface.getNetworkInterfaces();
for (; n.hasMoreElements();)
{
NetworkInterface e = n.nextElement();
Enumeration<InetAddress> a = e.getInetAddresses();
for (; a.hasMoreElements();)
{
InetAddress addr = a.nextElement();
System.out.println(" " + addr.getHostAddress());
}
}
}
publicstaticvoidmain(字符串[]args)引发异常
{
System.out.println(“您的主机地址:+InetAddress.getLocalHost().getHostAddress());//通常返回“127.0.0.1”
枚举n=NetworkInterface.getNetworkInterfaces();
对于(;n.hasMoreElements();)
{
网络接口e=n.nextElement();
枚举a=e.getInetAddresses();
对于(;a.hasMoreElements();)
{
InetAddress addr=a.nextElement();
System.out.println(“+addr.getHostAddress());
}
}
}
如果您的系统配置了多个ip,请执行以下操作
try {
InetAddress inet = InetAddress.getLocalHost();
InetAddress[] ips = InetAddress.getAllByName(inet.getCanonicalHostName());
if (ips != null ) {
for (int i = 0; i < ips.length; i++) {
System.out.println(ips[i]);
}
}
} catch (UnknownHostException e) {
}
试试看{
InetAddress inet=InetAddress.getLocalHost();
InetAddress[]ips=InetAddress.getAllByName(inet.getCanonicalHostName());
如果(ips!=null){
对于(int i=0;i
您有Lan和WiFi吗?WiFi,但它应该可以同时使用。好的,谢谢:),您知道是否有可能获得第二个Ip吗?如果您想激活第二个Ip及其Lan,请拔下它,10秒后再插回。它将切换到第二个地址作为主机问题是,程序应该知道它应该使用哪个Ip。嗯,你有路由表,电脑使用的是“最旧”的接口,它有互联网。不,这不是代码问题,只是你电脑的路由表是的,这会返回3个ip…@Tyratox列表中有192.168.178.119 ip吗?是的:)但顺序并不总是一样的:/
try {
InetAddress inet = InetAddress.getLocalHost();
InetAddress[] ips = InetAddress.getAllByName(inet.getCanonicalHostName());
if (ips != null ) {
for (int i = 0; i < ips.length; i++) {
System.out.println(ips[i]);
}
}
} catch (UnknownHostException e) {
}