Unable to connect from remote machine - c#

I have some kind of problem and I can't check this at home if its working or not.
Here is the code
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using System.Net.Security;
class Program
{
private static IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
private static int port = 6000;
private static string data = null;
static void Main(string[] args)
{
Thread thread = new Thread(new ThreadStart(receiveThread));
thread.Start();
Console.ReadKey();
}
public static void receiveThread()
{
while (true)
{
TcpListener tcpListener = new TcpListener(ipAddress, port);
tcpListener.Start();
Console.WriteLine("Waiting for connection...");
TcpClient tcpClient = tcpListener.AcceptTcpClient();
Console.WriteLine("Connected with {0}", tcpClient.Client.RemoteEndPoint);
while (!(tcpClient.Client.Poll(20, SelectMode.SelectRead)))
{
NetworkStream networkStream = tcpClient.GetStream();
StreamReader streamReader = new StreamReader(networkStream);
data = streamReader.ReadLine();
if(data != null)
Console.WriteLine("Received message: {0}", data);
}
Console.WriteLine("Dissconnected...\n");
tcpListener.Stop();
}
}
}
I have a simple program as well to connect to this and then send a string with data. It works fine on localhost but there is a problem when I'm trying to connect with a different coputer.
I even turned off the firewall on my PC and router, as I did on my friend's laptop. Every time I have tried to connect, his computer refused connection. Maybe I'm doing something wrong?
Of course, ipAddress is a local address now since it's only working with that at the moment. Any suggestions what to do?

You need to set it to accept connections from any IP, there is an IPAddress overload function for this:
System.Net.IPAddress.Any
use it instead of 127.0.0.1 and it will fix your problem.

You're listening on 127.0.0.1 which is the loopback address which is a special address that means 'this computer'. This means that you will only accept connections that are made on the same machine as the server is running on.
You need to listen on one (or more) of the server's real ip addresses.

Your problem is that the setting an IP address explicitly when you initialize the TcpListener will only allow it to accept connections from that address. Therefore, putting in the local address of 127.0.0.1 will only accept connections originating from your PC.
The implementation you want to use is as follows:
TcpListener tcpListener = new TcpListener(IPAddress.Any, port);
This will allows connections from any IP address to connect to your program on the specified port.

I think it is your computer (the server) that refuses to connect because 127.0.0.1 is local(-only).
Try this simple overload:
TcpListener tcpListener = new TcpListener(port);

Related

Public TCP server with C# hosted on my computer

I'm trying to run a game TCP/UDP server on my computer. It's working fine within the local network, but when I'm trying to run the server with my public IP, it just doesn't work. I've tried to disable the firewall in my router, set port forwarding for port 17000 and added a firewall rule to my computer. I've also bound IP to my computer.
I've checked client calls with Wireshark and I found out that the client (Unity game) is sending data to my IP, but it's giving TCP Retransmission error for every TCP packet that it is trying to send.
There is some of the code from server and client.
Server IP is set to 192.168.0.*:17000
And the client is connecting to my IP with port 17000
SERVER:
public static void Start(byte _maxPlayers)
{
MaxPlayers = _maxPlayers;
Port = 17000;
Console.WriteLine("Starting server..");
InitializeServerData();
tcpListener = new TcpListener(GetLocalIPAddress(), Port);
tcpListener.Start();
tcpListener.BeginAcceptTcpClient(new AsyncCallback(TCPConnectCallback), null);
udpListener = new UdpClient(Port, GetLocalIPAddress().AddressFamily);
udpListener.BeginReceive(UDPReceiveCallback, null);
Console.WriteLine($"Server started on {tcpListener.LocalEndpoint}.");
}
CLIENT:
public void Connect()
{
socket = new TcpClient
{
ReceiveBufferSize = dataBufferSize,
SendBufferSize = dataBufferSize
};
receiveBuffer = new byte[dataBufferSize];
socket.BeginConnect(instance.ip, instance.port, ConnectCallback, socket);
}
private void ConnectCallback(IAsyncResult _result)
{
socket.EndConnect(_result);
if (!socket.Connected)
return;
stream = socket.GetStream();
receivedData = new Packet();
stream.BeginRead(receiveBuffer, 0, dataBufferSize, ReceiveCallback, null);
}
So I've found out, that I have two-router set up, and because I was forwarding port 17000 just on one router, it didn't work.

