Java에서 내 라우터/게이트웨이의 IP를 어떻게 확인할 수 있나요?

StackOverflow https://stackoverflow.com/questions/11930

  •  08-06-2019
  •  | 
  •  

문제

Java에서 내 라우터/게이트웨이의 IP를 어떻게 확인할 수 있나요?내 IP를 충분히 쉽게 얻을 수 있습니다.웹사이트의 서비스를 사용하여 인터넷 IP를 얻을 수 있습니다.하지만 게이트웨이의 IP를 어떻게 확인할 수 있나요?

방법을 알고 있다면 .NET에서는 다소 쉽습니다.그런데 Java에서는 어떻게 합니까?

도움이 되었습니까?

해결책

불행히도 Java는 다른 언어만큼 이를 즐겁게 만들지 않습니다.내가 한 일은 다음과 같습니다.

import java.io.*;
import java.util.*;

public class ExecTest {
    public static void main(String[] args) throws IOException {
        Process result = Runtime.getRuntime().exec("traceroute -m 1 www.amazon.com");

        BufferedReader output = new BufferedReader(new InputStreamReader(result.getInputStream()));
        String thisLine = output.readLine();
        StringTokenizer st = new StringTokenizer(thisLine);
        st.nextToken();
        String gateway = st.nextToken();
        System.out.printf("The gateway is %s\n", gateway);
    }
}

이는 게이트웨이가 세 번째 토큰이 아니라 두 번째 토큰이라고 가정합니다.그렇다면 추가사항을 추가해야 합니다. st.nextToken(); 토크나이저를 한 단계 더 발전시킵니다.

다른 팁

Windows, OSX, Linux 등에서 다음을 사용하면 Chris Bunch의 답변이 훨씬 향상될 수 있습니다.

netstat -rn

대신에 traceroute 명령.

게이트웨이의 IP 주소는 다음 중 하나로 시작하는 줄의 두 번째 필드에 나타납니다. default 또는 0.0.0.0.

이는 사용하려고 할 때 여러 가지 문제를 해결합니다. traceroute:

  1. 윈도우즈에서 traceroute 실제로는 tracert.exe, 따라서 코드에 O/S 종속성이 필요하지 않습니다.
  2. 실행하는 빠른 명령입니다. 네트워크가 아닌 O/S에서 정보를 가져옵니다.
  3. traceroute 가끔 네트워크에 의해 차단되는 경우가 있습니다

유일한 단점은 계속해서 줄을 읽어야 한다는 것입니다. netstat 출력 라인이 두 개 이상이기 때문에 올바른 라인을 찾을 때까지 출력합니다.

편집하다: 기본 게이트웨이의 IP 주소는 MAC(Lion에서 테스트)에 있는 경우 'default'로 시작하는 줄의 두 번째 필드에 있습니다. 세 번째 필드 '0.0.0.0'으로 시작하는 줄 (Windows 7에서 테스트)

윈도우:

네트워크 대상 넷마스크 게이트웨이 인터페이스 메트릭

0.0.0.0 0.0.0.0 192.168.2.254 192.168.2.46 10

맥:

대상 게이트웨이 플래그 참조 Netif Expire 사용

기본 192.168.2.254 UGSc 104 4 ko1

try{
    Process result = Runtime.getRuntime().exec("netstat -rn");

    BufferedReader output = new BufferedReader(new InputStreamReader(result.getInputStream()));

    String line = output.readLine();
    while(line != null){
        if ( line.startsWith("default") == true )
            break;      
        line = output.readLine();
    }

    StringTokenizer st = new StringTokenizer( line );
    st.nextToken();
    gateway = st.nextToken();
    st.nextToken();
    st.nextToken();
    st.nextToken();
    adapter = st.nextToken();

} catch( Exception e ) { 
    System.out.println( e.toString() );
    gateway = new String();
    adapter = new String();
}

Windows에서 IPConfig의 출력을 구문 분석하면 추적을 기다리지 않고 기본 게이트웨이를 얻을 수 있습니다.

공용 IP 주소를 결정하는 checkmyip.org와 같은 사이트를 사용하는 것이 더 나을 수 있습니다. 반드시 첫 번째 홉 라우터일 필요는 없습니다.Uni에는 "실제" IP 주소가 있지만 집에서는 로컬 라우터의 공용 IP 주소입니다.

반환되는 페이지를 구문 분석하거나 IP 주소를 유일한 문자열로 다시 가져올 수 있는 다른 사이트를 찾을 수 있습니다.

(내 말은 이 URL을 Java/무엇이든 로드한 다음 필요한 정보를 얻으라는 의미입니다.)

이는 완전히 플랫폼 독립적이어야 합니다.

UPnP 관련:모든 라우터가 UPnP를 지원하는 것은 아닙니다.그리고 그렇게 하는 경우 (보안상의 이유로) 전원을 끌 수 있습니다.따라서 귀하의 솔루션이 항상 작동하지 않을 수도 있습니다.

