I'm trying to send a packet by TCP to a server from VPN if I'm not connected to the local network, if I'm on the same local network I'm putting its IP if it's sent, but if I'm not and I'm passing the server's remote IP It gives an error.
This code works for me if I'm in the same local network as the server:
//Crear socket
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//Definir Ip de destino y puerto
IPAddress ip = IPAddress.Parse("192.168.1.50");
int puerto = 8888;
//Apuntar a donde se enviara el mensaje
IPEndPoint destino = new IPEndPoint(ip, puerto);
try
{
//Realizar conexion
socket.Connect(destino);
//Crear mensaje
byte[] mensaje = Encoding.ASCII.GetBytes("shutdown");
//Enviar mensaje
var result = socket.Send(mensaje);
}
catch (Exception ex)
{
throw ex;
}
finally
{
socket.Close();
}
But to do it from outside the local network connected to the VPN passing as address the ip obtained by DNS does not work for me:
//Crear socket
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//Definir Ip de destino y puerto
IPAddress ip = Dns.GetHostAddresses("google.com")[0]; //it returns me for example ip 88.23.154.89
int puerto = Convert.ToInt32(ConfigurationManager.AppSettings["PUERTO_SERVIDOR"]);
//Apuntar a donde se enviara el mensaje
IPEndPoint destino = new IPEndPoint(ip, puerto);
try
{
//Realizar conexion
socket.Connect(destino);
//Crear mensaje
byte[] mensaje = Encoding.ASCII.GetBytes("shutdown");
//Enviar mensaje
var result = socket.Send(mensaje);
}
catch (Exception ex)
{
throw ex;
}
finally
{
socket.Close();
}
The error gives me in socket.Connect(destino);
The connection attempt failed because the connected party did not respond properly after a period of time, or the established connection failed because the connected host was unable to respond 88.23.154.89:1025
Related
I'm make this TCP server in C# (UWP App in Win 10/11):
IPHostEntry ipHostInfo = Dns.GetHostEntry("localhost");
IPAddress ipAddress = ipHostInfo.AddressList[1]; //IP v4 address
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 21234);
System.Diagnostics.Debug.WriteLine("Wait on: " + localEndPoint.ToString());
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and
// listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(100);
// Start listening for connections.
while (true)
{
System.Diagnostics.Debug.WriteLine("Wait for a connection request...");
Socket handler = listener.Accept();
System.Diagnostics.Debug.WriteLine("Connection Request arrived!");
}//while
}//try
//...
and I have this client, written in C++ with boost::asio libraries:
using namespace boost::asio;
using ip::tcp;
boost::asio::io_context io_context;
tcp::resolver* resolver;
tcp::socket* socket_;
resolver = new tcp::resolver(io_context);
socket_ = new tcp::socket(io_context);
try
{
boost::asio::connect(*socket_, resolver->resolve("localhost", "21234"));
}
catch (std::exception& e)
{
std::cerr << "Connect Exception--->>" << e.what() << std::endl;
}
Ok, I obtain an exception from client:"Impossibile stabilire la connessione. Risposta non corretta della parte connessa dopo l'intervallo di tempo oppure mancata risposta dall'host collegato"("Unable to establish connection. Incorrect response from the connected party after the time interval or no response from the connected host").
I think that the wrong in the server because I tried successfully with a C++ boost::asio client and it work.
Where is wrong?
i want to let 2 c# apps each one is on a separate computer and both connected to the same ADSL router to send messages to each other i know that we have to use Sockets and tried many solutions on the internet but they are all working at the same computer but not working on a separate computers.
i believe that the problem is in the ip addresses but i tried a lot with no good results
is there any simple code to help please
i tried this function on server side
public static void StartServer()
{
IPHostEntry host = Dns.GetHostEntry("DESKTOP-SBJHC7I");
IPAddress ipAddress = host.AddressList[0];
Console.WriteLine(ipAddress.ToString());
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
try
{
// Create a Socket that will use Tcp protocol
Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
// A Socket must be associated with an endpoint using the Bind method
listener.Bind(localEndPoint);
// Specify how many requests a Socket can listen before it gives Server busy response.
// We will listen 10 requests at a time
listener.Listen(10);
Console.WriteLine("Waiting for a connection...");
Socket handler = listener.Accept();
// Incoming data from the client.
string data = null;
byte[] bytes = null;
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf("<EOF>") > -1)
{
break;
}
}
Console.WriteLine("Text received : {0}", data);
byte[] msg = Encoding.ASCII.GetBytes(data);
handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\n Press any key to continue...");
Console.ReadKey();
}
and this function in the client side
public static void StartClient()
{
byte[] bytes = new byte[1024];
try
{
// Connect to a Remote server
// Get Host IP Address that is used to establish a connection
// In this case, we get one IP address of localhost that is IP : 127.0.0.1
// If a host has multiple addresses, you will get a list of addresses
IPHostEntry host = Dns.GetHostEntry("DESKTOP-SBJHC7I");
IPAddress ipAddress = host.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);
// 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
{
// Connect to Remote EndPoint
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("This is a test<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));
// 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());
}
}
please make sure that your client is connected to the same IP on which server is started. because it seems in your code that your client connecting to host which you getting it from localhost identity. For your testing purpose please hardcode the Server's IP address in your Remoteendpoint. if still the issue same then I will share code to test on a different networks.
I went to request to open socket from web service to be like notification when the database change . The client is request to web service when it's connection to internet to apply to web service to get his IP Address then web service can send in this IP socket when database change . And client have socket open response the request .
Code of web service in Remote host
[WebMethod]
public string GetMyIpAddress()
{
string adree = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; //get client request ip address
byte[] bytes = new byte[1024];
try
{
IPAddress ipaddress = IPAddress.Parse(adree);
IPEndPoint remote = new IPEndPoint(ipaddress, 1093);
Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sender.Connect(remote);
byte[] meg = Encoding.ASCII.GetBytes("This is a test<EOF>"); // send message to client in it's ip address
int bytesend = sender.Send(meg);
int byterecive = sender.Receive(bytes);
string red = Encoding.ASCII.GetString(bytes, 0, byterecive);
sender.Shutdown(SocketShutdown.Both);
sender.Close();
return(red);
}
catch (Exception e)
{
return(e.ToString());
}
}
Code of client socket
class Program
{
public static string data = null;
static void Main(string[] args)
{
byte[] bytes = new byte[1024];
IPHostEntry iphostinfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipaddress = iphostinfo.AddressList[0];
IPEndPoint localendpoint = new IPEndPoint(ipaddress, 1093);
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
listener.Bind(localendpoint);
listener.Listen(10);
while (true)
{
Console.WriteLine("Waiting for a connection...");
Socket hander = listener.Accept();
data = null;
while (true)
{
bytes = new byte[1024];
int bytsize = hander.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytsize);
if (data.IndexOf("<EOF>") > -1)
{
break;
}
}
Console.WriteLine("Text received : {0}", data);
byte[] meg = Encoding.ASCII.GetBytes(data);
hander.Send(meg);
hander.Shutdown(SocketShutdown.Both);
hander.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
}
The problem when i request to web service to get my client IP address and send to this IP address for test i get this problem :
System.Net.Sockets.SocketException (0x80004005): A connection attempt failed because the connected party did not properly respond after a period of time, or est ablished connection failed because connected host has failed to respond 41.218.1
9.226:1093
Please help me how can solve this problem ?
If we run the code below the output will be
Connecting to www.google.com
30 bytes were sent.
Connecting to www.google.com
We failed to connect!
Connecting to www.google.se
30 bytes were sent.
Why can't i connect to the same host multiple times using the same socket?
(Also the socket seems to have some sort of memory its not just the latest host it remembers all of them...)
static void Main(string[] args)
{
Socket client = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
client.SendTimeout = 500;
Connect(client, "www.google.com");
Connect(client, "www.google.com");
Connect(client, "www.google.se");
Console.ReadKey();
}
private static void Connect(Socket client, string hostName)
{
Console.WriteLine("Connecting to " + hostName);
IPHostEntry ipHost = Dns.GetHostEntry(hostName);
IPAddress ipAddr = ipHost.AddressList[0];
IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 80);
// Connect the socket to the remote end point.
//client.Connect(ipEndPoint);
IAsyncResult ar = client.BeginConnect(ipEndPoint, null, null);
ar.AsyncWaitHandle.WaitOne(5000);
if (!client.Connected)
{
Console.WriteLine("We failed to connect!");
return;
}
// Send some data to the remote device.
string data = "This is a string of data <EOF>";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int bytesTransferred = client.Send(buffer);
// Write to the console the number of bytes transferred.
Console.WriteLine("{0} bytes were sent.", bytesTransferred);
// Release the socket.
//client.Shutdown(SocketShutdown.Both);
client.Disconnect(true);
if (client.Connected)
Console.WriteLine("We failed to disconnect");
}
I try to send a string over the network, this is my code:
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 25);
TcpClient client = new TcpClient(serverEndPoint);
Socket socket = client.Client;
byte[] data = Encoding.ASCII.GetBytes(response);
socket.Send(data, data.Length, SocketFlags.None);
socket.Close();
client.Close();
When I run it I got System.Net.Sockets.SocketException
If you are using a connectionless protocol, you must call Connect before calling Send, or Send will throw a SocketException. If you are using a connection-oriented protocol, you must either use Connect to establish a remote host connection, or use Accept to accept an incoming connection.
Refer Socket.Send Method (Byte[], Int32, SocketFlags)
Assuming you are using a connectionless protocol the code should be like this,
string response = "Hello";
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
if (ipAddress != null)
{
IPEndPoint serverEndPoint = new IPEndPoint(ipAddress, 25);
byte[] receiveBuffer = new byte[100];
try
{
using (TcpClient client = new TcpClient(serverEndPoint))
{
using (Socket socket = client.Client)
{
socket.Connect(serverEndPoint);
byte[] data = Encoding.ASCII.GetBytes(response);
socket.Send(data, data.Length, SocketFlags.None);
socket.Receive(receiveBuffer);
Console.WriteLine(Encoding.ASCII.GetString(receiveBuffer));
}
}
}
catch (SocketException socketException)
{
Console.WriteLine("Socket Exception : ", socketException.Message);
throw;
}
}
Next time, try including the exception message to explain what actually went wrong.