C # UDP broadcast send / receive

1 minute read


The source code is the following round pakuri, which is the source code with comments.

IPEndPoint / UdpClient

  • IPEndPoint
    Endpoint (communication port) information (IP address / port number)
  • UdpClient
    Things like a controller for various controls of UDP


Listen for requests from clients on port number 8888,
When a request is received, it returns a response to the source endpoint.

static void Main(string[] args)
    var Server = new UdpClient(8888);                                       //Generate UdpClient by specifying the listening port
    var ResponseData = Encoding.ASCII.GetBytes("SomeResponseData");         //Appropriate response data

    while (true)
        var ClientEp = new IPEndPoint(IPAddress.Any, 0);                    //Client (communication partner) endpoint ClientEp creation (IP)/Port not specified)
        var ClientRequestData = Server.Receive(ref ClientEp);               //Packet reception from client, client endpoint information is entered in ClientEp
        var ClientRequest = Encoding.ASCII.GetString(ClientRequestData);

        Console.WriteLine("Recived {0} from {1}, sending response", ClientRequest, ClientEp.Address.ToString());    // ClientEp.Address: Client IP
        Server.Send(ResponseData, ResponseData.Length, ClientEp);           //Packet transmission to Client Ep containing client information


Broadcast the request to port number 8888 and
Wait for the response to come back to you.

static void Main(string[] args)
    var Client = new UdpClient();                           //Create UdpClient (port number is assigned appropriately)
    var RequestData = Encoding.ASCII.GetBytes("Request");   //Appropriate request data
    var ServerEp = new IPEndPoint(IPAddress.Any, 0);        //Server (communication partner) endpoint ServerEp creation (IP)/Port not specified)

    Client.EnableBroadcast = true;                          //Broadcast enabled
    Client.Send(RequestData, RequestData.Length, new IPEndPoint(IPAddress.Broadcast, 8888)); //Broadcast to port 8888

    //The person who received the transmitted data should have known the endpoint information of himself / herself (client).
    //Wait for the packet to be sent to it
    var ServerResponseData = Client.Receive(ref ServerEp);  //Packet reception from the server, server endpoint information is entered in ServerEp
    var ServerResponse = Encoding.ASCII.GetString(ServerResponseData);
    // ServerEp.Address / ServerEp.IP of the server on Port/Get port number
    Console.WriteLine("Recived {0} from {1}:{2}", ServerResponse, ServerEp.Address.ToString(), ServerEp.Port.ToString());


Tags: ,