java java中的小型ip扫描仪代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5462805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 11:13:18  来源:igfitidea点击:

small ip scanner code in java

javanetworkingip-address

提问by Airlike

I'm writing a small game in java. There's a server and a client module. At the moment every client has to enter the server IP (in a local network) manually. Thats why I have written this code here:

我正在用java编写一个小游戏。有一个服务器和一个客户端模块。目前,每个客户端都必须手动输入服务器 IP(在本地网络中)。这就是为什么我在这里写了这段代码:

import java.net.*;


public class myIP {

public static void main (String argv[]) 
{ 
    try{
          InetAddress ownIP=InetAddress.getLocalHost();
          String myIP = ownIP.getHostAddress();
          System.out.println( "IP of my system is := "+ myIP );
        }catch (Exception e){
          System.out.println( "Exception caught ="+e.getMessage() );
        }
      }
}

This piece of code returns the IP address of the machine. With this information (my own IP address) I'd like to check now for other IP addresses in this range to find the server automatically.

这段代码返回机器的IP地址。有了这些信息(我自己的 IP 地址),我现在想检查此范围内的其他 IP 地址以自动查找服务器。

Now I don't know how to iterate over this IP range. For example: if "myIP" is 10.0.0.5, how can I modify that string so I would have 10.0.0.6 for example? If it would be an integer value, it would be easy to add 1 every time - but since it's a string - separated by dots - I'm not sure how to solve that :) any idea?

现在我不知道如何遍历这个 IP 范围。例如:如果“myIP”是 10.0.0.5,我怎样才能修改那个字符串,例如我会有 10.0.0.6?如果它是一个整数值,那么每次都很容易加 1 - 但因为它是一个字符串 - 用点分隔 - 我不知道如何解决这个问题:) 知道吗?

cheers

干杯

采纳答案by OscarRyz

So, what you need is to convert an IPv4 address to Int and back.

因此,您需要将 IPv4 地址转换为 Int 并返回。

See if this helps:

看看这是否有帮助:

http://teneo.wordpress.com/2008/12/23/java-ip-address-to-integer-and-back/

http://teneo.wordpress.com/2008/12/23/java-ip-address-to-integer-and-back/

回答by Paul Ruane

This tends to be achieved using broadcast/multicast. This is not something I have ever played with so can not offer you any code, but this linkoffers a good explanation.

这往往是使用广播/多播来实现的。这不是我曾经玩过的东西,因此无法为您提供任何代码,但此链接提供了很好的解释。

Edit: it transcends there is a MulticastSocketclass which you may be able to put to use.

编辑:它超越了您可以使用的MulticastSocket类。

回答by xappymah

You should you getAddresswhich returns ip as byte array instead of getHostAdress.

您应该getAddress将 ip 作为字节数组而不是getHostAdress.

回答by Babar

Here is the code sample from TechnoJeevesto do this.

以下是来自TechnoJeeves的代码示例,用于执行此操作。

import java.net.InetAddress;

public class ScanNet {
    public static void main(String[] args) throws Exception {
    int[] bounds = ScanNet.rangeFromCidr("192.168.1.255/24");

    for (int i = bounds[0]; i <= bounds[1]; i++) {
        String address = InetRange.intToIp(i);
        InetAddress ip = InetAddress.getByName(address);

        if (ip.isReachable(100)) { // Try for one tenth of a second
            System.out.printf("Address %s is reachable\n", ip);
        }
    }
}

public static int[] rangeFromCidr(String cidrIp) {
    int maskStub = 1 << 31;
    String[] atoms = cidrIp.split("/");
    int mask = Integer.parseInt(atoms[1]);
    System.out.println(mask);

    int[] result = new int[2];
    result[0] = InetRange.ipToInt(atoms[0]) & (maskStub >> (mask - 1)); // lower bound
    result[1] = InetRange.ipToInt(atoms[0]); // upper bound
    System.out.println(InetRange.intToIp(result[0]));
    System.out.println(InetRange.intToIp(result[1]));

    return result;
}

static class InetRange {
    public static int ipToInt(String ipAddress) {
        try {
            byte[] bytes = InetAddress.getByName(ipAddress).getAddress();
            int octet1 = (bytes[0] & 0xFF) << 24;
            int octet2 = (bytes[1] & 0xFF) << 16;
            int octet3 = (bytes[2] & 0xFF) << 8;
            int octet4 = bytes[3] & 0xFF;
            int address = octet1 | octet2 | octet3 | octet4;

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

            return 0;
        }
    }

    public static String intToIp(int ipAddress) {
        int octet1 = (ipAddress & 0xFF000000) >>> 24;
        int octet2 = (ipAddress & 0xFF0000) >>> 16;
        int octet3 = (ipAddress & 0xFF00) >>> 8;
        int octet4 = ipAddress & 0xFF;

        return new StringBuffer().append(octet1).append('.').append(octet2)
                                 .append('.').append(octet3).append('.')
                                 .append(octet4).toString();
    }
} }