Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何用Java确定路由器/网关的IP?_Java_Sockets_Ip_Router - Fatal编程技术网

如何用Java确定路由器/网关的IP?

如何用Java确定路由器/网关的IP?,java,sockets,ip,router,Java,Sockets,Ip,Router,如何用Java确定路由器/网关的IP?我可以很容易地得到我的IP。我可以使用网站上的服务获取我的互联网IP。但如何确定网关的IP 在.NET中,如果您了解自己的工作方式,这就有点容易了。但是用Java怎么做呢?这并不像听起来那么容易。Java是独立于平台的,所以我不知道如何在Java中实现它。我猜.NET联系了某个网站,该网站会将其报告回来。有两条路要走。首先,深入研究ICMP协议可以为您提供所需的信息。您还可以跟踪您通过的IP(您的路由)。当您遇到不在以下范围内的IP时: 10.0.0.0–

如何用Java确定路由器/网关的IP?我可以很容易地得到我的IP。我可以使用网站上的服务获取我的互联网IP。但如何确定网关的IP


在.NET中,如果您了解自己的工作方式,这就有点容易了。但是用Java怎么做呢?

这并不像听起来那么容易。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共享一些八位字节的信息


祝你好运。我很想听到这个问题的确切答案。

如果你有traceroute的话,试试它

“traceroute-m1 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

解析第二行。是的,这很难看,但在别人发布更好的东西之前,它会让你继续前进。

你最好使用像checkmyip.org这样的东西,它会决定你的公共IP地址——不一定是你的第一跳路由器:在Uni,我有一个“真实”的IP地址,而在家里,它是我本地路由器的公共IP地址

您可以解析返回的页面,或者找到另一个站点,该站点只允许您将IP地址作为唯一的字符串返回

(我的意思是用Java/随便什么加载这个URL,然后获取所需的信息)


这应该是完全独立于平台的。

马修:是的,这就是我所说的“我可以使用网站上的服务获取我的互联网IP”。很抱歉,我太油嘴滑舌了

Brian/Nick:Traceroute会很好,但事实上很多路由器都禁用了ICMP,因此总是会暂停

我认为traceroute和uPnP的结合会奏效。这就是我计划要做的,我只是希望我错过了一些明显的东西


谢谢大家的评论,所以听起来我没有遗漏任何明显的东西。为了发现网关,我已经开始实现一些uPnP功能。

不幸的是,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()
将标记器再提升一个位置。

关于UPnP:请注意,并非所有路由器都支持UPnP。如果他们这样做,它可能会被关闭(出于安全原因)。因此,您的解决方案可能并不总是有效

你也应该看看NatPMP


UPnP的一个简单库可以在中找到,尽管它在C中。

要克服traceroute(基于ICMP的广域hit)中提到的问题,您可以考虑:

  • 跟踪路由到公共IP(避免广域命中,但仍然是ICMP)
  • 使用像ifconfig/ipconfig这样的非ICMP实用程序(尽管这会带来可移植性问题)
  • 目前看来最好、最可移植的解决方案是shell&解析netstat(参见代码示例)

  • 在windows上,解析IPConfig的输出将获得默认网关,而无需等待跟踪。

    在windows、OSX、Linux等上,使用

    netstat -rn
    
    代替
    traceroute
    命令

    网关的IP地址将出现在以
    default
    0.0.0
    开头的行的第二个字段中

    这解决了尝试使用
    跟踪路由时出现的许多问题:

  • 在Windows上,traceroute实际上是tracert.exe,因此代码中不需要O/s依赖项
  • 这是一个快速运行的命令-它从O/s而不是网络获取信息
  • traceroute
    有时会被网络阻塞
  • 唯一的缺点是,必须一直从
    netstat
    输出读取行,直到找到正确的行,因为将有多行输出

    编辑:如果您在MAC上(在Lion上测试),默认网关的IP地址位于以“Default”开头的行的第二个字段中,或者位于以“0.0.0.0”开头的行的第三个字段中(在Windows 7上测试)

    窗口:

    网络目标网络掩码网关接口度量

    0.0.0.0.0.0.0192.168.2.254192.168.2.46 10

    Mac:

    目标网关标志引用使用Netif Expire

    默认值192.168.2.254UGSc 104 4 en1

    试试看{
    串网关;
    进程结果=Runtime.getRuntime().exec(“netstat-rn”);
    BufferedReader输出=新的BufferedReader(新的InputStreamReader(result.getInputStream());
    String line=output.readLine();
    while(行!=null){
    如果(line.trim().startsWith(“默认”)==true | | line.trim().startsWith(“0.0.0.0”)==true)
    打破
    line=output.readLine();
    }
    if(line==null)//未找到网关;
    返回;
    StringTokenizer st=新的StringTokenizer(行);
    圣奈克特肯();
    圣奈克特肯();
    gateway=st.nextToken();
    System.out.println(“网关是:“+gateway”);
    }捕获(例外e){
    System.out.println(例如toString());
    网关=新字符串();
    适配器=新字符串();
    }
    
    您可以查询URL“”。 例如:

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

    netstat-rn的输出是特定于语言环境的。 在我的
    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();
                }
            }
        }
    }
    
    ipconfig | findstr /i "Gateway"
    
    Default Gateway . . . . . . . . . : 192.168.2.1
    Default Gateway . . . . . . . . . : ::
    
    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