P i
P i

Reputation: 30684

SocketException: Address already in use

I'm attempting to catch incoming UDP packets through an asynchronous socket listener

I'm using code from here: http://www.alexthissen.nl/blogs/main/archive/2004/12/26/receiving-udp-messages-using-udpclient-or-socket-classes.aspx

(I've also been reading through a very good tutorial here: http://www.winsocketdotnetworkprogramming.com/clientserversocketnetworkcommunication8d.html that's not related to the question, just putting it up as a good resource)

However, I get the following error:

SocketException: Address already in use

Here is the code:

private Byte[] buffer;

public void StartListening()
{
    int port = 6500; // 'netstat -an' shows this is initially unused
    int bufferSize = 1024;
    buffer = new Byte[bufferSize];
    IPAddress ip = IPAddress.Any; // IPAddress.Parse( "127.0.0.1" );
    IPEndPoint ep = new IPEndPoint(ip, port);
    Socket sock = new Socket(ip.AddressFamily, SocketType.Dgram, ProtocolType.Udp);

    sock.Bind(ep); // 'SocketException: Address already in use'

    sock.BeginReceive(buffer, 0, 1024, SocketFlags.None, new AsyncCallback(this.OnReceive), sock);
}

private void OnReceive(IAsyncResult ar)
{
    Socket s1 = (Socket)ar.AsyncState;
    int x = s1.EndReceive(ar);
    string message = System.Text.Encoding.ASCII.GetString(buffer, 0, x);
    Console.WriteLine(message);
    s1.BeginReceive(buffer, 0, 1024, SocketFlags.None, new AsyncCallback(this.OnReceive), s1);
}   

Upvotes: 4

Views: 10319

Answers (1)

P i
P i

Reputation: 30684

The code is actually correct.

The script was getting run twice.

Just providing this stub answer so the question doesn't misfile as unanswered.

Upvotes: 2

Related Questions