NatPMP도 살펴봐야 합니다.

UPnP를 위한 간단한 라이브러리는 다음에서 찾을 수 있습니다. http://miniupnp.free.fr/, 비록 C에 있지만 ...

Traceroute(ICMP 기반, 광역 적중)에서 언급된 문제를 극복하려면 다음을 고려할 수 있습니다.

  1. 공개 IP에 대한 추적 경로(광역 히트는 방지하지만 여전히 ICMP)
  2. ifconfig/ipconfig와 같은 ICMP가 아닌 유틸리티를 사용하십시오(단, 이식성 문제가 있음).
  3. 현재로선 가장 좋고 이식성이 뛰어난 솔루션은 netstat를 쉘링하고 구문 분석하는 것입니다(코드 예제 참조). 여기)

netstat -rn의 출력은 로케일별로 다릅니다.내 시스템(locale=de)에서 출력은 다음과 같습니다....표준게이트웨이:10.22.0.1

따라서 'default'로 시작하는 줄이 없습니다.

따라서 netstat를 사용하는 것은 좋은 생각이 아닐 수도 있습니다.

이 버전은 www.whatismyip.com에 연결하여 사이트의 내용을 읽고 정규식을 통해 IP 주소를 검색하여 cmd에 인쇄합니다.MosheElishas 코드가 약간 개선되었습니다.

import java.io.BufferedReader;  
import java.io.IOException;  
import java.io.InputStreamReader; 
import java.net.URL;  
import java.util.regex.Matcher;  
import java.util.regex.Pattern;  

public class Main {

