您的位置:

Java获取当前IP的方法

一、使用InetAddress获取本机IP地址

Java提供了InetAddress类来获取本机IP地址。通过调用getLocalHost方法可以获取本机的InetAddress对象,然后可以通过getHostAddress方法获取IP地址。

import java.net.InetAddress;

public class GetIPAddress {

    public static void main(String[] args) throws Exception {
        InetAddress address = InetAddress.getLocalHost();
        System.out.println("本机 IP 地址:" + address.getHostAddress());
    }

}

二、通过Socket获取本机IP地址

通过Tcp Socket可以获取本机IP地址。创建一个Tcp Socket对象后,调用其getLocalAddress方法即可获取本机IP地址。

import java.net.Socket;

public class GetIPAddress {

    public static void main(String[] args) throws Exception {
        Socket socket = new Socket();
        String ip = socket.getLocalAddress().getHostAddress();
        System.out.println("本机 IP 地址:" + ip);
    }

}

三、使用NetworkInterface获取本机IP地址

Java提供了NetworkInterface类来操作网络接口,可以通过NetworkInterface获取本机IP地址。

import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class GetIPAddress {

    public static void main(String[] args) throws SocketException {
        Enumeration networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = networkInterfaces.nextElement();
            Enumeration
    inetAddresses = networkInterface.getInetAddresses();
            while (inetAddresses.hasMoreElements()) {
                InetAddress inetAddress = inetAddresses.nextElement();

                if (!inetAddress.isLinkLocalAddress() && !inetAddress.isLoopbackAddress()
                        && inetAddress.isSiteLocalAddress()) {
                    System.out.println("本机 IP 地址:" + inetAddress.getHostAddress());
                }
            }
        }
    }

}

   
  

四、使用HttpClient获取外网IP地址

使用HttpClient发起网络请求,可以获取外网IP地址。通过访问带有IP地址信息的网页,可以获取当前机器的外网IP地址。

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;

public class GetIPAddress {

    public static void main(String[] args) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet("http://pv.sohu.com/cityjson?ie=utf-8");

        CloseableHttpResponse response = httpClient.execute(httpGet);
        String content = EntityUtils.toString(response.getEntity());

        int start = content.indexOf("\"cip\":") + 7;
        int end = content.indexOf("\",\"cid\"");

        System.out.println("本机 IP 地址:" + content.substring(start, end));
    }

}

五、使用第三方API获取外网IP地址

通过调用第三方API,可以获取当前机器的外网IP地址。如:http://httpbin.org/ip、http://ip.taobao.com/service/getIpInfo.php,这些API返回的都是JSON格式数据。

import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class GetIPAddress {

    public static void main(String[] args) throws Exception {
        String urlStr = "http://httpbin.org/ip";
        URL url = new URL(urlStr);
        URLConnection urlConnection = url.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        String content = "";

        String line;
        while ((line = in.readLine()) != null) {
            content += line;
        }

        JSONObject jsonObject = JSONObject.parseObject(content);
        System.out.println("本机 IP 地址:" + jsonObject.getString("origin"));
    }

}

六、小结

以上是Java获取当前IP地址的几种方法,不同的场景可以使用不同的方法。如果只是需要获取本机IP地址,可以使用 InetAddress 或 Socket;如果需要获取外网IP地址,可以使用 HttpClient 或第三方 API。