How to get subnet mask of local system using java?

2019-01-04 12:38发布

How to get Subnet mask address of local system using Java programming?

10条回答
家丑人穷心不美
2楼-- · 2019-01-04 13:14

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.

查看更多
贪生不怕死
3楼-- · 2019-01-04 13:15

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();
查看更多
唯我独甜
4楼-- · 2019-01-04 13:15

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

https://launchpad.net/subnettingapi

it has that functionality and more.

查看更多
Deceive 欺骗
5楼-- · 2019-01-04 13:15

You can convert the obtained value into the standard textual 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;
查看更多
Summer. ? 凉城
6楼-- · 2019-01-04 13:16
String local=InetAddress.getLocalHost().getHostAddress();
String[] ip_component = local.split("\\.");
String subnet=ip_component[0]+"."+ip_component[1]+"."+ip_component[2]+".";

This worked for me. here the variable subnet has the subnet adress.

查看更多
Fickle 薄情
7楼-- · 2019-01-04 13:22

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)

查看更多
登录 后发表回答