Raikoug
Raikoug

Reputation: 357

c# TCP/IP communication error: Address requested non valid in own context

as suggested in an other SO question, I followed this tutorial https://www.youtube.com/watch?v=ObcGBT4ZWEU This works on lan but when I try over internet with IP taken from any web service, and using port 80, it gives the error in the image error

The italian part is "Address requested non valid in own context" (I dunno if this would be english text for this error) The error comes out with "Start" button (button1). the code is:

private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            epLocal = new IPEndPoint(IPAddress.Parse(textLocalIp.Text), Convert.ToInt32(textLocalPort.Text));
            sck.Bind(epLocal);

            epRemote = new IPEndPoint(IPAddress.Parse(textFriendsIp.Text), Convert.ToInt32(textFriendsPort.Text));
            sck.Connect(epRemote);

            byte[] buffer = new byte[1500];
            sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);

            button1.Text = "Connected";
            button1.Enabled = false;
            button2.Enabled = true;
            textMessage.Focus();

        }
        catch (Exception exp)
        {
            MessageBox.Show(exp.ToString());
        }

    }

the socket variables are declared as global:

    Socket sck;
    EndPoint epLocal, epRemote;

and initialized as:

        sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

Any suggestion?! Thanks!!

edit: i successfull get an englsh error!!! enter image description here In italian versione i've the precise line too and it is:

sck.Bind(epLocal);

Upvotes: 0

Views: 381

Answers (1)

Ben Voigt
Ben Voigt

Reputation: 283624

You haven't told us what the value of textLocalIp.Text is, but the problem likely lies there.

You can't bind to just any IP address, it has to be the address of one of the network cards in your computer, or 0.0.0.0 for "any". Trying to use your router's public IP address or your friend's IP address will not work.

Most of the time, you should skip calling Bind and just let Windows pick the local address and port. If you want a specific port, then bind using INADDR_ANY which is 0.0.0.0, along with that port.

Upvotes: 1

Related Questions