java获取本地ip地址,Java获得本地IP

Im trying to get the local IP. It should work with

System.out.println(Inet4Address.getLocalHost().getHostAddress());

or

InetAddress addr = InetAddress.getLocalHost();

ip = addr.getHostAddress();

System.out.println("Ip: " + ip);

but it always returns 192.168.178.154 instead of 192.168.178.119(This is my real local IP(Terminal --> ifconfig))

What should I do?

解决方案

Sounds like you have two IP addresses.

On a computer that has one network adapter, the IP address that is chosen is the Primary IP address of the network adaptor in the computer. However, on a multiple-homed computer, the stack must first make a choice. The stack cannot make an intelligent choice until it knows the target IP address for the connection.

When the program sends a connect() call to a target IP address, or sends a send() call to a UDP datagram, the stack references the target IP address, and then examines the IP route table so that it can choose the best network adapter over which to send the packet. After this network adapter has been chosen, the stack reads the Primary IP address associated with that network adapter and uses that IP address as the source IP address for the outbound packets.

If you want to activate second IP and its for example LAN, unplug it and after 10 sec plug in back. Other IP might be selected as host IP in routing table.

You can get 2nd IP from getNetworkInterfaces.

Try to run followed code:

public static void main(String[] args) throws Exception

{

System.out.println("Your Host addr: " + InetAddress.getLocalHost().getHostAddress()); // often returns "127.0.0.1"

Enumeration n = NetworkInterface.getNetworkInterfaces();

for (; n.hasMoreElements();)

{

NetworkInterface e = n.nextElement();

Enumeration a = e.getInetAddresses();

for (; a.hasMoreElements();)

{

InetAddress addr = a.nextElement();

System.out.println(" " + addr.getHostAddress());

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值