System.Net.Sockets.SocketFlags Enumeration

Specifies the transmission mode and other option flags for socket operations.

Namespace: System.Net.Sockets
Assembly: System.Net.Sockets.dll

Syntax

public enum SocketFlags

Members

  • Broadcast: Indicates that the transmission is a broadcast.
  • DontRoute: Indicates that the data should not be routed.
  • None: No flags are specified. This is the default.
  • OutOfBand: Process the out-of-band data.
  • Peek: Indicates that the data should be read without removing it from the input queue.
  • Truncate: Indicates that datagrams larger than the buffer will be truncated.

Remarks

The SocketFlags enumeration is used by various socket methods, such as Socket.Receive and Socket.Send, to control the behavior of the socket operation. For example, you can use SocketFlags.Peek to examine incoming data without consuming it from the receive buffer, or SocketFlags.Broadcast to send data to all connected hosts on a network.

Some flags may not be supported by all protocols or network interfaces. Refer to the specific protocol documentation for details.

Example

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

public class Example
{
    public static void Main(string[] args)
    {
        try
        {
            // Create a UDP client
            UdpClient udpClient = new UdpClient(11000);
            IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, 0);

            Console.WriteLine("Waiting for broadcast...");

            // Receive data with Peek flag
            byte[] receivedBytes = udpClient.Receive(ref ipEndPoint);
            string message = System.Text.Encoding.ASCII.GetString(receivedBytes);

            Console.WriteLine($"Received from {ipEndPoint}: {message}");

            // Send data with Broadcast flag
            using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            {
                IPAddress broadcastAddress = IPAddress.Parse("192.168.1.255"); // Replace with your network's broadcast address
                IPEndPoint broadcastEndPoint = new IPEndPoint(broadcastAddress, 11000);

                byte[] dataToSend = System.Text.Encoding.ASCII.GetBytes("Hello, broadcast!");
                socket.SendTo(dataToSend, SocketFlags.Broadcast, broadcastEndPoint);
                Console.WriteLine("Broadcast sent.");
            }

            udpClient.Close();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}

Requirements

Component Version
.NET Framework 1.1 or later
.NET Core 1.0 or later
.NET Standard 1.3 or later

See Also