I'm doing a client and server program and I am having issues getting my computer's local IP address. Dns.GetHostAddresses(Dns.GetHostName()); returns 2 addresses for me. My computer is behind a router with 2 others on the network. The code returns 192.168.1.2 (I know this is my computer), and 192.168.56.1 (I have no idea what this is.)

If that code returns more than one address, how can I test to see which one belongs to the computer the server is running on?

Also, I had originally tried to have my server listen for connections on my computer's external IP, but for some reason it kept complaining that the format wasn't correct. I couldn't figure out why, because it looked fine to me. So I did the above.

But if my client is running on another network, tries to send data to my computer's external IP (27.432.810.410; not real), and my server is listening on my computer's local IP (192.168.1.2), that's not going to work. Or will it??

Recommended Answers

All 11 Replies

Just use IPAddress.Any and you don't have to worry about the local machines IP address. You will most likely have to configure your router to forward the port(s) you'll be using to your machine, however.

The first address is that of your router...the one that gives you the link to your network.
Google public and private IP address for more information.
You may use this code for finding the IP Address of your own machine:

string myHost = System.Net.Dns.GetHostName();
// Show the hostname
//MessageBox.Show(myHost);
// Get the IP from the host name
string myIP = System.Net.Dns.GetHostEntry(myHost).AddressList[0].ToString();
string myIP1 = System.Net.Dns.GetHostEntry(myHost).AddressList[1].ToString();
// Show the IP
label1.Text = myIP;//gives IP Address of your router
label2.Text = myIP1;//gives IP Address of your machine

Alright. I used IPAddress.Any and the client successfully sent a string to the server program with both running on my computer. However I had a chance to test it on a different network today and the client failed to send the string, yet neither program showed any error messages!

This is what my client does to send the string to the server.

private void ConnectButton_Click(object sender, EventArgs e)
        {
            try
            {
                TcpClient tcpclnt = new TcpClient();
                InfoBox.AppendText("Connecting...\r\n");

                tcpclnt.Connect("12.345.678.910", 9852); //External IP and port the server is listening on

                //Did not reach this point. But no errors.
                InfoBox.AppendText("Connected.\r\n");

                string str = "Hello world!";
                Stream stm = tcpclnt.GetStream();

                ASCIIEncoding asen = new ASCIIEncoding();
                byte[] ba = asen.GetBytes(str);
                InfoBox.AppendText("Sending.\r\n");

                stm.Write(ba, 0, ba.Length);

                byte[] bb = new byte[100];
                int k = stm.Read(bb, 0, 100);

                for (int i = 0; i < k; i++)
                    InfoBox.AppendText(Convert.ToChar(bb[i]).ToString());

                tcpclnt.Close();
            }

            catch (Exception E)
            {
                InfoBox.AppendText("Error: " + E.ToString());
            }

        }

And here is what my server does to listen for connections and data.

public void Start()
        {
            IP = IPAddress.Any;

            TcpListener Listener = new TcpListener(IP, Port);
            Listener.Start();

            List<char> chars = new List<char>();

            while (true)
            {
                try
                {
                    Socket S = Listener.AcceptSocket();

                    byte[] b = new byte[100];
                    int k = S.Receive(b);

                    for (int i = 0; i < k; i++)
                    {
                        chars.Add(Convert.ToChar(b[i]));
                    }

                    LogCT(string.Join("", chars)); //Update textbox with string sent by client
                    chars.Clear();

                    ASCIIEncoding ASCIIEnc = new ASCIIEncoding();
                    S.Send(ASCIIEnc.GetBytes("The string was recieved by the server.")); //Send response to client
                    LogCT("Sent answer.");
                }

                catch (Exception E)
                {
                    LogCT(E.ToString());
                }
            }
        }

I still need help with this. I've rewritten the server a little and getting the client to log in to it is almost complete. I still cannot communicate with the server using my computer's external IP address. I must use its address on my router (192.168.1.2) on my network of course to send messages to the server.

The client finally gave me this error.

Error: System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond ##.###.###.###:9852 (# is my external IP)

My server is listening on "all network interfaces", if I understand IPAddress.Any correctly, with the port I specified. (which is also forwarded on my router)

Here is part of my rewritten server's code. My client's code remains the same, except for sending the password I type instead of "Hello world".

public void Initialize(string s_Port, string Password)
        {
            try
            {
                Log("Initializing server...");

                Log("Getting External IP...");
                WebClient GetIPClient = new WebClient();
                UTF8Encoding UTF8 = new UTF8Encoding();

                string DownloadedIP = UTF8.GetString(GetIPClient.DownloadData("http://www.whatismyip.com/automation/n09230945.asp"));
                IPAddress ExternalIP = IPAddress.Parse(DownloadedIP);

                Log("Setting IP...");
                IPAddress IP = IPAddress.Any;

                Log("Checking port value...");
                int i_Port = Convert.ToInt32(s_Port);

                Log("Creating Listening Socket");
                TcpListener ListeningSocket = new TcpListener(IP, i_Port);

                ParameterizedThreadStart pts_ListeningThread = new ParameterizedThreadStart(
                                    delegate
                                    {
                                        WaitForLogin(ListeningSocket, Password);
                                    });

                Thread t_ListeningThread = new Thread(pts_ListeningThread);
                t_ListeningThread.Start();

                Log("Initialization complete. Waiting for client login.");

                Log("\r\n\t\t Client Connection Information:", false);
                Log("\t\t\t IP Address: " + ExternalIP, false);
                Log("\t\t\t Port: " + i_Port, false);
            }

            catch (Exception E)
            {
                Log("Failed to initialize.\r\n" +
                    "Calling Method: " + E.TargetSite + "\r\n" +
                    "Stack Trace: " + E.StackTrace + "\r\n" +
                    "Message: " + E.Message + "\r\n");
            }
        }

        private void WaitForLogin(TcpListener ListeningSocket, string Password)
        {
            bool ValidLogin = false;

            ListeningSocket.Start();
            List<char> RecievedChars = new List<char>();

            while (ValidLogin == false)
            {
                Thread.Sleep(1000);

                Socket S = ListeningSocket.AcceptSocket();

                byte[] b = new byte[100];
                int k = S.Receive(b);

                for (int i = 0; i < k; i++)
                {
                    RecievedChars.Add(Convert.ToChar(b[i]));
                }

                ASCIIEncoding ASCIIEnc = new ASCIIEncoding();

                if (string.Join("", RecievedChars) == Password)
                {
                    LogCT("Client sent correct password.");
                    S.Send(ASCIIEnc.GetBytes("Password accepted. Waiting for commands."));
                }

                else
                {
                    LogCT("Client sent an invalid password.");
                    S.Send(ASCIIEnc.GetBytes("Invalid password."));
                }
            }
        }

Can anyone please help me fix this?

Are you trying to connect from a computer that is outside your internal network?

Did you unblock the port in the Windows Firewall?

I believe so. When I first ran the server Windows Firewall asked me if I wanted to unblock it, and I did. I'm completely rewriting the client right now so maybe I'll find something.

Whatever I did it works now...I need to do one more thing until I'm done with it. When my client requests to connect to the server, how can I get the IP Address of the computer the request is coming from?

The RemoteEndpoint property of the Socket should return an IPEndpoint object, which will have the address.

Thank you. Both programs finally work how I want now.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.