private Optional < InetAddress > onSameSubnet ( final InetAddress remote ) { try { return Collections . list ( NetworkInterface . getNetworkInterfaces ( ) ) . stream ( ) . flatMap ( ni -> ni . getInterfaceAddresses ( ) . stream ( ) ) . filter ( ia -> ia . getAddress ( ) instanceof Inet4Address ) . peek ( ia -> logger . trace ( "match local address {}/{} to {}" , ia . getAddress ( ) , ia . getNetworkPrefixLength ( ) , remote ) ) . filter ( ia -> matchesPrefix ( ia . getAddress ( ) , ia . getNetworkPrefixLength ( ) , remote ) ) . map ( ia -> ia . getAddress ( ) ) . findFirst ( ) ; } catch ( final SocketException ignore ) { } return Optional . empty ( ) ; }
finds a local IPv4 address with its network prefix matching the remote address