0

Currently I've got a working port scanner but I want to limit it to only scanning IP address on the local subnet.

The only solution i've found when digging is this: Does anyone know a java component to check if IP address is from particular network/netmask? however I dont full understand

What is the difference between a subnet and a netmask? I thought they were the same thing?

Secondly, how can i find the values for subnet and netmask for localHost?

So far this is what I have

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

But is this the netmask or the subnet? And how do I get the other value?

Community
  • 1
  • 1
Byron Mihailides
  • 145
  • 1
  • 1
  • 6

1 Answers1

0

The subnetMask you determined is the number of bits in the network. The network address is found by setting all bits in the address that are after the bits in the mask to zero. This code should print the mask and network address in the usual form.

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

You can test if any address is on this network by using the bitwise and of the address in integer form with the network_mask integer. If it is on the network this should produce the address_int.

WillShackleford
  • 6,918
  • 2
  • 17
  • 33