• Re: Berkeley Sockets -- Reply to UDP Broadcast

    From Lew Pitcher@21:1/5 to Frederick Gotham on Thu Oct 7 16:18:16 2021
    XPost: comp.unix.programmer

    On Wed, 06 Oct 2021 11:33:20 -0700, Frederick Gotham wrote:

    I'm programming an embedded Linux device to send a reply to an incoming
    UDP broadcast packet. I spent a few hours today trying to figure this
    out, and it looks like I might be resorting to raw sockets with custom headers that I've written by myself byte by byte.

    Let's say the incoming UDP broadcast datagram has source port 5432, and destination port 1011.

    I want the reply packet I send to have source port 1011 and destination
    port 5432. I thought this would be possible by simply taking the address structure from the 'recvfrom' function and passing it verbatim to the 'sendto' function, however this doesn't work (it doesn't send the packet out).

    It seems as though I would have to create a new UDP socket and then send
    the reply packet on that new socket, however the problem here is that
    the source port will be an ephemeral port (e.g. 17654 instead of 1011).

    I played with all the settings like SO_BROADCAST but no joy.

    In your server,
    - bind() to port 1011, which allows the server to receive datagrams sent
    to port 1011, and to send datagrams from port 1011
    - recvfrom(), to populate a buffer with the received datagram, and
    populate a struct sockaddr with the sender's address
    - sendto(), with your server's reply buffer, and the struct sockaddr
    populated by recvfrom(). This sends the reply datagram to the
    sender's address

    Your client will bind() to it's port (in your example, 5432) or use an ephimeral port, and send() or sendto() the broadcast address, specifying
    the same port as the server is listening on (in your example, port 1011).

    Your server will bind() to it's port (your example was 1011), and
    recvfrom() that socket to receive datagrams sent to that port. This will include those datagrams sent "broadcast", as well as datagrams that were specifically addressed to your server.

    The server's recvfrom() will, in the case of received UDP datagrams,
    populate the struct sockaddr with the client's source IP address and
    source port number. If your client uses port 5432 as it's port number,
    the struct sockaddr will contain port 5432, and the client's IP address.

    Lew Pitcher
    "In Skills, We Trust"

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)