Syntax
public void Bind(EndPoint localEP);
Parameters
| Name | Type | Description |
|---|---|---|
| localEP | EndPoint | An EndPoint that represents the local port and network address to bind the Socket to. |
Return Value
None
Remarks
The Bind method associates a Socket with a specific local network endpoint. This endpoint includes both the local IP address and the port number. If you are creating a server application, you typically call Bind to assign a well-known port or an ephemeral port to the Socket so that clients can connect to it.
If the IP address portion of the localEP parameter is IPAddress.Any, the Socket will be bound to all network interfaces on the local computer.
If you are using a connectionless protocol like UDP, you need to call Bind before you can send or receive data.
For connection-oriented protocols like TCP, Bind is typically followed by a call to Listen to begin accepting incoming connection requests.
Attempting to bind a Socket to an endpoint that is already in use will result in an exception, usually an SocketException with an error code indicating the address is already in use.
Exceptions
- SocketException: An error occurred when attempting to access the network.
- ArgumentNullException: The
localEPparameter is null. - ArgumentException: The
localEPparameter is not a valid network endpoint.
Examples
using System;
using System.Net;
using System.Net.Sockets;
public class Example
{
public static void Main()
{
int port = 13000;
IPAddress ipAddress = IPAddress.Any;
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);
using (Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
{
try
{
listener.Bind(localEndPoint);
Console.WriteLine($"Socket bound to {localEndPoint.ToString()}");
// Now you can proceed to listen for connections or send/receive data
// listener.Listen(10);
// Socket handler = listener.Accept();
}
catch (SocketException ex)
{
Console.WriteLine($"SocketException: {ex.Message}");
}
catch (ArgumentException ex)
{
Console.WriteLine($"ArgumentException: {ex.Message}");
}
}
}
}