Program Tip

자바에서 '외부'IP 주소 얻기

programtip 2020. 9. 25. 23:31
반응형

자바에서 '외부'IP 주소 얻기


네트워크 외부의 컴퓨터에서 볼 수 있으므로 컴퓨터의 외부 IP 주소를 얻는 방법을 잘 모르겠습니다.

내 다음 IPAddress 클래스는 컴퓨터의 로컬 IP 주소 만 가져옵니다.

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를 가져올 수 있는지 확실하지 않습니다.

그러나 JSP와 같이 웹 사이트에서 실행되는 코드를 빌드 한 다음 요청이 발생한 IP를 반환하는 코드를 사용할 수 있습니다.

request.getRemoteAddr()

또는 단순히이를 수행하는 기존 서비스를 사용한 다음 서비스에서 응답을 구문 분석하여 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);

@stivlo의 댓글 중 하나가 답이 될 가치가 있습니다.

Amazon 서비스 http://checkip.amazonaws.com을 사용할 수 있습니다 .

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

public class IpChecker {

    public static String getIp() throws Exception {
        URL whatismyip = new URL("http://checkip.amazonaws.com");
        BufferedReader in = null;
        try {
            in = new BufferedReader(new InputStreamReader(
                    whatismyip.openStream()));
            String ip = in.readLine();
            return ip;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

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.


As @Donal Fellows wrote, you have to query the network interface instead of the machine. This code from the javadocs worked for me:

The following example program lists all the network interfaces and their addresses on a machine:

import java.io.*;
import java.net.*;
import java.util.*;
import static java.lang.System.out;

public class ListNets {

    public static void main(String args[]) throws SocketException {
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface netint : Collections.list(nets))
            displayInterfaceInformation(netint);
    }

    static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
        out.printf("Display name: %s\n", netint.getDisplayName());
        out.printf("Name: %s\n", netint.getName());
        Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
        for (InetAddress inetAddress : Collections.list(inetAddresses)) {
            out.printf("InetAddress: %s\n", inetAddress);
        }
        out.printf("\n");
     }
} 

The following is sample output from the example program:

Display name: TCP Loopback interface
Name: lo
InetAddress: /127.0.0.1

Display name: Wireless Network Connection
Name: eth0
InetAddress: /192.0.2.0

From docs.oracle.com


All this are still up and working smoothly! (as of 23 Sep 2019)

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!


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


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


How about this? It's simple and worked the best for me :)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;


public class IP {
    public static void main(String args[]) {
        new IP();
    }

    public IP() {
        URL ipAdress;

        try {
            ipAdress = new URL("http://myexternalip.com/raw");

            BufferedReader in = new BufferedReader(new InputStreamReader(ipAdress.openStream()));

            String ip = in.readLine();
            System.out.println(ip);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

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!


If you are using JAVA based webapp and if you want to grab the client's (One who makes the request via a browser) external ip try deploying the app in a public domain and use request.getRemoteAddr() to read the external IP address.


System.out.println(pageCrawling.getHtmlFromURL("http://ipecho.net/plain"));

참고URL : https://stackoverflow.com/questions/2939218/getting-the-external-ip-address-in-java

반응형