1

I am writing a game in Java using libGDX. I want to add local area network discovery into the game, so players will only have to press a button to start a multiplayer game. To achieve this, each client broadcasts UDP packets to a certain port (255.255.255.255:40667) and listens for other incoming packets on this port to create a list of other players on the network.

This works perfectly, but the packets which were broadcasted by a machine are also received by it.

For example:
If there are 2 machines on the network with the program running

Machine 1 (192.168.1.137)

Machine 2 (192.168.1.111)

Then the 1st machine receives packets from 192.168.1.111 AND from 192.168.1.137
I am trying to find a way to determine if the packet came from my own address, but I can't figure it out.

InetAddress.getLocalHost() returns 127.0.1.1, and reading the local address from the outbound socket returns 0.0 0.0
How do I determine if the packet was sent from the same machine?

Thanks

Community
  • 1
  • 1
  • Possible duplicate of [java InetAddress.getLocalHost(); returns 127.0.0.1 ... how to get REAL IP?](https://stackoverflow.com/questions/2381316/java-inetaddress-getlocalhost-returns-127-0-0-1-how-to-get-real-ip) – Am_I_Helpful Jun 18 '17 at 13:19

1 Answers1

0

Your machine usually has multiple IP addresses and calling to localhost often returns 127.0.1.1 There is several options how to determine local IP address, one is just to create socket connection:

// Here is the existing IP address in my local network, or you will get the exception
try (Socket socket = new Socket("192.168.0.1", 80)) {
    System.out.println(socket.getLocalAddress().getHostAddress());
} catch (UnknownHostException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

You can manually assosiate your host name with address modifying:

C:\Windows\System32\drivers\etc\hosts

Add 10.10.10.1 test for example and in your app just call:

System.out.println(InetAddress.getByName("test").getHostAddress());

command hostname in cmd will return you the hostname.

J-Alex
  • 6,881
  • 10
  • 46
  • 64