0

I am currently trying to read in messages from a port and for some reason I am able to do this using a TCPClient however I am recieving an error when trying to use a TCPListener. I was wondering if anyone could tell me why, or where I may be going wrong?

This is the code which works, and I am able to read messages from:

 public static NetworkStream nwStream;
 public static TcpClient client = new TcpClient();
 public const string address = "10.10.10.151";
 public const int port = 9004; //both never change


 public MainWindow()
    {
        InitializeComponent();

        client.Connect(address, port);

        connected = true;

        if (connected == true)
        {
            readInTxtBox.Text = "Connected";
        }
}

And this is the code which throws an error:

 static void Main(string[] args)
    {
        IPAddress ipAddress = IPAddress.Parse("10.10.10.151");
        TcpListener Listener = new TcpListener(ipAddress, 9004);
        Listener.Start(); //this is where the error is!
        Socket Client = Listener.AcceptSocket();
        using (NetworkStream PMS_NS = new NetworkStream(Client))
        {
            StreamReader sr = new StreamReader(PMS_NS);
            Console.WriteLine(sr.ReadLine());
        }
        Console.ReadLine();
    }

The error says:

An unhandled exception of type 'System.Net.Sockets.SocketException' occurred in System.dll Additional information: The requested address is not valid in its contexts

Lucy Copp
  • 95
  • 10
  • What makes you think you can exchange TcpClient for TcpListener? The latter is used to listen, the former to connect... – CodeCaster Aug 03 '17 at 10:58

2 Answers2

2

You can only bind to a local IP of the machine you're running on - presumably 10.10.10.151 isn't one. You can use IPAddress.Any to bind to any available interface, which is usually the desired behaviour for a Server. Alternatively, use the TCPListener.Create static function to just specify the port and skip specifying the IP.

If you do want to bind to a specific local IP then your current approach should be fine, just use an IP that's assigned to one of your network interfaces (see ifconfig on Windows or ip a on linux) instead of 10.10.10.151.

hnefatl
  • 5,860
  • 2
  • 27
  • 49
1

Maybe the given IP Adress is not your IP adress. Try to use

 TcpListener Listener = new TcpListener(IPAdress.Any, 9004);

instead of

IPAddress ipAddress = IPAddress.Parse("10.10.10.151");
TcpListener Listener = new TcpListener(ipAddress, 9004);
Michael Meyer
  • 2,179
  • 3
  • 24
  • 33