I am working with C++ application which is windows service and C# server .
With localhost testing everything works great, but with virtualbox system or the same network computers it doesnt work.
I disabled windows firewall and antivirus.
Here is my C# Server most important code:
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = IPAddress.Parse("192.168.1.2");
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 8517);
tcpListener = new TcpListener(localEndPoint);
tcpListener.Start();
tcpListenerThread = new Thread(listenerSocket);
tcpListenerThread.Start();
}
static void listenerSocket()
{
while (true)
{
try
{
Socket client = tcpListener.AcceptSocket();
clientSockets.Add(client);
}
catch (Exception exc)
{
return;
}
}
}
And here is my C++ client most important code(according msdn examples for c++ socket clients):
connectToServer(){
serviceState = DISCONNECTED;
ConnectSocket = INVALID_SOCKET;
sendbuf = "Client Service is ready";
recvbuflen = DEFAULT_BUFLEN;
//----------------------
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != NO_ERROR) {
SaveEvent(L"WSAStartup failed");
}
else{
SaveEvent(L"WSAStartup success");
}
// Create a SOCKET for connecting to server
ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ConnectSocket == INVALID_SOCKET) {
SaveEvent(L"Error creating socket for connecting to server");
WSACleanup();
}
else{
SaveEvent(L"Creating socket for connecting to server success");
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr( std::string(serverIP.begin(), serverIP.end()).c_str());
address.sin_port = htons( serverPort );
//----------------------
// Connect to server.
iResult = connect( ConnectSocket, (SOCKADDR*) &address, sizeof(address) );
if ( iResult == SOCKET_ERROR) {
closesocket (ConnectSocket);
serviceState = DISCONNECTED;
SaveEvent(L"Unable to connect to server");
WSACleanup();
}
else{
serviceState = CONNECTED;
SaveEvent(L"Connected to server : " + serverIP );
u_long iMode = 1;
ioctlsocket(ConnectSocket, FIONBIO, &iMode);
}
}
With localhost it works and i have client and server on the same ip but with different ports.
With different ips i got situation when server doesnt 'hear' client.
My log looks like this:
2017-03-31 18:01:30 Settings readed: server IP = 192.168.1.2, server port = 8517-
2017-03-31 18:01:30 WSAStartup success -
2017-03-31 18:01:30 Creating socket for connecting to server success-
2017-03-31 18:01:31 Unable to connect to server-
I would really appreciate any kind oif help i stuck with this almost one week.
I can that add ping to server ip works on client pc
Related
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.
The C#-Application is the TCP-Server and Delphi-Application represents the TCP-Client polling Server for information.
I'm using Microsoft Visual Studio Community 2017 and .NET-Framework 4.5.1 for the C#-Application and Delphi 7 (Embarcadero) for the Client-Application.
Both Applications run on the same PC, therefore I set IP-Address to "localhost" or "127.0.0.1".
The Port is 12345.
class Program
{
static void Main(string[] args)
{
int port = 0;
IPHostEntry host;
IPAddress localAddress;
try
{
port = 12345;
host = Dns.GetHostEntry("localhost");
localAddress = host.AddressList[0];
Console.WriteLine("Server waits for a client");
// init Listener
TcpListener listener = new TcpListener(localAddress, port);
// start Listener
listener.Start();
// Wait for a client..
TcpClient c = listener.AcceptTcpClient();
Console.WriteLine("Connection established.");
//..
// Close connection
c.Close();
// stop Listener
listener.Stop();
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
}
}
My Problem is, that I get error # 10061 "Connection refused" in the Client (Delphi) Application when the socket tries to connect to the server.
TForm1 = class(TForm)
TcpClient1: TTcpClient;
btnConnect: TButton;
// ..
procedure TForm1.btnConnectClick(Sender: TObject);
begin
// try to connect to TCP-Server
TcpClient1.RemoteHost := 'localhost';
TcpClient1.RemotePort := '12345';
if not TcpClient1.Connect() then // Error 10061
begin
ShowMessage('No connection to server');
end
else
begin
ShowMessage('Connected with server.');
end;
end;
In Delphi I tried the component TcpClient as well as the Indy component TIdTCPClient - the error appears on both.
For testing purpose I wrote a Client-Application in C# where the error didn't occur (same address and port).
class Program
{
static void Main(string[] args)
{
try
{
// init Client
TcpClient c = new TcpClient("localhost", 12345);
Console.WriteLine("Connected to localhost.");
// ..
// close connection
Console.WriteLine("Close connection.");
c.Close();
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
Console.WriteLine("Press Enter to exit... ");
string cmd = Console.ReadLine();
}
}
My guess is, that there is something between C# and Delphi, but I have no idea what.
Did anyone has an idea why I cannot establish a connection with the Delphi-Application?
Update: It seems to work, when the C#-Server accepts Clients from any IP-Address.
// ..
// host = Dns.GetHostEntry("localhost");
// localAddress = host.AddressList[0];
Console.WriteLine("Server waits for a client");
// init Listener
TcpListener listener = new TcpListener(IPAddress.Any, port);
//..
In C# localAddress can be of Address Family IPv4, IPv6 or others, I wasn't able to connect with my Delphi-Application that works with IPv4.
My current solution:
I loop through the AddressList and make sure that I get an IP-Address of IPv4-Family.
host = Dns.GetHostEntry("localhost");
for (int i = 0; i <= host.AddressList.Length - 1; i++)
{
if (host.AddressList[i].AddressFamily == AddressFamily.InterNetwork) // check if family is IPv4
{
localAddress = host.AddressList[i];
// init Listener
listener = new TcpListener(localAddress, port);
// start Listener
listener.Start();
// ..
}
}
Previously I had problem to connecting my client and server using DNS Server, because I could not solve the ip,
public static TcpClient client;
private const int _PORT = 100; // same as server port
public static string connectTo = "kamikazehc.ddns.net";
public static IPAddress ipaddress = null;
resolving IP addresses into DNS name:
private static void ConnectToServer()
{
int attempts = 0;
bool IsValidIP = IPAddress.TryParse(connectTo, out ipaddress);
if (IsValidIP == false)
{
ipaddress = Dns.GetHostAddresses(connectTo)[0];
Console.WriteLine(Dns.GetHostAddresses(connectTo)[0]);
}
client = new TcpClient();
while (!_clientSocket.Connected)
{
try
{
attempts++;
Console.WriteLine("Connection attempt " + attempts);
_clientSocket.Connect(ipaddress, _PORT);
Thread.Sleep(100);
}
catch (SocketException)
{
Console.Clear();
}
}
Console.Clear();
Console.WriteLine("Connected");
}
If I put my local Ip 192.168.x.x I connect.
But if I use my fixed IP or dns the client makes endless attempts to connect.
Using DNS or Fixed IP
Using local IP:
I would like to know how to solve this to be able to connect, I imagine I do not need to modify the code, just configure my internet, but I do not know how to configure
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
I'm playing around with broadcasting and receiving UDP messages.
I have a client and a server that work ok in my machine, but that can't connect across machines.
My server sends messages and my client receives them.
I turned of the firewall on both machines, that can't be the problem.
The server looks like:
var udpclient = new UdpClient();
IPAddress multicastAddress = IPAddress.Parse("239.0.0.222");
udpclient.JoinMulticastGroup(multicastAddress);
var endPoint = new IPEndPoint(multicastAddress, 2222);
while(true)
{
Byte[] buffer = Encoding.Unicode.GetBytes(Dns.GetHostName());
udpclient.Send(buffer, buffer.Length, endPoint);
Console.WriteLine("Broadcasting server hostname: {0}", Dns.GetHostName());
Thread.Sleep(3000);
}
And the client looks like:
var client = new UdpClient { ExclusiveAddressUse = false };
var ipEndPoint = new IPEndPoint(IPAddress.Any, 2222);
client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
client.ExclusiveAddressUse = false;
client.Client.Bind(ipEndPoint);
IPAddress multicastaddress = IPAddress.Parse("239.0.0.222");
client.JoinMulticastGroup(multicastaddress);
Byte[] data = client.Receive(ref ipEndPoint);
string strData = Encoding.Unicode.GetString(data);
Console.WriteLine("Received hostname {0} from the server", strData);
Console.WriteLine("I'm done. Press any key to close me.");
Console.ReadLine();
I think the problem is not in the code, but network related.
Any ideas on how to check what's the problem? Thank you in advance
Try connecting them to a same network such as a wifi network.Note: every time you connect to a different network the IP address changes.