日期:2014-05-17  浏览次数:20749 次

java中如何获取客户端IP
我在用java做一个C/S的程序,想在服务器上获取客户端的IP,该如何获取?
注:客户端可能用的NAT设备,所以在客户端调用InetAddress.getLocalHost()得到的是客户端的内网ip,例如:192.168.1.12,
  而我想在服务器得到的是该用户的公网IP地址,请问谁有过类似的经验,谢谢

------解决方案--------------------
你真小气···
import java.net.URL;
import java.util.Date;
import java.io.InputStream;
import java.net.URLConnection;
import java.io.InputStreamReader;
public class GetOnerIp {
String OutPutStream = new String();
int a;
char b;
int power = 1;
String c = null;
String res;
URLConnection urlcon;
public GetOnerIp() {
}
public static void main(String[] args) {
GetOnerIp getonerip = new GetOnerIp();
try {
getonerip.chaojiip();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public String dayinji(int power, char d) {

if (power == 1) {
res = String.valueOf(d);
} else {
res = "";
}
return res;
}
public String chaojiip() throws Exception {
// TODO 自动生成方法存根
URL url = new URL("http://www.cz88.net/ip/viewip468.aspx");
System.out.println("主机:" + url.getHost());
System.out.println("路径:" + url.getPath());
System.out.println("端口:" + url.getPort());
System.out.println("文件:" + url.getFile());

urlcon = url.openConnection();
System.out.println("超时设置:" + urlcon.getConnectTimeout());
System.out.println("当前时间:" + new Date(urlcon.getLastModified()));
System.out.println("==content==");

int i = urlcon.getContentLength();
if (i > 0) {
InputStream isr = urlcon.getInputStream();
InputStreamReader is = new InputStreamReader(isr, "GB2312");


int spower = 0;
while ((a = is.read()) != -1) {
b = (char) a;
OutPutStream = OutPutStream + "" + dayinji(power, b);
c = String.valueOf(b);
if (OutPutStream.indexOf("IPMessage\">") > 0) {
OutPutStream = "";
power = 1;
spower = 1;
}
if (spower == 1) {
if (c.equalsIgnoreCase("<")) {
power = 0;
}
}
}
OutPutStream = OutPutStream.replaceAll(">", "");
OutPutStream = OutPutStream.replaceAll("", "");
OutPutStream = OutPutStream.replaceAll("<", "");
System.out.println("您的IP是:" + OutPutStream); //.replaceAll(">",""));
OutPutStream.indexOf("|");
is.close();
} else {
System.out.println("Length is null.");
}
return OutPutStream;
}
}

你看看吧··是用HttpConnection来实现的··
不过很傻···
是调取别人网页上的东西··然后进行分析···
你看看吧····
------解决方案--------------------
request.getheader(“user-agent”)返回客户端浏览器的版本号、类型

getheader(string name):获得http协议定义的传送文件头信息,

request. getmethod():获得客户端向服务器端传送数据的方法有get、post、put等类型

request. getrequesturi():获得发出请求字符串的客户端地址

request. getservletpath():获得客户端所请求的脚本文件的文件路径

request. getservername():获得服务器的名字

r