java中,如何获取真实的IP地址

java中,如何获取真实的IP地址,第1张

/

获取客户端ip

@param request

@return

/

>

import javaio;

import javanet;

try {

URL url = new URL(">

public static String getHostIpAddress() {

String hostIp = "";

InetAddress netAddress = getInetAddress();

hostIp = getHostIp(netAddress);

return hostIp;

}

public static InetAddress getInetAddress() {

try {

return InetAddressgetLocalHost();

} catch (UnknownHostException e) {

Systemoutprintln("unknown host!");

}

return null;

}

public static String getHostIp(InetAddress netAddress) {

if (null == netAddress) {

return null;

}

String ip = netAddressgetHostAddress(); // get the ip address

return ip;

}

public static String getHostName(InetAddress netAddress) {

if (null == netAddress) {

return null;

}

String name = netAddressgetHostName(); // get the host address

return name;

}

楼上的方法是不合理的。第一,如果用户使用代理,是无法获得真实Ip的0;第二,IF语句不能保证禁止IP,而且很多网站并不需要登录的。给楼主些方法,可供参考。

1。 获取用户IP

public String getRemortIP(>

方法如下:

方法一,使用CMD命令:

public static String getLocalIPForCMD(){

StringBuilder sb = new StringBuilder();

String command = "cmdexe /c ipconfig | findstr IPv4";

try {

Process p = RuntimegetRuntime()exec(command);

BufferedReader br = new BufferedReader(new InputStreamReader(pgetInputStream()));

String line = null;

while((line = brreadLine()) != null){

line = linesubstring(linelastIndexOf(":")+2,linelength());

sbappend(line);

}

brclose();

pdestroy();

} catch (IOException e) {

eprintStackTrace();

}

return sbtoString();

}

方法二,使用Java方法:

public static String getLocalIPForJava(){

StringBuilder sb = new StringBuilder();

try {

Enumeration<NetworkInterface> en = NetworkInterfacegetNetworkInterfaces();

while (enhasMoreElements()) {

NetworkInterface intf = (NetworkInterface) ennextElement();

Enumeration<InetAddress> enumIpAddr = intfgetInetAddresses();

while (enumIpAddrhasMoreElements()) {

InetAddress inetAddress = (InetAddress) enumIpAddrnextElement();

if (!inetAddressisLoopbackAddress() && !inetAddressisLinkLocalAddress()

&& inetAddressisSiteLocalAddress()) {

sbappend(inetAddressgetHostAddress()toString()+"\n");

}

}

}

} catch (SocketException e) { }

return sbtoString();

}

以上就是关于java中,如何获取真实的IP地址全部的内容,包括:java中,如何获取真实的IP地址、本地java应用怎么代理到阿里云负载均衡让外界访问、请问java获取请求对象的电脑ip和网络ip的方法是什么等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/10137043.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-05
下一篇 2023-05-05

发表评论

登录后才能评论

评论列表(0条)

保存