Using Java UDP broadcast to detect Server IP address on LAN

I develop a game server on LAN.
My game server is TCP based (java socket)
But when the game client starts, it needs to know what is server IP address. How to client detect Server's IP address?
I using UDP broadcast to detect server IP.

Firstly :
In Server I create a UDP server, it broadcast in a schedule :

       
       DatagramSocket ss = new DatagramSocket();
       ss.setBroadcast(true);
       byte[] b = new byte[100];
       DatagramPacket p = new DatagramPacket(b, b.length);
       p.setAddress(InetAddress.getByAddress(new byte[] { (byte) 255,
               (byte) 255, (byte) 255, (byte) 255 }));
       p.setPort(PORT);

This code will send a null package(100 bytes) to 255.255.255.255 , and this package will send all IP on LAN.
Of course, we need a loop to send in a schedule.

       

DatagramSocket ss = new DatagramSocket();
       ss.setBroadcast(true);
       byte[] b = new byte[100];
       DatagramPacket p = new DatagramPacket(b, b.length);
       p.setAddress(InetAddress.getByAddress(new byte[] { (byte) 255,
               (byte) 255, (byte) 255, (byte) 255 }));
       p.setPort(PORT);
                 int i = 0;
       while (true) {
           String s = new Integer(i++).toString();
                             b = s.getBytes();
           p.setData(b);
           ss.send(p);
           try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
       }

Secondly.
When client starts, it will retrieve UDP package sent by a server and of course, it know Server's IP address.

       

 byte[] receiveData = new byte[100];
DatagramSocket clientSocket = new DatagramSocket(1234);
DatagramPacket receivePacket =
        new DatagramPacket(receiveData,
                     receiveData.length);
     clientSocket.receive(receivePacket);
     System.out.println(receivePacket.getAddress());

Finally. I use detected IP to create a socket connection with the game server and everything works great.

Share this

Related Posts

Previous
Next Post »

3 comments

comments
May 20, 2013 at 7:19 AM delete

Thank you for this example. It helped me a lot.

Reply
avatar
August 21, 2013 at 4:11 AM delete

I use this code but the second module (receive) doesn't work for me. I wanto to use this method between a PC and an android smartphone...

Reply
avatar