如何使用java获取本地系统的子网掩码?

发布于 2024-07-29 18:04:52 字数 31 浏览 4 评论 0原文

如何使用 Java 获取本地系统的子网掩码地址?

How do you get the Subnet mask address of the local system using Java?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

在风中等你 2024-08-05 18:04:53

SE6 中的 java.net.InterfaceAddress 有一个 getNetworkPrefixLength 方法,顾名思义,该方法返回网络前缀长度。 如果您希望采用该格式,则可以从中计算子网掩码。 java.net.InterfaceAddress 同时支持 IPv4 和 IPv6。

多个网络应用程序 API 中的 getSubnetMask() 以 java.net.InetAddress 形式返回指定 IP 地址的子网掩码(本地系统可能有许多本地 IP 地址)

java.net.InterfaceAddress in SE6 has a getNetworkPrefixLength method that returns, as the name suggests, the network prefix length. You can calculate the subnet mask from this if you would rather have it in that format. java.net.InterfaceAddress supports both IPv4 and IPv6.

getSubnetMask() in several network application APIs returns subnet mask in java.net.InetAddress form for specified IP address (a local system may have many local IP addresses)

茶底世界 2024-08-05 18:04:53

我设计了一个非常简单的纯 IPv4 解决方案。 我需要在这里为子网生成网络掩码,以便正确委派这些子网。 我知道我可以生成一个包含 32 个可能掩码的表,但我更喜欢每次都计算它。

这是我的解决方案。

/*
 * Get network mask for the IP address and network prefix specified...
 * The network mask will be returned has an IP, thus you can
 * print it out with .getHostAddress()...
 */
public static InetAddress getIPv4LocalNetMask(InetAddress ip, int netPrefix) {

    try {
        // Since this is for IPv4, it's 32 bits, so set the sign value of
        // the int to "negative"...
        int shiftby = (1<<31);
        // For the number of bits of the prefix -1 (we already set the sign bit)
        for (int i=netPrefix-1; i>0; i--) {
            // Shift the sign right... Java makes the sign bit sticky on a shift...
            // So no need to "set it back up"...
            shiftby = (shiftby >> 1);
        }
        // Transform the resulting value in xxx.xxx.xxx.xxx format, like if
        /// it was a standard address...
        String maskString = Integer.toString((shiftby >> 24) & 255) + "." + Integer.toString((shiftby >> 16) & 255) + "." + Integer.toString((shiftby >> 8) & 255) + "." + Integer.toString(shiftby & 255);
        // Return the address thus created...
        return InetAddress.getByName(maskString);
    }
        catch(Exception e){e.printStackTrace();
    }
    // Something went wrong here...
    return null;
}

您只需使用 IP 和您想要使用的前缀来调用它,它就会为您生成网络掩码。

I devised an IPv4 only solution that is simple enough. I needed that to generate netmask for subnetworks here in order to delegate those subnets correctly. I know I could have generated a table of the 32 possible masks, but I prefered to get it computed each time.

So here is my solution.

/*
 * Get network mask for the IP address and network prefix specified...
 * The network mask will be returned has an IP, thus you can
 * print it out with .getHostAddress()...
 */
public static InetAddress getIPv4LocalNetMask(InetAddress ip, int netPrefix) {

    try {
        // Since this is for IPv4, it's 32 bits, so set the sign value of
        // the int to "negative"...
        int shiftby = (1<<31);
        // For the number of bits of the prefix -1 (we already set the sign bit)
        for (int i=netPrefix-1; i>0; i--) {
            // Shift the sign right... Java makes the sign bit sticky on a shift...
            // So no need to "set it back up"...
            shiftby = (shiftby >> 1);
        }
        // Transform the resulting value in xxx.xxx.xxx.xxx format, like if
        /// it was a standard address...
        String maskString = Integer.toString((shiftby >> 24) & 255) + "." + Integer.toString((shiftby >> 16) & 255) + "." + Integer.toString((shiftby >> 8) & 255) + "." + Integer.toString(shiftby & 255);
        // Return the address thus created...
        return InetAddress.getByName(maskString);
    }
        catch(Exception e){e.printStackTrace();
    }
    // Something went wrong here...
    return null;
}

