Search code examples
c#socketswebsocketsocial-networkingserversocket

Client is not connecting to Server, instead getting invalid pointer address


I want to connect server from my pc. but its not working. its always showing error. I also want to send a message to server from client side so please help me what should i do?

The system detected an invalid pointer address in attempting to use a pointer argument in a call

My code is :

public partial class Form1 : Form
    {
        Socket socket;
        IPAddress ipAddress;
        string address = "192.168.1.203";
        public Form1()
        {
            InitializeComponent(); 
        }

        private void btnStartServer_Click(object sender, EventArgs e)
        {
            SocketPermission socketPermission = new SocketPermission(NetworkAccess.Connect, TransportType.Tcp, "", SocketPermission.AllPorts);
            socketPermission.Demand();
            IPHostEntry ipHOst = Dns.GetHostEntry("");
            ipAddress = ipHOst.AddressList[0];
            IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse(address), 4532);
            socket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            socket.NoDelay = false;
            socket.Connect(ipEndPoint);
            txtClinet1.Text = "Socket connected to " + socket.RemoteEndPoint.ToString();
        }

    }

Solution

  • What makes you think that AddressList[0] is the one you can use? According to the DOCS you have to iterate through the list until you find the correct one.

    For example:

    private void button1_Click(object sender, EventArgs e)
        {
            SocketPermission socketPermission = new SocketPermission(NetworkAccess.Connect, TransportType.Tcp, "", SocketPermission.AllPorts);
            socketPermission.Demand();
            IPHostEntry ipHOst = Dns.GetHostEntry("");
            for (int i = 0; i < ipHOst.AddressList.Length; i++)
            {
    
                ipAddress = ipHOst.AddressList[i];
                IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse(address), 4532);
                socket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                socket.NoDelay = false;
                try
                {
                    socket.Connect(ipEndPoint);
                    MessageBox.Show("Socket connected to " + socket.RemoteEndPoint.ToString());
                    break;
                }
                catch (Exception eX)
                {
                    MessageBox.Show(eX.Message);
                }
            }
    
        }
    

    In my computer it connects in the third address AddressList[2];