Getting the 'external' IP address in Java

2019-01-01 00:37发布

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.

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;
    }
}

11条回答
低头抚发
2楼-- · 2019-01-01 01:08

The truth is, 'you can't' in the sense that you posed the question. NAT happens outside of the protocol. There is not way for your machine's kernel to know how your NAT box is mapping from external to internal IP addressees. Other answers here offer tricks involving methods of talking to outside web sites.

查看更多
泪湿衣
3楼-- · 2019-01-01 01:16

All this are still up and working smoothly! (as of 19 Dec 2016)

Piece of advice: Do not direcly depend only on one of them; try to use one but have a contigency plan considering others! The more you use, the better!

Good luck!

查看更多
浮光初槿花落
4楼-- · 2019-01-01 01:17

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

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()

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

Use a webservice like AWS and others

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);
查看更多
与君花间醉酒
5楼-- · 2019-01-01 01:23

It's not that easy since a machine inside a LAN usually doesn't care about the external IP of its router to the internet.. it simply doesn't need it!

I would suggest you to exploit this by opening a site like http://www.whatismyip.com/ and getting the IP number by parsing the html results.. it shouldn't be that hard!

查看更多
谁念西风独自凉
6楼-- · 2019-01-01 01:24

Make a HttpURLConnection to some site like www.whatismyip.com and parse that :-)

查看更多
孤独总比滥情好
7楼-- · 2019-01-01 01:24

http://jstun.javawi.de/ will do it - provided your gateway device does STUN )most do)

查看更多
登录 后发表回答