Tuesday, May 22, 2012

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 game client start, it need to know what is server IP address . How to client dectect 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 byte) 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 start , it will retrieve UDP package sent by 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 deteced IP for create a socket connection with game server and everything working great .



2 comments:

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

    ReplyDelete
  2. 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...

    ReplyDelete