1

How do i get the Wide Area Network of my computer with Java? I try with this:

ServerSocket ss = new ServerSocket(port);
System.out.println(ss.getInetAddress().getHostAddress());
//wich return 0.0.0.0

then i try with this:

System.out.println(InetAddress.getLocalHost().toString());
//which return keenan-a658368c/192.168.1.100 < yes it is connected to router

like the function said, it return my local IP address

How do i get the WAN IP Address? such as 118.137.43.219

4

5 回答 5

2

如果您最终使用了回复您的“外部 IP 地址”的远程服务(请参阅其他答案以了解它的定义),请不要使用免费的无名地址之一。部署你自己的。您不得构建依赖于某人的Acme Whats-My-IP 3000的应用程序,该应用程序可能会在不通知您或任何其他不幸用户的情况下随时消失。

于 2010-10-07T15:44:14.047 回答
2

您可以从http://whatismyip.com/automation/n09230945.asp获得它。您可以打开到该站点的 HttpURLConnection 并解析输出。

这个程序应该是有帮助的:

import java.net.HttpURLConnection;

public class GetExternalIp {

    public static void main(String args[]) {
        try {

            java.net.URL url = new java.net.URL(
                    "http://whatismyip.com/automation/n09230945.asp");

            java.net.HttpURLConnection con = (HttpURLConnection) url
                    .openConnection();

            java.io.InputStream stream = con.getInputStream();

            java.io.InputStreamReader reader = new java.io.InputStreamReader(
                    stream);

            java.io.BufferedReader bReader = new java.io.BufferedReader(reader);

            System.out.print("Your IP address is " + bReader.readLine());

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

引用自:

http://www.daniweb.com/forums/thread192872.html

http://www.coderanch.com/t/411356/java/java/Public-IP-Address-time-limit

于 2010-10-07T15:27:06.067 回答
1

如评论中所述,如果您在执行 NAT 的路由器后面,您的机器将不知道其 WAN 地址。

更复杂的情况是您位于 NAT 池后面。如果这是真的,那么您的 WAN 地址可能会定期更改,可能每天一次或更频繁。

或者某些类型的流量可能会强制通过代理。这可能使出站 HTTP 请求来自与 SSH 或其他任意协议不同的 WAN 地址。

于 2010-10-07T15:01:37.157 回答
0

一般来说,任何依赖于这样做的代码都存在设计错误——您能否详细说明为什么需要获取其 NAT 路由器的出口 IP 地址?

出口 IP 地址根本不会帮助您创建回连接,因为路由器通常不会将其转发到适当的内部主机。

于 2010-10-07T15:39:04.803 回答
0

获取计算机主接口的 IP 地址:

InetAddress.getLocalHost().getHostAddress()

获取所有接口的 IP 地址:

List<InetAddress> addresses = new LinkedList<InetAddress>();
Enumeration<NetworkInterface> ifcs = NetworkInterface.getNetworkInterfaces();
while (ifcs.hasMoreElements()) {
    NetworkInterface ifc = ifcs.nextElement();
    for (InterfaceAddress ifcAddr : ifc.getInterfaceAddresses()) {
        addresses.add(ifcAddr.getAddress());
    }
}

要获取 Internet 上的其他计算机会看到来自您计算机的连接的 IP 地址,请使用 YoK 的答案。

于 2010-10-07T18:50:45.297 回答