在 Java 中获取“外部"IP 地址 [英] Getting the 'external' IP address in Java

查看:31
本文介绍了在 Java 中获取“外部"IP 地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不太确定如何获取机器的外部 IP 地址,因为网络外部的计算机会看到它.

I'm not too sure how to go about getting the external IP address of the machine as a computer outside of a network would see it.

我下面的IPAddress类只获取机器的本地IP地址.

My following IPAddress class only gets the local IP address of the machine.

public class IPAddress {

    private InetAddress thisIp;

    private String thisIpAddress;

    private void setIpAdd() {
        try {
            InetAddress thisIp = InetAddress.getLocalHost();
            thisIpAddress = thisIp.getHostAddress().toString();
        } catch (Exception e) {
        }
    }

    protected String getIpAddress() {
        setIpAdd();
        return thisIpAddress;
    }
}

推荐答案

我不确定您是否可以从本地机器上运行的代码中获取该 IP.

I am not sure if you can grab that IP from code that runs on the local machine.

然而,您可以构建在网站上运行的代码,比如在 JSP 中,然后使用返回请求来源 IP 的内容:

You can however build code that runs on a website, say in JSP, and then use something that returns the IP of where the request came from:

request.getRemoteAddr()

或者简单地使用已经存在的服务来执行此操作,然后从服务中解析答案以找出 IP.

Or simply use already-existing services that do this, then parse the answer from the service to find out the IP.

使用 AWS 等网络服务

import java.net.*;
import java.io.*;

URL whatismyip = new URL("http://checkip.amazonaws.com");
BufferedReader in = new BufferedReader(new InputStreamReader(
                whatismyip.openStream()));

String ip = in.readLine(); //you get the IP as a String
System.out.println(ip);

这篇关于在 Java 中获取“外部"IP 地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