bind (ws2_32)
Last changed: -77.124.220.248

.
Summary
The bind function associates a local address with a socket.
Remarks
The bind function is used on an unconnected socket before subsequent calls to the connect or listen functions. It is not neccessary to use bind for connect(), but is required for listen(). This binding process is performed by the connect() function implicitly.
Parameter
Parameter
socketAddress A sockaddr_in structure used to identify the IP address and port to bind to.
Parameter
addressLength The length of the supplied socketAddress parameter.

C# Signature:

[DllImport("ws2_32.dll", CharSet=CharSet.Ansi, SetLastError=true)]
static extern int bind(
    IntPtr socketHandle,
    ref sockaddr_in socketAddress,
    int addressLength);

VB Signature:

Declare Function bind Lib "ws2_32.dll" ( _
        socketHandle As IntPtr, _
        ByRef socketAddress As sockaddr_in, _
        addressLength as Integer) As Integer

User-Defined Types:

/// <summary>
/// Internet socket address structure.
/// </summary>
internal struct sockaddr_in
{
    /// <summary>
    /// Protocol family indicator.
    /// </summary>
    public short  sin_family;
    /// <summary>
    /// Protocol port.
    /// </summary>
    public short sin_port;
    /// <summary>
    /// Actual address value.
    /// </summary>
    public int sin_addr;
    /// <summary>
    /// Address content list.
    /// </summary>
    //[MarshalAs(UnmanagedType.LPStr, SizeConst=8)]
    //public string sin_zero;
    public long sin_zero;
}

Alternative Managed API:

Do you know one? Please contribute it!

Notes:

None.

Tips & Tricks:

Please add some!

Sample Code:

public static bool Bind(string ipAddress, int port, IntPtr socketHandle)
{
    sockaddr_in remoteAddress;            //Remote address structure.
    int resultCode = 0;            //Result of operation.
    int errorCode = 0;                //Resultant error.
    bool returnValue = false;            //Return value.

    if (socketHandle != IntPtr.Zero)
    {
        try
        {
            //Attempt to create the destination address.
            remoteAddress = new sockaddr_in();
            remoteAddress.sin_family = SocketsConstants.AF_INET;
            remoteAddress.sin_port = htons((short)port);
            remoteAddress.sin_addr = inet_addr(ipAddress);
            remoteAddress.sin_zero = 0;

            //Check to ensure the address translated correctly.
            if (remoteAddress.sin_addr != 0)
            {
                //Attempt to connect.
                resultCode = bind(socketHandle, ref remoteAddress,
                    Marshal.SizeOf(remoteAddress));
                errorCode = Marshal.GetLastWin32Error();
                returnValue = (resultCode == 0);
            }
        }
        catch
        {
            returnValue = false;
        }
    }
    return returnValue;
}


Documentation