Cannot connect to a localhost. Is it client or localhost issue? - c#

I am trying to create a thread, which keeps a listener alive at 127.0.0.1. I am using the following code to create the listener:
IPAddress ipAddress = IPAddress.Parse("127.0.0.1"); //Localhost Ip Address
TcpListener connectionListner = new TcpListener(ipAddress, 2003);
connectedSocket = connectionListner.AcceptSocket();
connectionListner.Start();
I am facing the problem at the client-side. When I try to connect a client to the above-created localhost (separate program), I get an error.
Client Code:
class Client
{
static void Main(string[] args)
{
Console.WriteLine("client has started." + Environment.NewLine);
connectToLocalHost();
}
static void connectToLocalHost()
{
string ipaddress = "127.0.0.1";
int port = 2003;
try
{
TcpClient client = new TcpClient(ipaddress, port);
NetworkStream stream = client.GetStream();
Byte[] data = new Byte[256]; // Buffer to store the response bytes.
// String to store the response ASCII representation.
String responseData = String.Empty;
// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine("Received: {0}", responseData);
// Close everything.
stream.Close();
client.Close();
}
catch (SocketException SE)
{
Console.WriteLine("Socket Error..... " + SE.StackTrace);
}
}
}
Error:
Message = "No connection could be made because the target machine
actively refused it 127.0.0.1:2003"

Maybe you need to open this port on firewall.
https://www.tomshardware.com/news/how-to-open-firewall-ports-in-windows-10,36451.html

Related

TcpListener and TcpClient connection fails when changing from localhost to actual IP address

I'm attempting to create a simple piece of software to 'chat' between two computers to test out Networking. At the moment, all I have done is copied the TcpListener (https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.tcplistener?view=netframework-4.8) and TcpClient (https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.tcpclient?view=netframework-4.8) code to see how it works (code at end).
It all works great, but once I replace localhost ("127.0.0.1") in both files with my actual IP address (my IPv4 address that I got by typing 'ipconfig' into the command console on windows), the two won't connect.
Are there some settings I need to configure? Is this a firewall issue or something? Or am i just being super dumb? I am pretty new to C# networking.
Thanks for any help!
TcpListener:
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
class MyTcpListener
{
public static void Main()
{
TcpListener server=null;
try
{
// Set the TcpListener on port 13000.
Int32 port = 13000;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);
// Start listening for client requests.
server.Start();
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
// Enter the listening loop.
while(true)
{
Console.Write("Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
data = null;
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
// Loop to receive all the data sent by the client.
while((i = stream.Read(bytes, 0, bytes.Length))!=0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
// Process the data sent by the client.
data = data.ToUpper();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
// Send back a response.
stream.Write(msg, 0, msg.Length);
Console.WriteLine("Sent: {0}", data);
}
// Shutdown and end connection
client.Close();
}
}
catch(SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
finally
{
// Stop listening for new clients.
server.Stop();
}
Console.WriteLine("\nHit enter to continue...");
Console.Read();
}
}
TcpClient:
using System;
using System.Net.Sockets;
namespace Client
{
class Program
{
static void Main(string[] args)
{
Connect("127.0.0.1", "Test");
}
static void Connect(String server, String message)
{
try
{
// Create a TcpClient.
// Note, for this client to work you need to have a TcpServer
// connected to the same address as specified by the server, port
// combination.
Int32 port = 13000;
TcpClient client = new TcpClient(server, port);
// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
// Get a client stream for reading and writing.
// Stream stream = client.GetStream();
NetworkStream stream = client.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);
Console.WriteLine("Sent: {0}", message);
// Receive the TcpServer.response.
// Buffer to store the response bytes.
data = new Byte[256];
// String to store the response ASCII representation.
String responseData = String.Empty;
// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine("Received: {0}", responseData);
// Close everything.
stream.Close();
client.Close();
}
catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: {0}", e);
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
Console.WriteLine("\n Press Enter to continue...");
Console.Read();
}
}
}
Edit:
I DO get an exception, sorry:
SocketException: System.Net.Internals.SocketExceptionFactory+ExtendedSocketException (10060): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. [IPv4]:13000
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.Sockets.Socket.Connect(EndPoint remoteEP)
at System.Net.Sockets.Socket.Connect(IPAddress address, Int32 port)
at System.Net.Sockets.TcpClient.Connect(String hostname, Int32 port)
--- End of stack trace from previous location where exception was thrown ---
at System.Net.Sockets.TcpClient.Connect(String hostname, Int32 port)
at System.Net.Sockets.TcpClient..ctor(String hostname, Int32 port)
at Client.Client.Connect(String server, String message) in C:\Users\[User]\Documents\[User]\Programming\GenericC#\Client\Client.cs:line 22
easy enough to test and see if it is a firewall issue.
Open a command prompt
Type command telnet " " so you'd do on the machine stating the connection.If no error you're having a clear path and your application accepted the connection.
Have a look at the Firewall logs to see if a issue was
generated.
If possible you should allow your application to communicate in and out (if both are needed)
if you need to you could open the ports with your code (need elevated permission) if you see that the rule is missing. StackOverfow has quite a few example for this

