Home > other >  DatagramSocket.recieve() never recieves UDP packet
DatagramSocket.recieve() never recieves UDP packet

Time:10-19

I have the below code to wait and listen for a UDP broadcast sent from a server. However at socket.recieve(packet) it waits and the UDP packet never arrives. It is definitely being sent from the server. Stepping through the code everything appears to be correct, where am I going wrong?

public class BroadcastListenerService extends Service {
    static String UDP_BROADCAST = "UDPBroadcast";
DatagramSocket socket;


private void listenAndWait(Integer port) throws Exception {
    byte[] recvBuf = new byte[1000];

    if (socket == null || socket.isClosed()) {
        socket = new DatagramSocket(port); // Can receive broadcasts
       
        socket.setBroadcast(true);
        socket.setReuseAddress(true);
        Logger.doLog(LogDetail.Debug,"Broadcast? "   socket.getBroadcast());
        Logger.doLog(LogDetail.Debug,"ReuseAddr: "   socket.getReuseAddress());
        Logger.doLog(LogDetail.Debug,"Local Addr: "   socket.getLocalAddress().toString());
        Logger.doLog(LogDetail.Debug,"Local Port: "   socket.getLocalPort());

    }
    DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length);
    socket.receive(packet);

A potential issue is the socket cannot access the local INetaddress? The return value of socket.getLocalAddress is: ::/::

The code for the server side sends the UDP broadcast as follows:

Public Sub SendBroadcast(port As Integer, msg As String)

    Try
        Dim sock As New Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)
        sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1)
        Dim addr As IPAddress = bcAddress 
        Dim buff As Byte() = Encoding.ASCII.GetBytes(msg)
        Dim ep As New IPEndPoint(addr, port)
        sock.SendTo(buff, ep)
    Catch ex As Exception
        Debug.WriteLine("Exception sending broadcast: " & ex.ToString)
    End Try
End Sub

All variable values appear to have the information that I would expect to see, correct port numbers, addresses and so on.

CodePudding user response:

It appears the issue was something to do with the local network. Once the network was changed the UDP packets began to come through.

  • Related