Replying to a client over sockets (UDP) from a different process

后端 未结 2 736
名媛妹妹
名媛妹妹 2021-01-27 09:29

I have a server than is a \"command handler\" process. It receives messages over UDP, and delegates the work to do to a different process by communicating to that process throu

相关标签:
2条回答
  • 2021-01-27 09:40

    Your client (or a firewall in between) will likely get confused by receiving the response from a different source port than it sent the request to (as the OS will just pick a random source port for the new socket).

    One way around this is to use the SO_REUSEADDR socket option in the server and explicitely bind to the correct port when sending the reply. But that would also have the undesireable side-effect that UDP requests might be redirected to one of the other processes instead of the server.

    Another option (if you are using Unix/Linux) is to pass the server socket to the other processes via a unix domain socket (via sendmsg and ancillary data).

    0 讨论(0)
  • 2021-01-27 09:54

    You should be testing for the error return, something like

    if((nsfd = socket (AF_INET, SOCK_DGRAM, IPROTO_UDP)) < 0} {
        perror("at socket open");
        // I'd call exit here, probably
    }
    if(sendto(nsfd, buff, bread, 0, &addr, sizeof(addr) < 0){
        perror("At sendto");
    }
    

    There's a nice tutorial example here.

    0 讨论(0)
提交回复
热议问题