本文目录一览:
java中获取本地IP地址
方法如下:
方法一,使用CMD命令:
public static String getLocalIPForCMD(){
StringBuilder sb = new StringBuilder();
String command = "cmd.exe /c ipconfig | findstr IPv4";
try {
Process p = Runtime.getRuntime().exec(command);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while((line = br.readLine()) != null){
line = line.substring(line.lastIndexOf(":")+2,line.length());
sb.append(line);
}
br.close();
p.destroy();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
方法二,使用Java方法:
public static String getLocalIPForJava(){
StringBuilder sb = new StringBuilder();
try {
EnumerationNetworkInterface en = NetworkInterface.getNetworkInterfaces();
while (en.hasMoreElements()) {
NetworkInterface intf = (NetworkInterface) en.nextElement();
EnumerationInetAddress enumIpAddr = intf.getInetAddresses();
while (enumIpAddr.hasMoreElements()) {
InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() !inetAddress.isLinkLocalAddress()
inetAddress.isSiteLocalAddress()) {
sb.append(inetAddress.getHostAddress().toString()+"\n");
}
}
}
} catch (SocketException e) { }
return sb.toString();
}
如何用 Java 获取系统 IP
import java.net.*;
public class Test6 {
public static void main(String[] args) {
// TODO Auto-generated method stub
InetAddress ia=null;
try {
ia=ia.getLocalHost();
String localname=ia.getHostName();
String localip=ia.getHostAddress();
System.out.println("本机名称是:"+ localname);
System.out.println("本机的ip是 :"+localip);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
java如何获取用户真实的ip
1、如果服务器如果没有采用反向代理,而且客户端没有用正向代理的话,那么可以获取客户端的真实IP地址request.getRemoteAddr()
2、如果服务器如果没有采用反向代理,而且客户端有用正向代理的话,那么通过request.getRemoteAddr()获取客户端的IP地址是客户端 的代理服务器的地址,并不是客户端的真实地址,
3、如果客户端使用的是多层代理的话,服务器获得的客户端地址是客户端的最外围代理服务器的地址如果服务器如果采用反向代理服务器,不管客户端采用的是何种方式访问服务器。
//获得客户端真实IP地址的方法一:
public String getRemortIP(HttpServletRequest request) {
if (request.getHeader("x-forwarded-for") == null) {
return request.getRemoteAddr();
}
return request.getHeader("x-forwarded-for");
}
//获得客户端真实IP地址的方法二:
public String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}