Search code examples
javaandroidsocketsbroadcastdatagram

DatagramPacket.getAddress().getHostName() is blocking my Thread


I have a thread that receives a data from a device. When it comes to line myDatagramPacket.getAddress().getHostName() it stops for 5-6 seconds then it continues.

When i tried a hardcoded ip like "192.168.1.163", it is working nonstop.

How can I solve this problem?

Any suggestions?


Solution

  • That line looks like it performs a Reverse DNS Lookup, that would naturally be slow.

    You can either try to modify the logic without the lookup, or if that is not possible, try caching the results of the call (so you don't pay the time multiple times).

    To just get the IP of the sender, work only with myDatagramPacket.getAddress(), it returns an InetAddress that represents the IP (instead of calling getHostName() on it, use getHostAddress() and/or toString()).