    public static void main(String[] args) {
        BufferedReader buffer = null;
        try {
            URL url = new URL(
                    "http://www.whatismyip.com/tools/ip-address-lookup.asp");
            InputStreamReader in = new InputStreamReader(url.openStream());
            buffer = new BufferedReader(in);
            String line = buffer.readLine();
            Pattern pattern = Pattern
                    .compile("(.*)value=\"(\\d+).(\\d+).(\\d+).(\\d+)\"(.*)");
            Matcher matcher;
            while (line != null) {
                matcher = pattern.matcher(line);
                if (matcher.matches()) {
                    line = matcher.group(2) + "." + matcher.group(3) + "."
                            + matcher.group(4) + "." + matcher.group(5);
                    System.out.println(line);
                }
                line = buffer.readLine();
            }
        } catch (IOException e) {
            e.printStackTrace();

        } finally {
            try {
                if (buffer != null) {
                    buffer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

import java.io.BufferedReader;  
import java.io.IOException;  
import java.io.InputStreamReader; 
import java.net.URL;  
import java.util.regex.Matcher;  
import java.util.regex.Pattern;  

public class Main {

    public static void main(String[] args) {
        BufferedReader buffer = null;
        try {
            URL url = new URL(
                    "http://www.whatismyip.com/tools/ip-address-lookup.asp");
            InputStreamReader in = new InputStreamReader(url.openStream());
            buffer = new BufferedReader(in);
            String line = buffer.readLine();
            Pattern pattern = Pattern
                    .compile("(.*)value=\"(\\d+).(\\d+).(\\d+).(\\d+)\"(.*)");
            Matcher matcher;
            while (line != null) {
                matcher = pattern.matcher(line);
                if (matcher.matches()) {
                    line = matcher.group(2) + "." + matcher.group(3) + "."
                            + matcher.group(4) + "." + matcher.group(5);
                    System.out.println(line);
                }
                line = buffer.readLine();
            }
        } catch (IOException e) {
            e.printStackTrace();

        } finally {
            try {
                if (buffer != null) {
                    buffer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

말처럼 쉽지는 않습니다.Java는 플랫폼 독립적이므로 Java에서 어떻게 수행하는지 잘 모르겠습니다.그래요 추측 해당 .NET은 이를 보고하는 일부 웹 사이트에 접속합니다.가는 방법에는 몇 가지가 있습니다.첫째, ICMP 프로토콜을 자세히 살펴보면 필요한 정보를 얻을 수 있습니다.귀하가 통과하는 IP(경로)를 추적할 수도 있습니다.다음 범위에 속하지 않는 IP를 발견한 경우:

  • 10.0.0.0 – 10.255.255.255
  • 172.16.0.0 – 172.31.255.255
  • 192.168.0.0 – 192.168.255.255

이는 귀하의 IP에서 한 홉 떨어진 IP이며 아마도 귀하의 IP와 몇 옥텟의 정보를 공유할 것입니다.

행운을 빌어 요.이 질문에 대한 확실한 답변을 듣고 싶습니다.

추적 경로가 있는 경우 이를 실행해 보십시오.

'traceroute -m 1 www.amazon.com'은 다음과 같은 내용을 내보냅니다.

traceroute to www.amazon.com (72.21.203.1), 1 hops max, 40 byte packets
 1  10.0.1.1 (10.0.1.1)  0.694 ms  0.445 ms  0.398 ms

두 번째 줄을 구문 분석합니다.예, 추악하지만 누군가가 더 좋은 것을 게시할 때까지는 계속 사용할 수 있습니다.

매튜:그렇습니다. 그것이 "웹 사이트에서 서비스를 사용하여 인터넷 IP를 얻을 수 있습니다"라는 의미입니다. glib에 대해 죄송합니다.

브라이언/닉:Traceroute는 많은 라우터가 ICMP를 비활성화하여 항상 정지된다는 점을 제외하면 괜찮습니다.

내 생각에는 Traceroute와 uPnP의 조합이 효과가 있을 것 같습니다.그것이 내가 계획하고 있던 일이었고, 나는 단지 내가 뭔가 분명한 것을 놓치고 있기를 바랐습니다.

의견을 보내주신 모든 분들께 감사드리며, 제가 놓친 부분은 없는 것 같습니다.게이트웨이를 발견하기 위해 몇 가지 uPnP를 구현하기 시작했습니다.

"라는 URL을 쿼리할 수 있습니다.http://whatismyip.com/automation/n09230945.asp".예를 들어:

    BufferedReader buffer = null;
    try {
        URL url = new URL("http://whatismyip.com/automation/n09230945.asp");
        InputStreamReader in = new InputStreamReader(url.openStream());
        buffer = new BufferedReader(in);

        String line = buffer.readLine();
        System.out.println(line);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (buffer != null) {
                buffer.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Windows에서는 다음 명령을 사용할 수 있습니다.

ipconfig | findstr /i "Gateway"

그러면 다음과 같은 출력이 제공됩니다.

Default Gateway . . . . . . . . . : 192.168.2.1
Default Gateway . . . . . . . . . : ::

그러나 Java에서는 이 명령을 실행할 수 없습니다. 이 사실을 알게 되면 게시하겠습니다.

당신이 사용할 수있는 netstat -rn Windows, OSX, Linux 등 플랫폼에서 사용할 수 있는 명령입니다.내 코드는 다음과 같습니다.

private String getDefaultAddress() {
        String defaultAddress = "";
        try {
            Process result = Runtime.getRuntime().exec("netstat -rn");

            BufferedReader output = new BufferedReader(new InputStreamReader(
                    result.getInputStream()));

            String line = output.readLine();
            while (line != null) {
                if (line.contains("0.0.0.0")) {

                    StringTokenizer stringTokenizer = new StringTokenizer(line);
                    stringTokenizer.nextElement(); // first element is 0.0.0.0
                    stringTokenizer.nextElement(); // second element is 0.0.0.0
                    defaultAddress = (String) stringTokenizer.nextElement();
                    break;
                }

                line = output.readLine();

            } // while
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return defaultAddress;

} // getDefaultAddress

모든 시스템에서 작동하는지 확실하지 않지만 적어도 여기서는 다음을 발견했습니다.

import java.net.InetAddress;
import java.net.UnknownHostException;
public class Main
{
    public static void main(String[] args)
    {
        try
        {
            //Variables to find out the Default Gateway IP(s)
            String canonicalHostName = InetAddress.getLocalHost().getCanonicalHostName();
            String hostName = InetAddress.getLocalHost().getHostName();

            //"subtract" the hostName from the canonicalHostName, +1 due to the "." in there
            String defaultGatewayLeftover = canonicalHostName.substring(hostName.length() + 1);

            //Info printouts
            System.out.println("Info:\nCanonical Host Name: " + canonicalHostName + "\nHost Name: " + hostName + "\nDefault Gateway Leftover: " + defaultGatewayLeftover + "\n");
            System.out.println("Default Gateway Addresses:\n" + printAddresses(InetAddress.getAllByName(defaultGatewayLeftover)));
        } catch (UnknownHostException e)
        {
            e.printStackTrace();
        }
    }
    //simple combined string out of the address array
    private static String printAddresses(InetAddress[] allByName)
    {
        if (allByName.length == 0)
        {
            return "";
        } else
        {
            String str = "";
            int i = 0;
            while (i < allByName.length - 1)
            {
                str += allByName[i] + "\n";
                i++;
            }
            return str + allByName[i];
        }
    }
}

나에게 이것은 다음을 생성합니다.

Info:
Canonical Host Name: PCK4D-PC.speedport.ip
Host Name: PCK4D-PC
Default Gateway Leftover: speedport.ip

Default Gateway Addresses:
speedport.ip/192.168.2.1
speedport.ip/fe80:0:0:0:0:0:0:1%12

모든 곳에서 작동하는지 확인하려면 다른 시스템/구성/PC-Gateway-Setups에 대한 추가 테스트가 필요합니다.의심스럽지만 이것이 제가 처음 발견한 것입니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top