No response from socket

I have built a server and client which communicate via sockets.
When i run both the server and the client on the same machine both the server and the client receive the messages which are expected.
when i run the server on a VM or a different physical machine and the client on my main machine the server receives messages fine, but the client never receives the reply's
I have made sure to dissable windows firewall and my anti virus on all 3 machines (the 2 physical and one virtual one) to ensure its not a security issue.
The relevant code is as follows
SERVER
public class SynchronousSocketListener
{
// Incoming data from the client.
public static string data = null;
public void StartListening()
{
InstructionProcessor instructionProcessor = new InstructionProcessor();
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket listener = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and
// listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
// Start listening for connections.
while (true)
{
Console.WriteLine("Waiting for a connection...");
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
data = null;
// An incoming connection needs to be processed.
while (true)
{
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf("<EOF>") > -1)
{
break;
}
}
data = data.Substring(0, data.Length - 5);
// Show the data on the console.
string response = instructionProcessor.doSomething(data);
// Echo the data back to the client.
byte[] msg = Encoding.ASCII.GetBytes(response);
handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
}
CLIENT
public static string StartClient(string message, string ip)
{
// Data buffer for incoming data.
byte[] bytes = new byte[1024];
//Declare this at class scope level so it can be returned outside of try/catch blocks
string response = null;
// Connect to a remote device.
try
{
// Establish the remote endpoint for the socket.
// This example uses port 11000 on the local computer.
IPHostEntry ipHostInfo = Dns.GetHostEntry(ip);
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);
//string hostName = Dns.GetHostName();
//string myIP = Dns.GetHostByName(hostName).AddressList[0].ToString(); ;
//Debug.WriteLine( ipAddress );
// Create a TCP/IP socket.
Socket sender = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
// Connect the socket to the remote endpoint. Catch any errors.
try
{
sender.Connect(remoteEP);
Console.WriteLine("Socket connected to {0}",
sender.RemoteEndPoint.ToString());
// Encode the data string into a byte array.
byte[] msg = Encoding.ASCII.GetBytes(message + "<EOF>");
// Send the data through the socket.
int bytesSent = sender.Send(msg);
// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
Console.WriteLine("Echoed test = {0}",
Encoding.ASCII.GetString(bytes, 0, bytesRec));
response = Encoding.ASCII.GetString(bytes, 0, bytesRec);
// Release the socket.
sender.Shutdown(SocketShutdown.Both);
sender.Close();
}
catch (ArgumentNullException ane)
{
Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
}
catch (SocketException se)
{
Console.WriteLine("SocketException : {0}", se.ToString());
}
catch (Exception e)
{
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
return response;
}
}
Maybe because client is receiving more than 1024 byte. Try to increase the size of the received buffer.
Also add if (data.IndexOf("") > -1) into the client project.

Cannot connect to another computer over TCP

I am working on a project that transfers files over TCP. It is written in .NET 4.7. The program works while the client connects on the server that is on the same computer but when I send it to a friend and I try to connect it I get an error:
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
Currently the program only sends some information about the file that will be copied and is nothing is encrypted as I cannot send even these information.
Here's the code for the server (Invoke is used because it is run on a separate thread):
private void Server_Start()
{
try
{
// Set port on 13000
int port = 13000;
//Get the ip adress for the server
String localIp;
using (var client = new WebClient())
{
// Try connecting to Google public DNS and get the local endpoint as IP
// If failed to connect set IP as local IP
if (CheckForInternetConnection())
{
try
{
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
{
socket.Connect("8.8.8.8", 65530);
IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
localIp = endPoint.Address.ToString();
}
}
catch (Exception e)
{
localIp = "127.0.0.1";
}
}
else
{
localIp = "127.0.0.1";
}
}
IPAddress IP = IPAddress.Parse(localIp);
// Create listener and start listening
server = new TcpListener(IP, port);
server.Start();
// Buffer for data
Byte[] bytes = new byte[256];
String data = string.Empty;
this.Invoke((MethodInvoker)(() => Log.Items.Add("Server started on ip: " + IP.ToString())));
while (true)
{
// Accepting requests
TcpClient client = server.AcceptTcpClient();
// Get the stream object
NetworkStream stream = client.GetStream();
// Read length of file name
byte[] nameLength = new byte[4];
stream.Read(nameLength, 0, 4);
int nameSize = BitConverter.ToInt32(nameLength, 0);
// Read the name of file
byte[] name = new byte[nameSize];
stream.Read(name, 0, nameSize);
String fileName = Encoding.UTF8.GetString(name);
// Read size of file
byte[] fileSizeB = new byte[4];
stream.Read(fileSizeB, 0, 4);
int fileSize = BitConverter.ToInt32(fileSizeB, 0);
// Read start signal
byte[] startB = new byte[9+1];
stream.Read(startB, 0, 9);
String start = Encoding.UTF8.GetString(startB);
this.Invoke((MethodInvoker)(() => Log.Items.Add("Size of name: " + nameSize.ToString())));
this.Invoke((MethodInvoker)(() => Log.Items.Add("Name of file: " + fileName)));
this.Invoke((MethodInvoker)(() => Log.Items.Add("File size: " + fileSize.ToString())));
this.Invoke((MethodInvoker)(() => Log.Items.Add("Start signal: " + start)));
// Response to client
byte[] message = Encoding.UTF8.GetBytes("Testmessage");
stream.Write(message, 0, message.Length);
}
server.Stop();
Log.Items.Add("Server started on ip: " + IP.ToString());
}
catch (Exception e)
{
this.Invoke((MethodInvoker)(() => Log.Items.Add(e)));
}
}
And here is the code for the client:
private void button1_Click(object sender, EventArgs e)
{
IPAddress iP = IPAddress.Parse(ConnectIp.Text);
int port = 13000;
int buffersize = 1024;
TcpClient client = new TcpClient();
NetworkStream netStream;
// Try to connect to server
try
{
client.Connect(new IPEndPoint(iP, port));
}
catch(Exception ex)
{
this.Invoke((MethodInvoker)(() => Log.Items.Add(ex.Message)));
return;
}
netStream = client.GetStream();
String path = "D:\\testingEnv\\test1\\testing\\Matematika\\2017\\Školsko\\2017-SS-skolsko-B-1234-zad.pdf";
String Filename = Path.GetFileName(path);
// We wish to send some data in advance:
// File name, file size, number of packets, send start and send end
byte[] data = File.ReadAllBytes(path);
// First packet contains: name size, file name, file size and "sendStart" signal
byte[] nameSize = BitConverter.GetBytes(Encoding.UTF8.GetByteCount(Filename)); // Int
byte[] nameB = Encoding.UTF8.GetBytes(Filename);
byte[] fileSize = BitConverter.GetBytes(data.Length);
byte[] start = Encoding.UTF8.GetBytes("sendStart");
// Last packet constains: "sendEnd" signal to stop reading netStream
byte[] end = Encoding.UTF8.GetBytes("sendEnd");
// Creating the first package: nameSize, fileName, fileSize and start signal
byte[] FirstPackage = new byte[4 + nameB.Length + 4 + 9];
nameSize.CopyTo(FirstPackage, 0);
nameB.CopyTo(FirstPackage, 4);
fileSize.CopyTo(FirstPackage, 4 + nameB.Length);
start.CopyTo(FirstPackage, 4 + nameB.Length + 4);
// Send the first pckage
netStream.Write(FirstPackage, 0, FirstPackage.Length);
byte[] buffer = new byte[30];
// Read the response
netStream.Read(buffer, 0, 11);
netStream.Close();
client.Close();
}
A friend tried to port forward the port 13000 but it didn't work either. We even tried with the firewall being down but nothing. I searched on the internet but couldn't find any solutions to the problem.
One thing to note is that both functions are in the same application. I don't know if that is the cause of the problem.
Does anyone know how what is the problem here?
Thanks in advance
Have you tried to connect to your server with telnet ? "telnet localhost 13000" or from other computer with correct ip and address nbr ? Try that while debugging your server code. If telnet works, then client code has some problem..

Sockets not able to receive message from the server

I am trying to connect to a application using sockets.
The application communicates using port 6100.
I am am able to send the messages to the application but not able to receive any message.
This is my code please let me know if i am doing anything wrong.
public void Connect2(string host, int port, string cmd)
{
byte[] bytes = new byte[10024];
IPAddress[] IPs = Dns.GetHostAddresses(host);
Socket s = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
s.SendTimeout = 100;
Console.WriteLine("Establishing Connection to {0}",
host);
try
{
s.Connect(IPs[0], port);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
byte[] sendBites = System.Text.Encoding.ASCII.GetBytes(cmd);
int bytesSent = s.Send(sendBites);
int bytesRec = s.Receive(bytes);
s.ReceiveFrom(bytes, ref tmpRemote);
MessageBox.Show(s.ReceiveBufferSize.ToString());
MessageBox.Show(Encoding.ASCII.GetString(bytes, 0, bytesRec));
s.Shutdown(SocketShutdown.Both);
s.Close();
}
First when the Connect failes, you're still trying to send/receive data. Put the send and receive inside the try/catch.
I can see that you're calling receive twice:
int bytesRec = s.Receive(bytes);
s.ReceiveFrom(bytes, ref tmpRemote);
What probably happens is:
You are sending a command
You are waiting for a response "int bytesRec = s.Receive(bytes);"
Then again you are waiting for more data.. "s.ReceiveFrom(bytes, ref tmpRemote);"
But probably the server won't send additional data, so you are waiting "forever"
Try again removing the s.ReceiveFrom(bytes, ref tmpRemote);
The Socket.ReceiveFrom() is usually used for receiving UDP broadcasts.
This piece of code works fine.
public string SocketSendReceive(string server, int port, string cmd)
{
byte[] recvBuffer = new byte[1024];
string host = "127.0.0.1";
TcpClient tcpClient = new TcpClient();
try
{
tcpClient.Connect(host, 6100);
}
catch (SocketException /*e*/)
{
tcpClient = null;
}
if (tcpClient != null && tcpClient.Connected)
{
tcpClient.Client.Send(Encoding.UTF8.GetBytes(cmd));
tcpClient.Client.Receive(recvBuffer);
// port = Convert.ToInt16(Encoding.UTF8.GetString(recvBuffer).Substring(2));
tcpClient.Close();
}
return Encoding.ASCII.GetString(recvBuffer, 0, recvBuffer.Length);
}

TCP port reading in 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();
}
}

Categories

Resources