Socket Exception error

0

I have a networking socket program in C#.net. I have to connect with an ip: 169.254.74.65 and port:7998 and my ip is:169.254.74.63. So I have this code:

using System;
using System.Net;
using System.Net.Sockets;

class MyTcpListener{
   public static void Main(){
       TcpListener server = null;
         try{
             Int32 port = 7998;
             IPAddress localAddr = IPAddress.Parse("169.254.74.65");
             server = new TcpListener(localAddr, port);
             server.Start();
             Byte[] bytes = new Byte[500];
             String data = null;
             while (true){
             Console.Write("Waiting for a connection... ");
             TcpClient client = server.AcceptTcpClient();
             data = null;
             NetworkStream stream = client.GetStream();
             int i;
             while ((i = stream.Read(bytes, 0, bytes.Length)) != 0){
             data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
             Console.WriteLine("Received: {0}", data);
             }
             client.Close();}
          }
        catch (SocketException e){
        Console.WriteLine("SocketException: {0}", e);}
        finally{ server.Stop();  }

Ping works fine between two IPs. Even telnet 169.254.74.65 7998 gives me proper result and listens to the correct messages. So the connection is solid. But when I run the above code it shows an exception:

> SocketException: System.Net.Sockets.SocketException (0x80004005): The requested address is not valid in its context
   at System.Net.Sockets.Socket.UpdateStatusAfterSocketErrorAndThrowException(SocketError error, String callerName)
   at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)
   at System.Net.Sockets.Socket.Bind(EndPoint localEP)
   at System.Net.Sockets.TcpListener.Start(Int32 backlog)
   at System.Net.Sockets.TcpListener.Start()
   at MyTcpListener.Main() in C:\Users\Administrator\source\repos\TCPListener\TCPListener\Program.cs:line 12

What is the problem here?

c#
.net
sockets
exception
asked on Stack Overflow Mar 19, 2018 by Sayan Sen

1 Answer

0

Your code works for me:

Have you actually hit your server at 127.0.0.1:7998 from a client socket code?

enter image description here

Update So your Server IP is 169.xx.xx.65, while your own DEV machine IP is 169.xx.xx.63 Your code is something which creates a TCP Server connection. While (if I am not wrong) - you only need to connect to that HL7 machine.

Understand that the HL7 machine will be the server and your machine will be the client. So you just need TcpClient. Something like:

TcpClient client = new TcpClient("169.xx.xx.65", 7998);

Use Connect/GetStream etc methods per: https://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient(v=vs.110).aspx

answered on Stack Overflow Mar 19, 2018 by Prateek Shrivastava • edited Mar 19, 2018 by Prateek Shrivastava

User contributions licensed under CC BY-SA 3.0