Specifies options for socket operations.
No SocketFlags are set. This is the default value.
Specifies that the system should ignore the routing table when sending data. The data is routed directly to the destination.
Specifies that the data should be sent as a broadcast datagram.
Specifies that the data should be sent as a multicast datagram.
Specifies that data sent on a multicast socket should be looped back to the sending socket.
Specifies that the socket is transactional. This flag is only supported on Windows NT.
Specifies that the socket is a Large Internet Message Exchange (LIME) socket. This flag is only supported on Windows NT.
Specifies that congestion control should be used for socket operations.
Specifies that no more data can be sent on this socket. This flag is set by the system.
Specifies that address data should be returned with the received data.
Specifies that connection auditing should be enabled for the socket.
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.
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}");
}
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}");
}