2015-10-17 52 views
0

目前我有一個工作端口掃描程序,但我想限制它僅掃描本地子網上的IP地址。嘗試僅在本地子網上進行端口掃描

唯一的解決辦法挖當我發現是這樣的: Does anyone know a java component to check if IP address is from particular network/netmask?但是我不明白全

是什麼子網和網絡掩碼之間的區別?我以爲他們是一樣的東西?

其次,我如何找到localhost的子網和網絡掩碼的值?

到目前爲止,這是我

NetworkInterface network = NetworkInterface.getByInetAddress(localHost); 
short subnetMask = 
network.getInterfaceAddresses().get(1).getNetworkPrefixLength(); 

但是,這是網絡掩碼或子網?我如何獲得其他價值?

回答

0

您確定的子網掩碼是網絡中的位數。通過將掩碼中的位之後的地址中的所有位設置爲零來找到網絡地址。該代碼應該以通常的形式打印掩碼和網絡地址。

NetworkInterface network = NetworkInterface.getByInetAddress(localhost); 
short subnetMask 
     = network.getInterfaceAddresses().get(1).getNetworkPrefixLength(); 
int address_int = ByteBuffer.wrap(localhost.getAddress()).getInt(); 
int mask_int = 0; 
for(int i = 0; i < subnetMask-1; i++) { 
    mask_int = mask_int | (1<<31); 
    mask_int = mask_int >> 1; 
} 
byte mask_bytes[] = ByteBuffer.allocate(4).putInt(mask_int).array(); 
InetAddress mask_address = InetAddress.getByAddress(mask_bytes); 
System.out.println("mask_address = " + mask_address); 
int network_int = mask_int & address_int; 
byte network_bytes[] = ByteBuffer.allocate(4).putInt(network_int).array(); 
InetAddress network_address = InetAddress.getByAddress(network_bytes); 
System.out.println("network_address = " + network_address); 

您可以測試任何地址是網絡上使用按位和整數形式與network_mask整數地址。如果它在網絡上,這應該產生address_int。