首页 / JAVA / 使用Java的IP地址
使用Java的IP地址
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了使用Java的IP地址,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2074字,纯文字阅读大概需要3分钟。
内容图文
![使用Java的IP地址](/upload/InfoBanner/zyjiaocheng/803/8c909bdf11794488bb9c34d2706331cc.jpg)
我如何获得用户的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<NetworkInterface> ifaces =
NetworkInterface.getNetworkInterfaces();
ifaces.hasMoreElements(); )
{
NetworkInterface iface = ifaces.nextElement();
System.out.println(iface.getName() + ":");
for (Enumeration<InetAddress> 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();
}
参考文献:
> IP Address not obtained in java
> http://www.roseindia.net/java/java-get-example/get-ip-address.shtml
内容总结
以上是互联网集市为您收集整理的使用Java的IP地址全部内容,希望文章能够帮你解决使用Java的IP地址所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。