SocketException when attempting to connect with TcpClient

When I try to create a new TcpClient I am getting a SocketException, here is my code:
public void TcpOpenConnection()
{
// The next line is where the exception is occurring.
tcpClient = new TcpClient(ipAddress, port);
connected = true;
}
I have checked to make sure the port is open with netstat -a in cmd, and I even made another function to check if the port is open:
public static bool PortCheck(int port)
{
bool portOpen = false;
IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
TcpConnectionInformation[] tcpConnInfo = ipGlobalProperties.GetActiveTcpConnections();
foreach (var tcpConn in tcpConnInfo)
{
if (tcpConn.LocalEndPoint.Port == port)
{
portOpen = true;
break;
}
}
return portOpen;
}
which returns true. The exception that I am getting is a SocketException and it is saying the machine I am trying to connect to is actively refusing the connection. What could be the issue here? I have also tried other ports, with no luck.
If you need more info please ask, and I will gladly supply more.
The exception that I am getting is a SocketException and it is saying the machine I am trying to connect to is actively refusing the connection.
This is likely an indication that the target host isn't listening on the port which could be caused by a number of reasons:
The router of the server's network is not correctly port-forwarded
The router's firewall / server's firewall is blocking the connections
The server and the client are not using the same port
The server is misconfigured
The list goes on... but essentially, this error means that the server isn't allowing the connection.
If the port is open and you try to connect to. You get SocketException because there is nothing for get the client connection.
So you need to host a Tcplistner on this port.
static void StartServer()
{
int port = 150;
TcpListener listner = new TcpListener(IPAddress.Any, port);
listner.Start();
// This line waits the client connection.
TcpClient remote_client = listner.AcceptTcpClient();
// do something with remote_client.
}
And you can connect to.
static void StartClient()
{
int port = 150;
IPAddress ip = IPAddress.Parse("127.0.0.1");
TcpClient client = new TcpClient();
client.Connect(ip, port);
// Do something with client.
}

Open TCP port using UDP?