You just call it with the IP and the prefix you want to use, it will generate the netmask for you.

笙痞 2024-08-05 18:04:53

我刚刚完成了使用 Java 对网络进行子网划分的 API 的开发工作。

https://launchpad.net/subnettingapi

它具有该功能以及更多功能。

I just finished working on an API for subnetting networks with Java.

https://launchpad.net/subnettingapi

it has that functionality and more.

帅的被狗咬 2024-08-05 18:04:53

这是一个答案,如何从 WIFI 连接获取子掩码: 链接

我根据我的需要对其进行了调整,如下:

private static String intToIP(int ipAddress) {
    String ret = String.format("%d.%d.%d.%d", (ipAddress & 0xff),
            (ipAddress >> 8 & 0xff), (ipAddress >> 16 & 0xff),
            (ipAddress >> 24 & 0xff));

    return ret;
}

public static String GetSubnetMask_WIFI() {

    WifiManager wifiManager = (WifiManager) Global.getMainActivity()
            .getSystemService(Context.WIFI_SERVICE);
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();

    DhcpInfo dhcp = wifiManager.getDhcpInfo();
    String mask = intToIP(dhcp.netmask);

    return mask;
}

Here is an answer, how to get a submask from WIFI connection: link

I adapted it for my needs, and here it is:

private static String intToIP(int ipAddress) {
    String ret = String.format("%d.%d.%d.%d", (ipAddress & 0xff),
            (ipAddress >> 8 & 0xff), (ipAddress >> 16 & 0xff),
            (ipAddress >> 24 & 0xff));

    return ret;
}

public static String GetSubnetMask_WIFI() {

    WifiManager wifiManager = (WifiManager) Global.getMainActivity()
            .getSystemService(Context.WIFI_SERVICE);
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();

    DhcpInfo dhcp = wifiManager.getDhcpInfo();
    String mask = intToIP(dhcp.netmask);

    return mask;
}
不离久伴 2024-08-05 18:04:53

总而言之,获取 mask 的方法如下:

public String mascara() throws SocketException{
    try{
        InetAddress localHost = Inet4Address.getLocalHost();
        NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localHost);
        prefijo = 
            ""+networkInterface.getInterfaceAddresses().get(0).getNetworkPrefixLength();
        int shft = 0xffffffff<<(32- 
                networkInterface.getInterfaceAddresses().get(0).getNetworkPrefixLength());
        int oct1 = ((byte) ((shft&0xff000000)>>24)) & 0xff;
        int oct2 = ((byte) ((shft&0x00ff0000)>>16)) & 0xff;
        int oct3 = ((byte) ((shft&0x0000ff00)>>8)) & 0xff;
        int oct4 = ((byte) (shft&0x000000ff)) & 0xff;
        mascara = oct1+"."+oct2+"."+oct3+"."+oct4;
        // System.out.println(""+mascara);           
    }catch(UnknownHostException e){
        System.out.println("Error: "+e);
    }
    return mascara;
}

In summary, a method to obtain the mask would be like this:

public String mascara() throws SocketException{
    try{
        InetAddress localHost = Inet4Address.getLocalHost();
        NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localHost);
        prefijo = 
            ""+networkInterface.getInterfaceAddresses().get(0).getNetworkPrefixLength();
        int shft = 0xffffffff<<(32- 
                networkInterface.getInterfaceAddresses().get(0).getNetworkPrefixLength());
        int oct1 = ((byte) ((shft&0xff000000)>>24)) & 0xff;
        int oct2 = ((byte) ((shft&0x00ff0000)>>16)) & 0xff;
        int oct3 = ((byte) ((shft&0x0000ff00)>>8)) & 0xff;
        int oct4 = ((byte) (shft&0x000000ff)) & 0xff;
        mascara = oct1+"."+oct2+"."+oct3+"."+oct4;
        // System.out.println(""+mascara);           
    }catch(UnknownHostException e){
        System.out.println("Error: "+e);
    }
    return mascara;
}
请你别敷衍 2024-08-05 18:04:53

