How to set IP address of client manually in .net socket program

Sachin K S picture Sachin K S · Dec 17, 2012 · Viewed 8.9k times · Source

I created a multithreaded client-server chat application and want to test my application with multiple clients. I'm planning to create a simulator in client side which create a random port and IP. By that I mean my client system should run with multiple ports (without running multiple times).

I tried to find out the part of the code which gives client IP and port number in the client class, but couldn't figure it out. I only found the part which gives server IP and port.

This is my connection establishing part

private void cmdConnect_Click(object sender, System.EventArgs e)
    {
        try
        {
            //create a new client socket ...
            m_socWorker = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            String szIPSelected  = txtIPAddress.Text;
            String szPort = txtPort.Text;
            int  alPort = System.Convert.ToInt16 (szPort,10);


            System.Net.IPAddress    remoteIPAddress  = System.Net.IPAddress.Parse(szIPSelected);
            System.Net.IPEndPoint   remoteEndPoint = new System.Net.IPEndPoint(remoteIPAddress, alPort);
            m_socWorker.Connect(remoteEndPoint);
        }
        catch (System.Net.Sockets.SocketException se)
        {
            MessageBox.Show ( se.Message );
        }
    }

and my data sending part

private void cmdSendData_Click(object sender, System.EventArgs e)
    {
        try
        {
            Object objData = txtData.Text;
            byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString ());
            m_socWorker.Send (byData);
        }
        catch(System.Net.Sockets.SocketException se)
        {
            MessageBox.Show (se.Message );
        }
    }

Answer

Hristo Iliev picture Hristo Iliev · Dec 17, 2012

If you really need to set the client socket address before making a connection to the server, and it is often a valid scenario when one wants to force the kernel to bind to a specific local address on multihomed systems, you may call Socket.Bind() before you call Socket.Connect():

IPAddress  localIPAddress = IPAddress.Parse(szLocalIP);
IPEndPoint localEndPoint  = new IPEndPoint(localIPAddress, 0);
m_socWorker.Bind(localEndPoint);

m_socWorker.Connect(remoteEndPoint);

You may also explicitly specify the local port number in the IPEndPoint constructor, but you have to make sure, that the port is not in use. If you leave the port number equal to 0, then the system would pick an (almost) arbitrary free port number.

Note that you cannot just pick an arbitrary client IP address - it must be one of the addresses, configured on your system's enabled network interfaces. See the output of ipconfig /all for what is configured. You can assign more than one IP address to an interface if you simply want to test.