I read something about using UDP to open ports. I can't find the original page I read but I did find this SO answer https://stackoverflow.com/a/1539394
I tried running this code. Perhaps I did something wrong? The idea (in link above) was Alice listens to port 5412, sends a UDP packet to bob from 5412 (the tcp port) to 5411. Bob (who doesn't listen) uses TCP port 5411 (the udp port) to connect to Alice 5412. I use the command line on bob to give alice IP address.
Did I do this wrong? When I run locally using my public IP address (and my network address but not 127.0.0.1) I get the exception A socket operation was attempted to an unreachable network. When I run it on Bob I get a connection timeout exception.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace TcpTest
{
class Program
{
static string localIp = "127.0.0.1";
static string remoteIP = ipaddr;
static void Main(string[] args)
{
//run remotely to connect to you using TCP
if (args.Count() > 0)
{
var t = new TcpClient(new IPEndPoint(IPAddress.Parse(localIp), 5411)); //Force port
t.Connect(args[0], 5412);
return;
}
//Run locally
//Bind TCP port
var l = new TcpListener(5412);
l.Start();
//Send UDP using the listening port to remote address/port
var u = new UdpClient(5412);
u.Connect(remoteIP, 5411);
var buf = new byte[10];
u.Send(buf, buf.Length);
//R
new Thread(SimulateRemote).Start();
//L
var c = l.AcceptTcpClient();
var af=c.Client.RemoteEndPoint;
}
static void SimulateRemote()
{
Thread.Sleep(500);
var t = new TcpClient(new IPEndPoint(IPAddress.Parse(localIp), 5411)); //Force port
t.Connect(myipaddr, 5412);
}
}
}
You can't do that.
TCP ports and UDP ports can't connect to each other. The packets you send from UdpClient.Send() have the Protocol field set to 0x11, the value for UDP, but the TCP stack only recognizes packets with Protocol set to 0x06, the value for TCP. It's part of the most-basic operation of an IP module. See RFC 791 if you want the details.

beginAccept() asynchronous server issue in C#

I'm struggling with some piece of simple code. However, I can't get it done. I have this server, which must accept connections from multiple clients (asynchronously, obviously). So, I have:
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, 8082);
TcpListener tcpListener = new TcpListener(IPAddress.Any, 8082);
server = tcpListener.Server;
server.Bind(ipEndPoint);
server.Listen(4);
server.BeginAccept(new AsyncCallback(beginConnection), server);
And,
static void beginConnection(IAsyncResult iar)
{
Console.WriteLine("Client connected");
Socket s = (Socket)iar.AsyncState;
server = s.EndAccept(iar);
server.Listen(4);
server.BeginAccept(beginConnection, s);
}
Then, when I try to connect myself, the first client works OK. It just sends a message to this server, and the server sends it back to the client. The server functions as an echo. But when I try to connect another clients it doesn't work. I have also put the Console.WriteLine("Client connected"), but the server doesn't write anything.
How can I fix this problem?
I think I'm not passing the right parameter to the first BeginAccept method. Instead of server socket, I should be passing the tcpListener.
Then I would have:
static void beginConnection(IAsyncResult iar)
{
Console.WriteLine("Client connected");
TcpListener tcpListener = (TcpListener)iar.AsyncState;
Socket s = tcpListener.Server.EndAccept(iar);
tcpListener.Server = s; // But I would have this error
server.Listen(2);
server.BeginAccept(beginConnection, s);
}
But I would have the error that I marked it up. In the first version nothing is modified, so I think this it's the issue in the first version of the code.
First, you do not need the Server property of the TcpListener. You should simply call Start(), even without Bind.
Second, EndAccept() is also should be called at TcpListener and return a TcpClient instance which you must use for sending and receiving data.
A simple example of what I just said might be presented as:
{
TcpListener listener = new TcpListener(IPAddress.Any, 8082);
listener.Start();
AcceptClient();
}
void AcceptClient()
{
listener.BeginAccept(ClientConnected, null);
}
void ClientConnected(IAsyncResult ar)
{
TcpClient client = listener.EndAccept();
AcceptClient();
// Now you can send or receive data using the client variable.
}

How to make more than 1 socket to the same host and port?

I am trying to forward multiple sockets communication to a target socket. So I need to make multiple connection to that target socket, but when I try to connect to it for the second time, I get this:
SocketException: No connection could be made because the target machine actively refused it
I think the problem is with the other end of the socket, i.e port and host and because there is already a connection between port related to my program and target port, to have a second connection I need a second port for my program.
I hope my problem be clear for you guys.
Any Idea how to do it?
This is a test program just to show the problem.
using System;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.Text;
class Sample
{
private static ManualResetEvent connectDone = new ManualResetEvent(false);
public static void Main()
{
Socket[] s = new Socket[10];
for (int i = 0; i < s.Length; i++)
{
IPAddress ipAddress;
ipAddress = IPAddress.Parse("127.0.0.1");
IPEndPoint localEndp = new IPEndPoint(ipAddress, 1100);
// Create a TCP/IP socket.
s[i] = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
connectDone.Reset();
s[i].BeginConnect(localEndp,
new AsyncCallback(ConnectCallback), s[i]);
connectDone.WaitOne();
s[i].Send(Encoding.ASCII.GetBytes(i.ToString() + ": hi.\r\n"));
}
}
private static void ConnectCallback(IAsyncResult ar)
{
Socket client = (Socket)ar.AsyncState;
// Complete the connection.
client.EndConnect(ar);
// Signal that the connection has been made.
connectDone.Set();
}
}
I even tried to bind my sockets to different ports, but still second socket gets that exception.
This error message means that there is no open port on that IP. The IP is valid but the remote host replied that it will not accept a connection on this port.
You should be getting this error even for the very first connection.
Find out why the port is not open.
Btw, you use of async connect is counter-productive. You have non of the async benefits and all of the disadvantages. But this is not the point of this question.

Categories