Network UDP broadcast design?

前端 未结 3 1791
借酒劲吻你
借酒劲吻你 2021-01-31 10:46

I am working on a C++ server/.NET client applications couple in which my server (which runs the c++ on linux) broadcasts a message to show it\'s alive to the whole network and m

3条回答
  •  梦毁少年i
    2021-01-31 11:32

    Regardless of the language you are using, here is my answer:

    Regarding the broadcast IP addresses, both addresses are broadcast addresses but the limited broadcast address (which is 255.255.255.255) won't be forwarded by routers. It is better to use the subnet-directed broadcast address (192.168.2.255).

    In order to send/receive a broadcast address, you need to define your broadcast address (broadcast IP address and port number). For example: 192.168.2.255 and port number 3000. The client applications (the senders) MUST enable SO_BROADCAST socket option as follows:

    int enabled = 1;
    setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &enabled, sizeof(enabled));
    

    where sockfd is the socket descriptor.

    The server application will listen on a specific port number (port 3000). Normally, the server will respond to each request using unicast message.

    There will be no conflict as long as no application is listening on the same port number. Your server will not run if another application is listening on the same port unless you enabled SO_REUSEADDRESS socket option. However, if there is a conflict, then your signiture is depending on your protocol (message format). So, check the message format and reject the message if it does not follow the message format defined by your application protocol.

    For client applications, the received packet is unicast (unless you have another design). So, no conflict at this side.

提交回复
热议问题