获取本机外网ip获取位置

时间:2021-02-28 10:51:15

1.思路

通过连接http://www.ip138.com/获取本机ip,然后根据本机ip获取位置

2.代码如下

package com.xiang;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class GetPlaceByIp {//获取地址
public static String getAddressByIP() {
try {
String strIP = getWebIp();
URL url = new URL("http://ip.qq.com/cgi-bin/searchip?searchip1="+ strIP);
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream(), "GBK"));
String line = null;
StringBuffer result = new StringBuffer();
while ((line = reader.readLine()) != null) {
result.append(line);
}
reader.close();
strIP = result.substring(result.indexOf("该IP所在地为:"));
strIP = strIP.substring(strIP.indexOf(":") + 1);
String province = strIP.substring(6, strIP.indexOf("省"));
String city = strIP.substring(strIP.indexOf("省") + 1, strIP
.indexOf("市"));
System.out.print(province + city);
} catch (IOException e) {
return "读取失败";
}
return "";
}

public static void main(String[] args) throws Exception {
getAddressByIP();
}

public static String getWebIp() throws IOException {//获取ip
InputStream ins = null;
try {
URL url = new URL("http://1111.ip138.com/ic.asp");
URLConnection con = url.openConnection();
ins = con.getInputStream();
InputStreamReader isReader = new InputStreamReader(ins, "GB2312");
BufferedReader bReader = new BufferedReader(isReader);
StringBuffer webContent = new StringBuffer();
String str = null;
while ((str = bReader.readLine()) != null) {
webContent.append(str);
System.out.println(str);
}
int start = webContent.indexOf("[") + 1;
int end = webContent.indexOf("]");
return webContent.substring(start, end);
} finally {
if (ins != null) {
ins.close();
}
}
}
}

3.http://1111.ip138.com/ic.asp由来

获取本机外网ip获取位置

4.运行结果

<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=gb2312">
<title> 您的IP地址 </title>
</head>
<body style="margin:0px"><center>您的IP是:[58.58.36.34] 来自:山东省青岛市 电信</center></body></html>
中国山东青岛