.NET Documentation

Enum SocketFlags

Specifies options for socket operations.

Members

Remarks

The SocketFlags enumeration provides a set of options that can be used to control the behavior of socket operations such as sending and receiving data. These flags are typically passed as parameters to methods like Send, Receive, SendTo, and ReceiveFrom.

For example, you might use SocketFlags.Broadcast to send a message to all devices on a local network or SocketFlags.Multicast to send data to a specific group of recipients.

Usage Example

Sending a broadcast message


using System.Net;
using System.Net.Sockets;
using System.Text;

// ...

// Assume udpClient is a UdpClient bound to a local port
byte[] data = Encoding.ASCII.GetBytes("Hello, network!");
IPEndPoint broadcastEndPoint = new IPEndPoint(IPAddress.Broadcast, 11000); // Port 11000 is an example

try
{
    // Send the broadcast message
    udpClient.Send(data, data.Length, broadcastEndPoint);
    Console.WriteLine("Broadcast message sent successfully.");
}
catch (Exception ex)
{
    Console.WriteLine($"Error sending broadcast message: {ex.Message}");
}
            

Receiving data with address information


using System.Net;
using System.Net.Sockets;
using System.Text;

// ...

// Assume udpClient is a UdpClient listening for incoming data
byte[] buffer = new byte[1024];
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);

try
{
    // Receive data and request address information
    int bytesRead = udpClient.Client.ReceiveFrom(buffer, SocketFlags.AddressData, ref remoteEndPoint);
    string receivedData = Encoding.ASCII.GetString(buffer, 0, bytesRead);

    Console.WriteLine($"Received '{receivedData}' from {remoteEndPoint.Address}:{remoteEndPoint.Port}");
}
catch (Exception ex)
{
    Console.WriteLine($"Error receiving data: {ex.Message}");
}