TCP port reading in C# - c#

I have an application running at remote server which writes data (string) to its local port, I want to read this systems port by another C# application running at some other system, When i connect to this port of the remote machine I get an error that the target machine actively refused the connection.
Any suggestion will be appreciated.
I have tried this code:
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
var ipaddress = IPAddress.Parse("192.168.1.12");
IPAddress add = new IPAddress(ipaddress.GetAddressBytes());
EndPoint ep = new IPEndPoint(add, 7862);
sock.Connect(ep);
if (sock.Connected)
{
byte[] bytes = new byte[256];
int i = sock.Receive(bytes);
Console.WriteLine(Encoding.UTF8.GetString(bytes));
}
Here 192.168.1.12 is the IP address of the remote system, where an application is writing string continuously to port 7862. I need to read the value from that port via a C# application

I had written a program like that while ago... i copy paste it as it is, dont forget to allow "port" to the firewall and NAT so that the packet actually gets through
class Transmitter
{
public Boolean Transmit(String ip ,String port, String data){
TcpClient client = new TcpClient();
int _port = 0;
int.TryParse(port, out _port);
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse(ip), _port);
client.Connect(serverEndPoint);
NetworkStream clientStream = client.GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes(data);
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
return true;
}
}
class Listener
{
private TcpListener tcpListener;
private Thread listenThread;
// Set the TcpListener on port 13000.
Int32 port = 8081;
IPAddress localAddr = IPAddress.Parse("192.168.1.3");
Byte[] bytes = new Byte[256];
MainWindow mainwind = null;
public void Server(MainWindow wind)
{
mainwind = wind;
this.tcpListener = new TcpListener(IPAddress.Any, port);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
}
private void ListenForClients()
{
this.tcpListener.Start();
while (true)
{
//blocks until a client has connected to the server
TcpClient client = this.tcpListener.AcceptTcpClient();
//create a thread to handle communication
//with connected client
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
}
private void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = 0;
try
{
//blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch
{
//a socket error has occured
// System.Windows.MessageBox.Show("socket");
break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
// System.Windows.MessageBox.Show("disc");
break;
}
//message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
mainwind.setText(encoder.GetString(message, 0, bytesRead));
//System.Windows.MessageBox.Show(encoder.GetString(message, 0, bytesRead));
// System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
}
tcpClient.Close();
}
}

Related

C# Unique ID for tcp/ip server client connection

