System.Net.Sockets.SocketeException: An invalid argument was supplied Error Code:10022

User23289 picture User23289 · Nov 9, 2013 · Viewed 16.8k times · Source

I do not know why I am receiving the following error. Can anyone shed some light on this?

System.Net.Sockets.SocketeException: An invalid argument was supplied Error Code:10022 [closed]

private void btnStart_Click(object sender, EventArgs e)
        {

 try
            {
                epLocal = new IPEndPoint(IPAddress.Parse(txtIP1.Text), Convert.ToInt32(txtPort1.Text));
                sck.Bind(epLocal);
                epRemote = new IPEndPoint(IPAddress.Parse(txtIP2.Text), Convert.ToInt32(txtPort2.Text));
              //Here Error Occures I dont know what is my mistake?
                sck.Bind(epRemote);
                byte[] buffer = new byte[1500];
                sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
                btnStart.Text = "Connected";
                btnStart.Enabled = false;
                btnSend.Enabled = true;
                txtMessage.Focus();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

Answer

Kas picture Kas · Nov 9, 2013

You are binding same socket to mutiple Endpoint objects , that's why you are getting an InvalidArgument exception , You can bind one socket to only one IPEndPoint object at a time.

As you are trying to listen on Public IP address and on Local IP , please try this one

 IPEndPoint ep =  new  IPEndPoint(IPAddress.Any, yourportnumber );
 sck.Bind(ep) ; 

this will create a listener that listen on All the ip addresses of your PC , Otherwise you better use a Seperate socket object

IF I were you , I would not parse local IPAddress from a textbox instead i would use something like IPAddress.Loopback