FWIW,过去我尝试过使用 InterfaceAddress.getNetworkPrefixLength() 和 InterfaceAddress.getBroadcast(),但它们不会返回准确的信息(这是在 Windows 上,使用 Sun JDK 1.6.0 update 10)。 网络前缀长度为 128(不是我网络上的 24),返回的广播地址是 255.255.255.255(不是我网络上的 192.168.1.255)。

James

更新:我刚刚找到了此处发布的解决方案:

     http://forums.sun.com/thread.jspa?threadID=5277744

您需要阻止 Java 使用 IPv6,这样它就不会通过 IPv6 访问 IPv4。
在命令行中添加 -Djava.net.preferIPv4Stack=true 可以修复 InterfaceAddress.getNetworkPrefixLength() 和 InterfaceAddress.getBroadcast() 的结果。

FWIW, in the past I'd tried using InterfaceAddress.getNetworkPrefixLength() and InterfaceAddress.getBroadcast(), but they don't return accurate info (this is on Windows, with Sun JDK 1.6.0 update 10). The network prefix length is 128 (not 24, which it is on my network), and the broadcast address returned is 255.255.255.255 (not 192.168.1.255, which it is on my network).

James

Update: I just found the solution posted here:

     http://forums.sun.com/thread.jspa?threadID=5277744

You need to prevent Java from using IPv6, so that it isn't getting to IPv4 via IPv6.
Adding -Djava.net.preferIPv4Stack=true to the command line fixes the results from InterfaceAddress.getNetworkPrefixLength() and InterfaceAddress.getBroadcast() for me.

羁〃客ぐ 2024-08-05 18:04:52

本地主机接口的第一个地址的网络掩码:

InetAddress localHost = Inet4Address.getLocalHost();
NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localHost);
networkInterface.getInterfaceAddresses().get(0).getNetworkPrefixLength();

更完整的方法:

InetAddress localHost = Inet4Address.getLocalHost();
NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localHost);

for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) {
    System.out.println(address.getNetworkPrefixLength());
}

/24 表示 255.255.255。

the netmask of the first address of the localhost interface:

InetAddress localHost = Inet4Address.getLocalHost();
NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localHost);
networkInterface.getInterfaceAddresses().get(0).getNetworkPrefixLength();

a more complete approach:

InetAddress localHost = Inet4Address.getLocalHost();
NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localHost);

for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) {
    System.out.println(address.getNetworkPrefixLength());
}

/24 means 255.255.255.

泛滥成性 2024-08-05 18:04:52

我发现:

NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localHost);

要获取 ipv6 的子网掩码,我们可以使用:

 networkInterface.getInterfaceAddresses().get(0).getNetworkPrefixLength(); 

要获取 ipv4 的子网掩码,我们可以使用:

networkInterface.getInterfaceAddresses().get(1).getNetworkPrefixLength();

I found that:

NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localHost);

To get subnetmask for ipv6 we can use:

 networkInterface.getInterfaceAddresses().get(0).getNetworkPrefixLength(); 

To get subnetmask for ipv4 we can use:

networkInterface.getInterfaceAddresses().get(1).getNetworkPrefixLength();
予囚 2024-08-05 18:04:52

您可以将获取的 ipv4 值转换为标准文本 ipv4 格式,如下所示:

short prflen=...getNetworkPrefixLength();
int shft = 0xffffffff<<(32-prflen);
int oct1 = ((byte) ((shft&0xff000000)>>24)) & 0xff;
int oct2 = ((byte) ((shft&0x00ff0000)>>16)) & 0xff;
int oct3 = ((byte) ((shft&0x0000ff00)>>8)) & 0xff;
int oct4 = ((byte) (shft&0x000000ff)) & 0xff;
String submask = oct1+"."+oct2+"."+oct3+"."+oct4;

You can convert the ipv4 obtained value into the standard textual ipv4 format like this:

short prflen=...getNetworkPrefixLength();
int shft = 0xffffffff<<(32-prflen);
int oct1 = ((byte) ((shft&0xff000000)>>24)) & 0xff;
int oct2 = ((byte) ((shft&0x00ff0000)>>16)) & 0xff;
int oct3 = ((byte) ((shft&0x0000ff00)>>8)) & 0xff;
int oct4 = ((byte) (shft&0x000000ff)) & 0xff;
String submask = oct1+"."+oct2+"."+oct3+"."+oct4;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文