HoNgOuRu
HoNgOuRu

Reputation: 249

"Can´t open socket or connection refused" with .NET

Im getting a connection refused when I try to send some data to my server app using netcat.

server side:

IPAddress ip;
ip = Dns.GetHostEntry("localhost").AddressList[0];
IPEndPoint ipFinal = new IPEndPoint(ip, 12345);
Socket socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(ipFinal);
socket.Listen(100);
Socket handler = socket.Accept(); ------> it stops here......nothing happens

Upvotes: 5

Views: 13740

Answers (4)

If you are using Android emulator, whenever it is under Android Studio or Xamarin, its IP is 10.0.2.2

Example: http://10.0.2.2:8585/v1/planificacion/planoperativo/cpercodigo/7000012312

Upvotes: 0

HoNgOuRu
HoNgOuRu

Reputation: 249

Problem solved, I had to move 1 position in the array, cause the first position points to an IPv6 address.

IPAddress ip;
ip = Dns.GetHostEntry("localhost").AddressList[1];
IPEndPoint ipFinal = new IPEndPoint(ip, 12345);
Socket socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(ipFinal);
socket.Listen(100);
Socket handler = socket.Accept(); //------> it stops here......nothing happens

Upvotes: 7

Bill
Bill

Reputation: 2461

There is absolutely nothing wrong with your code, it is functioning perfectly.

The call to Accept() method on the Socket class will block until a connection attempt is made from a client to your TCP port 12345.

"It stops here; nothing happens" is correct and expected behavior, but not accurate description.

What is happening is that your socket is waiting for a client connection.

See: http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.accept.aspx

"In blocking mode, Accept blocks until an incoming connection attempt is queued. Once a connection is accepted, the original Socket continues queuing incoming connection requests until you close it."

To test your code, open a telent client (type "telnet" in a command prompt), and enter the command "open localhost 12345". Your code will 'wake up'.

Upvotes: 2

Robert Davis
Robert Davis

Reputation: 2265

Have you tried using a TcpListener instead?

TcpListener listener = new TcpListener(IPAddress.Any, 12345);
listener.Start();
TcpClient client = listener.AcceptTcpClient();

I've found it much easier to use TcpListner and TcpClient rather than Sockets.

Upvotes: 1

Related Questions