Class InterfaceResolver

java.lang.Object
it.polimi.ingsw.gc14.Network.InterfaceResolver

public class InterfaceResolver extends Object
Utility class for resolving the local network interface to use when connecting to a server.
  • Constructor Details

    • InterfaceResolver

      private InterfaceResolver()
  • Method Details

    • resolveLocalInterface

      public static String resolveLocalInterface(String serverIp) throws Exception
      Returns the local IPv4 address that can reach the given server IP.

      If the server is localhost, returns "127.0.0.1". Otherwise, iterates active non-loopback interfaces to find one on the same subnet; falls back to a UDP connect trick if no matching subnet is found.

      Parameters:
      serverIp - the server IP address or hostname.
      Returns:
      the local IP address string to use for outbound connections.
      Throws:
      Exception - if no suitable interface can be determined.
    • sameSubnet

      private static boolean sameSubnet(InetAddress a, InetAddress b, int prefix)
      Returns true if a and b share the same subnet given a CIDR prefix length.
      Parameters:
      a - first IPv4 address.
      b - second IPv4 address.
      prefix - CIDR prefix length (0–32).
      Returns:
      true if both addresses belong to the same subnet.
    • toInt

      private static int toInt(byte[] bytes)
      Converts a 4-byte big-endian IPv4 address array to a signed 32-bit integer.
      Parameters:
      bytes - the 4-byte address array.
      Returns:
      the corresponding signed integer.