Search code examples
c#socketsudpudpclient

An invalid argument was supplied in socket programming


I want to create a UDP client and server in C# and when I run those, after first send and receive message, this error implement. My code is:

byte[] barray = new byte[1024];
EndPoint ipre = new IPEndPoint(IPAddress.Any, 4040);
socketClint.Bind((IPEndPoint)ipre);
int rc = socketClint.ReceiveFrom(barray, ref ipre);

if (rc > 0)
{
    listBox1.Items.Add("Server: "+ BitConverter.ToInt32(barray,0));
}

This error is about socketClint.Bind((IPEndPoint)ipre); line.

the Error is:

System.Net.Sockets.SocketException was unhandled
HResult=-2147467259
Message=An invalid argument was supplied
Source=System
ErrorCode=10022
NativeErrorCode=10022
StackTrace:
   at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)
   at System.Net.Sockets.Socket.Bind(EndPoint localEP)
   at client1.Form1.getmsg() in c:\Users\Inspiron 1545\Desktop\UDP\client1\client1\Form1.cs:line 38
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

InnerException:


Solution

  • Winsock error 10022 is WSAEINVAL:

    WSAEINVAL
    10022

    Invalid argument.
    Some invalid argument was supplied (for example, specifying an invalid level to the setsockopt function). In some instances, it also refers to the current state of the socket — for instance, calling accept on a socket that is not listening.

    In the context of the Winsock bind() function (which Socket.Bind() uses internally), it means this:

    WSAEINVAL

    An invalid argument was supplied.

    This error is returned if the socket s is already bound to an address.

    Once a socket has been bound to a local address, you can't re-bind it to a new local address. You are supposed to bind it only one time.

    So, in your case, call Bind() after creating socketClint only. Do not call it before every call to socketClint.ReceiveFrom().