below is roughly how I normally do when trying to setup a connection on my server with my slient device:
IPEndPoint localEP = new IPEndPoint(IPAddress.Any, nConst3rdPartyPort);
the3rdPartyListener = new Socket(localEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
the3rdPartyListener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
the3rdPartyListener.Bind(localEP);
the3rdPartyListener.Listen(100);
the3rdPartyListener.BeginAccept(new AsyncCallback(AcceptConnectBack), the3rdPartyListener);
Any client device can connect to my server if they know the server ip and port number.
Now, I want to do filtering of client device. Only specific client device can connect to my server.
Is it that we can insert a unique ID to client so that the client with only that unique ID can connect to my server?
How do we ensure that the client is the specific client that we want?
This is for security reason to prevent unauthorized client from connecting to the server.
You can use IPEndPoint Address method to retrieve the remote IPAddress and make a whitelist to check who can connect your server.
string clientIP = ((IPEndPoint)(the3rdPartyListener.RemoteEndPoint)).Address.ToString();
------------------------------------------------------------------------------------------------------------------------------------
Updated:
I'm not sure Csharp Socket has verified device method or not. But I have a method on below.
Use NetworkStream to pass data from Client to Server that verified the client.
Server Side:
TcpClient client;
TcpListener server;
Thread thread;
Thread threadTwo;
byte[] datalength = new byte[4];
public Server()
{
InitializeComponent();
server = new TcpListener(IPAddress.Any, 2018);
server.Start();
thread = new Thread(() =>
{
client = server.AcceptTcpClient();
ServerReceive();
}
thread.Start();
}
void ServerReceive()
{
networkStream = client.GetStream();
threadTwo = new Thread(() =>
{
while ((i = networkStream.Read(datalength, 0, 4)) != 0)
{
byte[] data = new byte[BitConverter.ToInt32(datalength, 0)];
networkStream.Read(data, 0, data.Length);
this.Invoke((MethodInvoker)delegate
{
if(Encoding.Default.GetString(data) == "unique ID")
{
//Do your job
}
}
}
}
threadTwo.Start();
}
Client Side:
NetworkStream networkStream;
TcpClient client;
byte[] datalength = new byte[4];
public Client()
{
InitializeComponent();
try
{
client = new TcpClient("your server ip", 2018);
ClientSend("unique ID");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void ClientSend(string msg)
{
try
{
networkStream = client.GetStream();
byte[] data;
data = Encoding.Default.GetBytes(msg);
int length = data.Length;
byte[] datalength = new byte[4];
datalength = BitConverter.GetBytes(length);
networkStream.Write(datalength, 0, 4);
networkStream.Write(data, 0, data.Length);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

C# udp Socket don't receive in long way connections ( vps to client )

I have an udp client server source on C# and now I have a problem: I test my source on localhost but it doesn't receive on long way connections for example a VPS to a client.
Client:
private static void StartListener()
{
bool done = false;
UdpClient listener = new UdpClient(listenPort);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
try
{
while (!done)
{
byte[] bytes = listener.Receive(ref groupEP);
Thread.Sleep(100);
byte[] dcbufresponse = new byte[512];
dcbufresponse = Encoding.ASCII.GetBytes("0xc00901");
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(ipaddresssv), 9052);
s.SendTo(dcbufresponse, dcbufresponse.Length, SocketFlags.None, ipep);
done = true;
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{
listener.Close();
}
}
Server :
private static Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
private static IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(ipnow), 9052);
s.SendTo(dcbuf, dcbuf.Length, SocketFlags.None, ipep);
Console.WriteLine("sended");
sended.Add(ipnow);
try
{
listener.Client.ReceiveTimeout = 5000;
byte[] bytes = listener.Receive(ref groupEP);
string dcresponse = Encoding.ASCII.GetString(bytes, 0, bytes.Length);
Console.WriteLine(dcresponse);
}
Problem is this : client doesn't receive anything and client can not send to server after receiving ...
Edit :
My Serve Have Two Ip Address !
and i thinking that i must bind once of my two ip address to my udp client :-?
do you think that its work ?

NullReferenceException was unhandled in TcpListener in c# [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 9 years ago.
I am trying to connect TcpListener to localhost for ip address 127.0.0.1 and port number 8081
but I'm getting an error
NullReferenceException was unhandled
Object reference not set to an instance of an object..
And here is my code ...
public class Listener
{
private TcpListener tcpListener;
private Thread listenThread;
Int32 port = 8081;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
Byte[] bytes = new Byte[256];
public void ListenForClients()
{
//getting error at this line..
this.tcpListener.Start();
while (true)
{
//blocks until a client has connected to the server
TcpClient client = this.tcpListener.AcceptTcpClient();
//create a thread to handle communication
//with connected client
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
}
public void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = 0;
try
{
//blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch
{
//a socket error has occured
// System.Windows.MessageBox.Show("socket");
break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
// System.Windows.MessageBox.Show("disc");
break;
}
//message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
String textdata = encoder.GetString(message, 0, bytesRead);
System.IO.File.AppendAllText(#"D:\ipdata.txt", textdata);
//mainwind.setText(encoder.GetString(message, 0, bytesRead));
//System.Windows.MessageBox.Show(encoder.GetString(message, 0, bytesRead));
// System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
}
tcpClient.Close();
}
}
And I am getting error at the following line of the code...
this.tcpListener.Start();
Your TcpListener is null. You need to call new on it and create an actual instance of it.
private TcpListener tcpListener;
Should probably be
private TcpListener tcpListener = new TcpListener();
You have only declared tcpListener
private TcpListener tcpListener;
It is not having any value. It is null.
You have to define it first before using it.
try
private TcpListener tcpListener = new TcpListener();

TCPListener does not accept clients

I'm running a TCP server in c#. The program seems to run and hold for new clients (it stop on TcpClient client = this.tcpListener.AcceptTcpClient();) waiting for new connections. However if I check the network (using the netstat command) the server is not listening, wich means is not running. I also tryied with different ports, but I guess than port 80 should be good for testing (I also tried with other ports and none of them worked). What is wrong in my code? Maybe the OS is blocking the server?
namespace TCPServer
{
class TestClass
{
static void Main(string[] args)
{
Server TCPServer = new Server();
// Display the number of command line arguments:
System.Console.WriteLine(args.Length);
}
}
class Server
{
private TcpListener tcpListener;
private Thread listenThread;
public Server()
{
this.tcpListener = new TcpListener(IPAddress.Any, 80);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
System.Console.WriteLine("Server started");
}
//starts the tcp listener and accept connections
private void ListenForClients()
{
this.tcpListener.Start();
System.Console.WriteLine("Listener started");
while (true)
{
System.Console.WriteLine("Accepting Clients");
//blocks until a client has connected to the server
TcpClient client = this.tcpListener.AcceptTcpClient();
System.Console.WriteLine("Client connected");
//create a thread to handle communication
//with connected client
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
}
//Read the data from the client
private void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client; //start the client
NetworkStream clientStream = tcpClient.GetStream(); //get the stream of data for network access
byte[] message = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = 0;
try
{
//blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch
{
//a socket error has occured
break;
}
if (bytesRead == 0) //if we receive 0 bytes
{
//the client has disconnected from the server
break;
}
//message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
//Reply
byte[] buffer = encoder.GetBytes("Hello Client!");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
tcpClient.Close();
}
}
}
Update:
I configure the app to get a firewall exemption. Im running in windows7. I also checked with the port 3000 and nothing listening on that port. I use the netstat output to determine if its listening or not.

C# tcp server-client, cannot send a message

C# client can not write message to server, I think the parsing byte to string is bad. I connect in client class with the connect method via ipaddress and port. However I start the compile the server don't change, but client will turn off.
Here is my Server:
class Server
{
private TcpListener tcpListener;
private Thread listenThread;
public Server()
{
this.tcpListener = new TcpListener(IPAddress.Parse("10.0.0.44"), 3000);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
}
private void ListenForClients()
{
this.tcpListener.Start();
while (true)
{
//blocks until a client has connected to the server
TcpClient client = this.tcpListener.AcceptTcpClient();
//create a thread to handle communication
//with connected client
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
Thread clientThreadSend = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
clientThreadSend.Start(client);
}
}
private void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
TcpClient sendClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = 0;
try
{
//blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch
{
//a socket error has occured
break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
break;
}
//message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
Console.WriteLine("To: " + tcpClient.Client.LocalEndPoint);
Console.WriteLine("From: " + tcpClient.Client.RemoteEndPoint);
Console.WriteLine(encoder.GetString(message, 0, bytesRead));
clientStream.Flush();
sendToClient("Test back", sendClient);
}
tcpClient.Close();
}
public void sendToClient(String line, TcpClient client)
{
try
{
NetworkStream stream = client.GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes(line + "\0");
stream.Write(buffer, 0, buffer.Length);
stream.Flush();
}
catch
{
Console.WriteLine("Client Disconnected." + Environment.NewLine);
}
}
public void broadcast(String line, TcpClient thisClient)
{
sendToClient(line, thisClient);
}
static void Main(string[] args)
{
new Server();
}
}
Here is my client:
public class Client
{
TcpClient _tcpClient;
// Connects the client to a server at the specified
// IP address and port.
public void Connect(IPAddress address, int port)
{
_tcpClient = new TcpClient();
IPEndPoint serverEndPoint = new IPEndPoint(address, port);
_tcpClient.Connect(serverEndPoint);
// Create a thread to read data sent from the server.
ThreadPool.QueueUserWorkItem(
delegate
{
Read();
});
}
// Sends bytes to the server.
public void Send(byte[] buffer)
{
_tcpClient.GetStream().Write(
buffer, 0, buffer.Length);
_tcpClient.GetStream().Flush();
}
public void Read()
{
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = _tcpClient.GetStream().Read(buffer, 0, 4096);
Console.WriteLine(encoder.GetString(buffer, 0, bytesRead));
}
}
public void Dispose()
{
_tcpClient.Close();
}
public static void Main(string[] args)
{
Client c = new Client();
c.Connect(IPAddress.Parse("10.0.0.44"), 3000);
}
}
Deadlock
your client is not sending the data and the server is also not able to send any data since it is getting blocked at
bytesRead = clientStream.Read(message, 0, 4096);

Categories

Resources