TcpListener doesn't detect connection - c#

I have been doing a client-server application in these days. I made a server part based on examples to launch a TcpListener and It seems to be working well.
However, It's not able to detect client connections, while the client says that It connected to the given ip and port.
Here is my code for the server side:
internal static void RunServer()
{
// Create a TCP/IP (IPv4) socket and listen for incoming connections.
ServerLogger.LogStatus("Starting listener...");
listener = new TcpListener(IPAddress.Any, Server.PORT + 2);
listener.Start();
ServerLogger.LogStatus("Starting thread listener...");
tlisten = new Thread(Listen);
tlisten.Start();
ServerLogger.LogStatus("Starting receiver...");
treceiver = new Thread(Receiver);
treceiver.Start();
ServerLogger.LogStatus("All done!");
}
internal static void Listen() // Listen to incoming connections.
{
while (running)
{
ServerLogger.LogStatus("Waiting for a connecion....");
TcpClient tcpClient = listener.AcceptTcpClient();
// The below code never runs on client connection.
ServerLogger.LogStatus("Accepting and Creating cert!");
// Create a new certification
byte[] serverCertificatebyte = Certificate.CreateSelfSignCertificatePfx("Test" + IP + RandomString(5),
new DateTime(2015, 12, 26),
new DateTime(DateTime.Today.Year, DateTime.Today.Month + 1, DateTime.Today.Day), RandomString(20));
ServerLogger.LogStatus("Created certificate!");
X509Certificate serverCertificate = new X509Certificate(serverCertificatebyte);
tcpclientbytecerts[tcpClient] = serverCertificatebyte;
tcpclientcerts[tcpClient] = serverCertificate;
ServerLogger.LogInfo("Sending Certificate!");
// Send SSL certification in bytes
tcpClient.GetStream().Write(serverCertificatebyte, 0, serverCertificatebyte.Length);
ServerLogger.LogInfo("Certificate sent to the client!");
Logger.Log(serverCertificatebyte.ToString());
// process it
ServerLogger.LogInfo("Processing");
ProcessClient(tcpClient, serverCertificate);
ServerLogger.LogInfo("Processed!");
}
}
Client side:
private SSL(string ip, int port)
{
UnityEngine.Debug.Log("Test");
if (!PrivacyHelper.IsInvocationAllowed())
{
Terminate();
}
UnityEngine.Debug.Log("Test2 " + ip + " - " + port);
UnityEngine.Debug.Log("Test3 " + IsLocalIpAddress(ip));
client = new TcpClient(ip, port);
//client.Connect(ip, port);
UnityEngine.Debug.Log("Test4 " + client.Connected); // <- This is true
var stream = client.GetStream();
UnityEngine.Debug.Log("Test5");
Byte[] cert = new Byte[65535];
UnityEngine.Debug.Log("Test6");
Int32 bytes = stream.Read(cert, 0, cert.Length);
UnityEngine.Debug.Log("Test7");
byte[] intBytes = BitConverter.GetBytes(bytes);
UnityEngine.Debug.Log("Test8");
if (BitConverter.IsLittleEndian) { Array.Reverse(intBytes);}
UnityEngine.Debug.Log("Test9");
byte[] result = intBytes;
UnityEngine.Debug.Log("Cert: " + result);
certificate1 = new X509Certificate2(result);
//client.GetStream().Read()
}
The client seems to be able to connect, It even returns true and says that It's connected. The server side doesn't detect It though. Any ideas?

Related

C# TCP Chat Working On Localhost But Message Is 0 Or Null On Other IP Addresses?

