Click here to Skip to main content
15,884,473 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to create a port Listener which keeps on listening to a port and save the data in text file or XML file.I does not send any reply just listen to the port.I have found the following.but it giving error "The requested address is not valid in its context".Where am i making the mistake .I am new to socket programming so please Suggest me a suitable solution to this.

C#
Console.WriteLine("Starting echo server...");

            int port = 1234;
            TcpListener listener = new TcpListener(IPAddress.Parse("192.168.2.162"),port); 
            listener.Start();

            TcpClient client = listener.AcceptTcpClient();
            NetworkStream stream = client.GetStream();
            StreamWriter writer = new StreamWriter(stream, Encoding.ASCII) { AutoFlush = true };
            StreamReader reader = new StreamReader(stream, Encoding.ASCII);

            while (true)
            {
                string inputLine = "";
                while (inputLine != null)
                {
                    inputLine = reader.ReadLine();
                    writer.WriteLine("Echoing string: " + inputLine);
                    Console.WriteLine("Echoing string: " + inputLine);
                }
                Console.WriteLine("Server saw disconnect from client.");
                Console.ReadLine();
            }
Posted
Updated 10-Sep-19 0:56am
Comments
Richard MacCutchan 17-Oct-15 4:49am    
Do you have a device connected to that IP address and port?
gggustafson 13-Sep-19 13:36pm    
What does 192.168.2.162 point to?
Nathan Minier 14-Sep-19 7:55am    
1. Make sure that address is properly bound to your NIC.
2. Make sure something else isn't using that port.
3. Your system is likely configured to require admin rights to open a port on an external facing IP.

So, an easy way to check this:
Try running this code against a port on the localhost loopback (127.0.0.1) for testing; that generally does not require admin rights.

If that works, delegate port rights to the service account that you plan to use to run the program via netsh urlacl

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900