ip地址java_使用Java的IP地址

我如何获得用户的IP地址?

InetAddress ip;

try {

ip = InetAddress.getLocalHost();

System.out.println("Current IP address : " + ip.getHostAddress());

} catch (UnknownHostException e) {

e.printStackTrace();

}

返回:127.0.0.1

我知道那不是我的IP.这是我的本地IP地址.如何使用java获取用户IP ..?

解决方法:

最短的方法是:

try {

InetAddress thisIp =InetAddress.getLocalHost();

System.out.println("IP:"+thisIp.getHostAddress());

}

catch(Exception e) {

e.printStackTrace();

}

但是getLocalHost文档说:

If there is a security manager, its checkConnect method is called with

the local host name and -1 as its arguments to see if the operation is

allowed. If the operation is not allowed, an InetAddress representing

the loopback address is returned.

在某些情况下,InetAddress.getLocalHost()不会查询您的接口,它只返回常量127.0.0.1(对于IPv4))

我认为NetworkInterface.getNetworkInterfaces是你需要枚举所有可能性的东西.这是一个不显示虚拟地址的示例,但适用于“主要”接口:

import java.net.*;

import java.util.*;

public class Test

{

public static void main(String[] args)

throws Exception // Just for simplicity

{

for (Enumeration ifaces =

NetworkInterface.getNetworkInterfaces();

ifaces.hasMoreElements(); )

{

NetworkInterface iface = ifaces.nextElement();

System.out.println(iface.getName() + ":");

for (Enumeration addresses =

iface.getInetAddresses();

addresses.hasMoreElements(); )

{

InetAddress address = addresses.nextElement();

System.out.println(" " + address);

}

}

}

}

或者:

尝试使用此功能(首先输出应该是PC名称后的IP):

InetAddress[] localaddr;

String computername = null;

try {

computername = InetAddress.getLocalHost().getHostName();//get pc name

} catch (UnknownHostException ex) {

ex.printStackTrace();

}

System.out.println(computername);

try {

localaddr = InetAddress.getAllByName(computername);

for (int i = 0; i < localaddr.length; i++) {

System.out.println("\n" + localaddr[i].getHostAddress());

}

} catch (UnknownHostException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

参考文献:

标签:java,ip-address,ip

来源: https://codeday.me/bug/20190613/1232217.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值