So my TCP C# client server, an oddity is happening, when the server sends a message to a client running on localhost 127.0.0.1, the message goes through no problem, but when sending the message to a client running on another IPv4, the client and server connect but the message is received as null or zero. I am wondering why the message would come through no problem on localhost, but connect and then recieve a null message on a different ip though they connect?
Server code:
{
{
{
try
{
IPAddress ipAd = IPAddress.Parse(IPV4.Text); //use local m/c IP address, and use the same in the client
/* Initializes the Listener */
TcpListener myList = new TcpListener(ipAd, 8001);
/* Start Listeneting at the specified port */
myList.Start();
MessageBox.Show("The server is running at port 8001...");
MessageBox.Show("The local End point is :" + myList.LocalEndpoint);
MessageBox.Show("Looking for other computer");
Socket s = myList.AcceptSocket();
Console.WriteLine("Found buddy " + s.RemoteEndPoint);
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes(satt.Text));
MessageBox.Show("The message " + satt.Text + " was sent to the computer with IP address " + IPV4.Text);
byte[] b = new byte[100];
int k = s.Receive(b);
for (int i = 0; i < k; i++)
Console.Write(Convert.ToChar(b[i]));
void ServerStart()
{
TcpListener listener = new TcpListener(IPAddress.Any, 8001);
listener.Start();
Console.WriteLine("Listening on port: 8001");
while (true)
{
TcpClient client = listener.AcceptTcpClient();
ThreadPool.QueueUserWorkItem(state => HandleConnection(client));
void HandleConnection(TcpClient client)
{
Socket s = myList.AcceptSocket();
Console.WriteLine("Found buddy " + s.RemoteEndPoint);
Console.WriteLine("Number of connected buddies: " + connectedbuddies++);
client.Close();
string buddylist = myList.ToString();
socketlist = s.ToString();
slist = char.Parse(socketlist);
foreach (char slist in buddylist)
{
void HandleConnection(TcpClient client)
{
TcpListener myList = new TcpListener(ipAd, 8001);
/* Start Listeneting at the specified port */
myList.Start();
Console.WriteLine("Found buddy " + s.RemoteEndPoint);
while (connectedbuddies > 1)
{
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes(satt.Text));
}
}
Console.WriteLine("Number of connected buddies: " + connectedbuddies++);
client.Close();
}
}
Client code:
try
{
TcpClient tcpclnt = new TcpClient();
tcpclnt.Connect(RecieveIPAdd.Text, 8001); // use the ipaddress as in the server program
MessageBox.Show("Connected");
Stream stm = tcpclnt.GetStream();
MessageBox.Show("Listening for information......");
byte[] bb = new byte[100];
int k = stm.Read(bb, 0, 100);
string atk = Encoding.UTF8.GetString(bb.AsSpan(0, k));
Console.WriteLine($"Connected to server at IPv4 address {RecieveIPAdd.Text} Attack command Received: {atk}.
Thank you so much, I don't know why this would happen on an IP that is not localhost?

Real server-client C# program over internet

Simple question, but after weeks of search no luck. I need to create a server-client program. Everything works well with localhost, but I need it over the internet. I work under Linux (Ubuntu).
Server:
public class SocketServer
{
private const int PORT_NO = 8001;
public SocketServer()
{
//---listen at the specified IP and port no.---
var listener = new TcpListener(IPAddress.Any, PORT_NO);
Console.WriteLine("Socket server started.");
listener.Start();
while (true)
{
//---incoming client connected---
var client = listener.AcceptTcpClient();
//---get the incoming data through a network stream---
var nwStream = client.GetStream();
var buffer = new byte[client.ReceiveBufferSize];
//---read incoming stream---
var bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);
//---convert the data received into a string---
var dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine($"{dataReceived}");
client.Close();
}
}
}
Client code:
public class Client
{
private const int PORT_NO = 8001;
private const string SERVER_IP = "xxx.xx.246.1";
public void Run()
{
while (true)
{
var textToSend = Console.ReadLine();
//---create a TCPClient object at the IP and port no.---
var client = new TcpClient(SERVER_IP, PORT_NO);
var nwStream = client.GetStream();
var bytesToSend = Encoding.ASCII.GetBytes(textToSend ?? string.Empty);
//---send the text---
Console.WriteLine("Sending : " + textToSend);
nwStream.Write(bytesToSend, 0, bytesToSend.Length);
}
}
}
For IP I used www.whatsmyip.org, and I got an error:
System.Net.Sockets.SocketException (0x80004005): Connection refused
What am I missing? Is there some real example, no just with localhost?

Tcp connection fails on LAN

I am trying to send a message from my laptop to my desktop over the LAN.
I have written a Tcp server that listens for a connection on a port, and a client that tries to connect to it and send a simple string as a message.
Server:
void Listen()
{
listener = new TcpListener(IPAddress.Any, port);
listener.Start();
while (true)
{
Debug.Log($"listening to {listener.LocalEndpoint}...");
var socket = listener.AcceptSocket();
Debug.Log("connected!");
var bytes = new byte[100];
int k = socket.Receive(bytes);
var data = Encoding.ASCII.GetString(bytes, 0, k);
Debug.Log(data);
socket.Send(new byte[] {1});
Debug.Log("responded");
socket.Close();
Debug.Log("closed connection");
}
}
Client:
public void Send()
{
client = new TcpClient();
Debug.Log("connecting...");
client.Connect("192.168.0.12", port);
Debug.Log("connected!");
var data = Encoding.ASCII.GetBytes("Hello!");
var stream = client.GetStream();
Debug.Log("sending data");
stream.Write(data, 0, data.Length);
Debug.Log("data sent! waiting for response...");
var reply = new byte[100];
stream.Read(reply,0,100);
Debug.Log("received response");
client.Close();
}
They communicate correctly when they are both on the same machine, but the client never connects to the server when I am running it on a different machine.
I have a rule in my firewall that allows an incoming connection through the port I have specified.
I have tried it with both computer's firewalls off and the connection still doesn't go through.
Any help would be greatly appreciated.

C# client communication Via UPD

I am looking for some help with communication between my server application and my client.The idea is that my client will listen for a UDP packet, read it and then execute a command based on what it reads.
My issue is that the server sends the packet however the client does nothing.
Here is a snippet of my code:
Client:
public void listen()
{
try
{
MessageBox.Show("");
UdpClient receivingUdpClient = new UdpClient(11000);
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 11000);
try
{
// Blocks until a message returns on this socket from a remote host.
Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
string[] split = returnData.Split(':');
if (split[0] == "SayHello")
{
MessageBox.show("Hello user","Hello");
}
//Note i have many commands but i shortened it to save room.
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
Server:
else if (radioButton4.Checked)
{
UdpClient udpClient = new UdpClient([IP_ADDRESS_HERE], 11000);
body = richTextBox1.Text;
title = textBox1.Text;
Command = "Message" + ":" + body + ":" + title + ":" + 4;
Byte[] sendBytes = Encoding.ASCII.GetBytes(Command);
try
{
udpClient.Send(sendBytes, sendBytes.Length);
}
catch (Exception)
{
Console.WriteLine(e.ToString());
}
}
Just wanted to see if you guys are able to find something I overlooked.
Check your Windows Firewall and verify it's not blocking your Client from opening port 11000.
Control Panel-> System and Security -> Windows Firewall

Simple UDP example to send and receive data from same socket

For some reason I am having a hard time sending and receiving data from the same socket. Anyways here is my client code:
var client = new UdpClient();
IPEndPoint ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11000); // endpoint where server is listening (testing localy)
client.Connect(ep);
// send data
client.Send(new byte[] { 1, 2, 3, 4, 5 }, 5);
// then receive data
var receivedData = client.Receive(ref ep); // Exception: An existing connection was forcibly closed by the remote host
Basically I want to create a protocol where I send a udp packet and then I expect a response. Just like the HTTP protocol for every request there is a response. This code works if the server is on a different computer. There might be the case where the server and client are on the same computer though.
Here is the server:
UdpClient udpServer = new UdpClient(UDP_LISTEN_PORT);
while (true)
{
var groupEP = new IPEndPoint(IPAddress.Any, 11000); // listen on any port
var data = udpServer.Receive(ref groupEP);
udpServer.Send(new byte[] { 1 }, 1); // if data is received reply letting the client know that we got his data
}
Edit
the reason why I cannot use tcp is because sometimes the client is behind a NAT (router) and it is simpler to do UDP hole punching than TCP.
Solution:
thanks to markmnl answer here is my code:
Server:
UdpClient udpServer = new UdpClient(11000);
while (true)
{
var remoteEP = new IPEndPoint(IPAddress.Any, 11000);
var data = udpServer.Receive(ref remoteEP); // listen on port 11000
Console.Write("receive data from " + remoteEP.ToString());
udpServer.Send(new byte[] { 1 }, 1, remoteEP); // reply back
}
Client code:
var client = new UdpClient();
IPEndPoint ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11000); // endpoint where server is listening
client.Connect(ep);
// send data
client.Send(new byte[] { 1, 2, 3, 4, 5 }, 5);
// then receive data
var receivedData = client.Receive(ref ep);
Console.Write("receive data from " + ep.ToString());
Console.Read();
(I presume you are aware that using UDP(User Datagram Protocol) does not guarantee delivery, checks for duplicates and congestion control and will just answer your question).
In your server this line:
var data = udpServer.Receive(ref groupEP);
re-assigns groupEP from what you had to a the address you receive something on.
This line:
udpServer.Send(new byte[] { 1 }, 1);
Will not work since you have not specified who to send the data to. (It works on your client because you called connect which means send will always be sent to the end point you connected to, of course we don't want that on the server as we could have many clients). I would:
UdpClient udpServer = new UdpClient(UDP_LISTEN_PORT);
while (true)
{
var remoteEP = new IPEndPoint(IPAddress.Any, 11000);
var data = udpServer.Receive(ref remoteEP);
udpServer.Send(new byte[] { 1 }, 1, remoteEP); // if data is received reply letting the client know that we got his data
}
Also if you have server and client on the same machine you should have them on different ports.
I'll try to keep this short, I've done this a few months ago for a game I was trying to build, it does a UDP "Client-Server" connection that acts like TCP, you can send (message) (message + object) using this. I've done some testing with it and it works just fine, feel free to modify it if needed.
here is my soln to define the remote and local port and then write out to a file the received data, put this all in a class of your choice with the correct imports
static UdpClient sendClient = new UdpClient();
static int localPort = 49999;
static int remotePort = 49000;
static IPEndPoint localEP = new IPEndPoint(IPAddress.Any, localPort);
static IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), remotePort);
static string logPath = System.AppDomain.CurrentDomain.BaseDirectory + "/recvd.txt";
static System.IO.StreamWriter fw = new System.IO.StreamWriter(logPath, true);
private static void initStuff()
{
fw.AutoFlush = true;
sendClient.ExclusiveAddressUse = false;
sendClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
sendClient.Client.Bind(localEP);
sendClient.BeginReceive(DataReceived, sendClient);
}
private static void DataReceived(IAsyncResult ar)
{
UdpClient c = (UdpClient)ar.AsyncState;
IPEndPoint receivedIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
Byte[] receivedBytes = c.EndReceive(ar, ref receivedIpEndPoint);
fw.WriteLine(DateTime.Now.ToString("HH:mm:ss.ff tt") + " (" + receivedBytes.Length + " bytes)");
c.BeginReceive(DataReceived, ar.AsyncState);
}
static void Main(string[] args)
{
initStuff();
byte[] emptyByte = {};
sendClient.Send(emptyByte, emptyByte.Length, remoteEP);
}

Categories