㈠ java怎么获取请求的ip
java获取外网ip地址方法:
public class Main {
public static void main(String[] args) throws SocketException {
System.out.println(Main.getRealIp());
}
public static String getRealIp() throws SocketException {
String localip = null;// 本地IP,如果没有配置外网IP则返回它
String netip = null;// 外网IP
Enumeration<NetworkInterface> netInterfaces =
NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
boolean finded = false;// 是否找到外网IP
while (netInterfaces.hasMoreElements() && !finded) {
NetworkInterface ni = netInterfaces.nextElement();
Enumeration<InetAddress> address = ni.getInetAddresses();
while (address.hasMoreElements()) {
ip = address.nextElement();
if (!ip.isSiteLocalAddress()
&& !ip.isLoopbackAddress()
&& ip.getHostAddress().indexOf(":") == -1) {// 外网IP
netip = ip.getHostAddress();
finded = true;
break;
} else if (ip.isSiteLocalAddress()
&& !ip.isLoopbackAddress()
&& ip.getHostAddress().indexOf(":") == -1) {// 内网IP
localip = ip.getHostAddress();
}
}
}
if (netip != null && !"".equals(netip)) {
return netip;
} else {
return localip;
}
}
}
㈡ 关于java web获取客户端ip地址的方法
request.getRemoteAddr()是获得客户端的ip地址。
request.getRemoteHost()是获得客户端的主机名。
㈢ 请问java获取请求对象的电脑ip和网络ip的方法是什么
importjava.io.*;
importjava.net.*;
try{
URLurl=newURL("http://checkip.amazonaws.com");
BufferedReaderbr=newBufferedReader(newInputStreamReader(url.openStream()));
StringwanIP=br.readLine();
System.out.println("WANIP:"+wanIP);
InetAddresslanIP=Inet4Address.getLocalHost();//orInet6Address.getLocalHost();
System.out.println("LANIP:"+lanIP.getHostAddress());
}catch(Exceptione){
e.printStackTrace();
}