㈠ 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();
}