java IP查询方法

Python013

java IP查询方法,第1张

Java编程查询IP地址归属地,可以调用淘宝提供的service查询,并且解析http请求返回的json串,代码如下:

package getAddressByIp

import java.io.ByteArrayOutputStream

import java.io.IOException

import java.io.InputStream

import java.net.HttpURLConnection

import java.net.MalformedURLException

import java.net.URL

import net.sf.json.JSONObject

 

public class GetAddressByIp

{        

    /**

     * 

     * @param IP

     * @return

     */

    public static String GetAddressByIp(String IP){

        String resout = ""

        try{

         String str = getJsonContent("http://ip.taobao.com/service/getIpInfo.php?ip="+IP)

         System.out.println(str)

         JSONObject obj = JSONObject.fromObject(str)

         JSONObject obj2 =  (JSONObject) obj.get("data")

         String code = (String) obj.get("code")

         if(code.equals("0")){

             resout =  obj2.get("country")+"--" +obj2.get("area")+"--" +obj2.get("city")+"--" +obj2.get("isp")

         }else{

             resout =  "IP地址有误"

         }

        }catch(Exception e){

             

            e.printStackTrace()

             resout = "获取IP地址异常:"+e.getMessage()

        }

        return resout

          

    }

    

    public static String getJsonContent(String urlStr)

    {

        try

        {// 获取HttpURLConnection连接对象

            URL url = new URL(urlStr)

            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection()

            // 设置连接属性

            httpConn.setConnectTimeout(3000)

            httpConn.setDoInput(true)

            httpConn.setRequestMethod("GET")

            // 获取相应码

            int respCode = httpConn.getResponseCode()

            if (respCode == 200)

            {

                return ConvertStream2Json(httpConn.getInputStream())

            }

        }

        catch (MalformedURLException e)

        {

            e.printStackTrace()

        }

        catch (IOException e)

        {

            e.printStackTrace()

        }

        return ""

    }

    

    private static String ConvertStream2Json(InputStream inputStream)

    {

        String jsonStr = ""

        // ByteArrayOutputStream相当于内存输出流

        ByteArrayOutputStream out = new ByteArrayOutputStream()

        byte[] buffer = new byte[1024]

        int len = 0

        // 将输入流转移到内存输出流中

        try

        {

            while ((len = inputStream.read(buffer, 0, buffer.length)) != -1)

            {

                out.write(buffer, 0, len)

            }

            // 将内存流转换为字符串

            jsonStr = new String(out.toByteArray())

        }

        catch (IOException e)

        {

            // TODO Auto-generated catch block

            e.printStackTrace()

        }

        return jsonStr

    }

}

java获取本机的外网ip示例:

import java.io.IOException

import java.io.InputStream

import java.net.HttpURLConnection

import java.net.MalformedURLException

import java.net.URL

import java.util.regex.Matcher

import java.util.regex.Pattern

/**

* 获取本机外网IP地址

* 思想是访问网站http://checkip.dyndns.org/,得到返回的文本后解析出本机在外网的IP地址

* @author pieryon

*

*/

public class ExternalIpAddressFetcher {

// 外网IP提供者的网址

private String externalIpProviderUrl

// 本机外网IP地址

private String myExternalIpAddress

public ExternalIpAddressFetcher(String externalIpProviderUrl) {

this.externalIpProviderUrl = externalIpProviderUrl

String returnedhtml = fetchExternalIpProviderHTML(externalIpProviderUrl)

parse(returnedhtml)

}

/**

* 从外网提供者处获得包含本机外网地址的字符串

* 从http://checkip.dyndns.org返回的字符串如下

* <html><head><title>Current IP Check</title></head><body>Current IP Address: 123.147.226.222</body></html>

* @param externalIpProviderUrl

* @return

*/

private String fetchExternalIpProviderHTML(String externalIpProviderUrl) {

// 输入流

InputStream in = null

// 到外网提供者的Http连接

HttpURLConnection httpConn = null

try {

// 打开连接

URL url = new URL(externalIpProviderUrl)

httpConn = (HttpURLConnection) url.openConnection()

// 连接设置

HttpURLConnection.setFollowRedirects(true)

httpConn.setRequestMethod("GET")

httpConn.setRequestProperty("User-Agent",

"Mozilla/4.0 (compatibleMSIE 6.0Windows 2000)")

// 获取连接的输入流

in = httpConn.getInputStream()

byte[] bytes=new byte[1024]// 此大小可根据实际情况调整

// 读取到数组中

int offset = 0

int numRead = 0

while (offset <bytes.length

&&(numRead=in.read(bytes, offset, bytes.length-offset)) >= 0) {

offset += numRead

}

// 将字节转化为为UTF-8的字符串

String receivedString=new String(bytes,"UTF-8")

// 返回

return receivedString

} catch (MalformedURLException e) {

e.printStackTrace()

} catch (IOException e) {

e.printStackTrace()

} finally {

try {

in.close()

httpConn.disconnect()

} catch (Exception ex) {

ex.printStackTrace()

}

}

// 出现异常则返回空

return null

}

/**

* 使用正则表达式解析返回的HTML文本,得到本机外网地址

* @param html

*/

private void parse(String html){

Pattern pattern=Pattern.compile("(\\d{1,3})[.](\\d{1,3})[.](\\d{1,3})[.](\\d{1,3})", Pattern.CASE_INSENSITIVE)

Matcher matcher=pattern.matcher(html)

while(matcher.find()){

myExternalIpAddress=matcher.group(0)

}

}

/**

* 得到本机外网地址,得不到则为空

* @return

*/

public String getMyExternalIpAddress() {

return myExternalIpAddress

}

public static void main(String[] args){

ExternalIpAddressFetcher fetcher=new ExternalIpAddressFetcher("http://checkip.dyndns.org/")

System.out.println(fetcher.getMyExternalIpAddress())

}

}

要解决这个问题,首先要明白域名与ip之间的联系。

我们平时在配置本地ip的时候,都会有一个dns,dns的作用就是将域名解析为ip后,找到对应的ip地址上对应的内容,然后在页面打开展示给你。

你现在想要通过ip来得到域名的话,有两种方式:

一种是你找到一个ip与域名对应的数据,然后根据这个数据来查找;

另外的话就是找一下,看看网络上是否有使用ip来查询并返回域名的接口。

通过这个接口来实现域名反查,但是这种接口一般都是专门做ip解析的公司内部使用的,像万网之类的,像ping和tracert返回的数据都是返回的ip的,不会有域名返回来的。