I can run the server on my local machine and connect to it on the same machine, but when I try to connect to it from a different computer over the internet, there is not sign of activity on my server, nor a response from the server on the computer I'm testing it on. I've tried both XP and Vista, turn off firewalls, opened ports, ran as admin; nothing is working. :(
Here is my code that I'm using to accept an incoming connection:
int port = 3326;
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
TcpListener listener = new TcpListener(new IPEndPoint(IPAddress.Any, port));
listener.Start();
Console.WriteLine("Server established\nListening on Port: {0}\n", port);
while (true)
{
socket = listener.AcceptSocket();
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, outime);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
socket.DontFragment = true;
NewConnection pxy = new NewConnection(socket);
Thread client = new Thread(new ThreadStart(pxy.Start));
client.IsBackground = true;
client.Start();
}
}
I think that the problem is in your router, not your computer. When packets come from the Internet, it should be routed to an specific server. You have to configure your router to redirect the traffic on port 3326 to your server.
You've probably got something blocking the connection higher up. Try connecting from another host on the LAN. If you can do that, then the OS itself isn't firewalling the connection.
If either you or your ISP run a NAT router, then your machine probably doesn't have a publicly accessible address, in which case it's impossible to connect directly to it.
If there is no NAT router, something may still be blocking the connection upstream.
I am serious: Many ISPs actively work to stop you from using your home connection as a web server. You might want to call them before you invest too much time.
If you are trying to host at home, your ISP may be restricting you.
Related
I'm writing a server/client application. my server works great on local ip addresses and i am able to test all of its features using 127.0.0.1 as ip address and communicate with my server.
Today i used my public ip address as ip address in my server application and i configured my port forwarding and checks it with common tools on network and everyone says my port is open an actually i get port checker site packets on my server that shows everything works fine.
but when i want to connect from my client application that it is written in c#(also my server is in c#) i get exception in Socket.Connect function that code is below "No connection could be made because the target machine actively refused it" :
clientSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
Console.WriteLine("Connectiong to server");
clientSocket.Connect("151.243.130.245", 1892);
and here is my listen method on my server :
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
for (int i = 0; i < MAX_CLIENTS; ++i)
{
clients[i] = new Client();
}
serverSocket.Bind(new IPEndPoint(IPAddress.Any, 1892));
serverSocket.Listen(MAX_CLIENTS);
serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
i have to mention that i tested port checker sites from my friend home and it did send a packet to my server.
also i have a wireless usb adaptor connected to my computer and i am connected with it to my mode.
i did search all the internet and everyone said that in this error common issues are you are not listening on that port or you are blocked by a firewall program but i have to say that i did both of them,it means i used -netstat -anb and it shows i am listening on port 1892 and also i configure firewall to let any connection goes through it but still no luck :(
any helps will greatly be appreciated.
I currently have 2 .Net applications which run on the same PC simultaneously.
These 2 applications communicate using UDP like this:
Client:
udpUnityToConsole = new UdpClient();
udpUnityToConsole.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
try
{
udpUnityToConsole.Connect("localhost", 11004);
}
Server:
unityUdpReceive = new UdpClient();
unityUdpReceive.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
unityUdpReceive.Client.Bind(new IPEndPoint(IPAddress.Any, 11004));
The communication stream is fast and reliable, there is just one issue with it and that is that if the PC is not connected to a network then it will crash with a
System.Net.Sockets.SocketException: No such host is known.
If the connection has been established already and then the PC is disconnected from the network, the connection will remain. Only if there is no network connection to start with will it fail.
Any suggestions are greatly appreciated.
All I had to do was change localhost to 127.0.0.1 which is the address of the local machine and never changes, therefore it is safe to use. Using localhost meant that the UDP library had to look up the IP being used with the localhost alias, but that wasn't necessary as I knew it already. I could probably also find out the IP some other way and run that query on both applications.
I've created two apps (A client and a server) which can communicate with each other as long as I input the local IP address of the machine the server app is running on into the client app (in code).
I would like the client app to automatically discover the local IP address of the machine running the server app and connect to it, so they can be run on any network without the need to enter the IP in code.
Both of these apps with be running on the same network (ie. Over WiFi, not the Internet)
Here is what I have so far in my client app:
// COMMUNICATE WITH SERVER
private TcpClient client = new TcpClient();
private IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("192.168.2.35"), 8888);
public Console()
{
InitializeComponent();
client.Connect(serverEndPoint);
}
private void SendMessage(string msg)
{
NetworkStream clientStream = client.GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes(msg);
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
In this example I can only connect to a server running on "192.168.2.35", I would like it to be able to find the server running on port 8888 on any machine on the network.
Alternatively, if this isn't possible I would like the server to broadcast its IP as a message (of some sort) and have the client receive this message and verify it is the server and connect to it.
I think my second example is the proper way to do this, but I can't seem to wrap my head around how to get it working (I'm fairly new to C#), and any other examples I've found I can't seem to get to work with my applications.
Here is my server code if it helps answer my question:
private void Server()
{
this.tcpListener = new TcpListener(IPAddress.Any, 8888);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
}
private void ListenForClients()
{
this.tcpListener.Start();
while (true)
{
TcpClient client = this.tcpListener.AcceptTcpClient();
connectedClients++;
lblNumberOfConnections.Text = connectedClients.ToString();
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
Thanks
EDIT: I've tried adding THIS to my project, but being so new I'm unsure how to implement it properly, and it didn't get me anywhere.
2nd EDIT: I've tried implementing a UDP broadcast a few times now, with no luck on any attempt yet. My latest attempt was at implementing THIS (minus the chat parts). I just can't seem to get a UDP broadcast working at all with my project, as it seems to be way over my head at my current skill level. Unfortunately, having my client automatically connect to the server is 100% necessary for my project to function...
My other problem, which is maybe best to start a separate question for, but somewhat correlates to this issue is: My client GUI consists of a panel that switches between multiple custom classes, each containing different buttons, etc. (works similar to tab pages) that communicate to the server I'm trying to connect to. Once I get the UDP broadcast figured out, will I need to code that into every class separately? or is there a way of having all classes running in my panel connect to the same server?
A simple, but possibly costly(in terms of network traffic) solution would be for your server application to broadcast over UDP it's application and connection info. Your client could listen for all broadcast packets that have your servers custom header. Assuming a connection is made you could stop the broadcast. The downside is you would have to be broadcasting constantly if a client is not connected and this can clog your network if there aren't limits placed on the broadcast speed.
EDIT: Here is a boiled down explanation generated from the MSDN article https://msdn.microsoft.com/en-us/library/tst0kwb1(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1
EDIT #2: I've expanded on this answer on my blog, as well as provided downloadable example projects. the article can be found at http://martialdeveloper.com/wordpress/?p=21
1. Find your network's broadcast IP
A special “Broadcast Address” must be used when using UDP for the purpose of sending a datagram to all machines connected to a given network. For example, the typical home network host/gateway of 192.168.0.1 has a broadcast address of 192.168.0.255. If your network differs from this you can use an IPv4 broadcast address calculator like the one found here http://jodies.de/ipcalc
Or read the introductory section on MSDN describing the broadcast address. https://msdn.microsoft.com/en-us/library/tst0kwb1(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1
2. Select a listening/broadcast port
Any port that is free on your client & server is fine. The MSDN example uses 11000. This port number is used in your broadcaster, and listener.
3. Code for the Listener
Note to the reader. All error handling has been omitted for clarity of the example.
int listenPort = 11000;
bool done = false;
UdpClient listener = new UdpClient(listenPort);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any,listenPort);
while (!done) // This loop listens for your broadcast packets
{
Console.WriteLine("Waiting for broadcast");
byte[] bytes = listener.Receive( ref groupEP);
Console.WriteLine("Received broadcast from {0} :\n {1}\n",
groupEP.ToString(),
Encoding.ASCII.GetString(bytes,0,bytes.Length));
}
listener.Close();
Note: The third parameter to Console.WriteLine, "Encoding.ASCII..." represents the string value sent over UDP in the datagram packet. This contains the desired negotiation information for a discovery situation, such as the IP address of the client or server you wish to connect to.
4. Code for the Broadcaster
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
IPAddress broadcast = IPAddress.Parse("This string should be the broadcast IP address"); //NOTE: Broadcast IP goes here!!
byte[] sendbuf = Encoding.ASCII.GetBytes("This is the message string to be broadcast"); //Your message to the client/server goes here, I.E. an
// app/client name or ID and an IP to connect with over TCP
IPEndPoint ep = new IPEndPoint(broadcast, 11000);
s.SendTo(sendbuf, ep);
Console.WriteLine("Message sent to the broadcast address");
NOTE: This is a very simple example. The broadcaster may need to rebroadcast for a period of time to make sure the Listener receives it. Even after the UDP datagram is sent/received there will need to be some negotiation to ensure the TCP connection is made properly.
I'm trying to learn Socket Programming, and I encountered this error while connecting to my server application.
Here's my declaration of the TcpListener in the server application:
TcpListener listener = new TcpListener(IPAddress.Loopback, 5152);
and here's my declaration of the TcpClient in my client application:
TcpClient client = new TcpClient(Dns.GetHostEntry(IPAddress.Loopback).HostName, 5152);
I have read several questions like this, and I always get the same answer: Either the server application isn't listening to the port or not running at all. But I've double-checked the Resource Monitor and cmd using netstat to see if the service is listening to the port, and it is. I've also included the service in the Firewall exceptions, so I'm not sure why I keep getting this error while trying to connect to the server app.
Any ideas?
Dns.GetHostEntry(IPAddress.Loopback).HostName returns the host name of your machine. When you pass a host name to TcpClient, it will resolve it to one or more IP addresses using Dns.GetHostAddresses(hostName). This includes the public and link-local IP addresses of your machine (e.g., 192.168.15.4), but not the loopback address (127.0.0.1).
So your client is trying to connect to any of the non-loopback addresses of your machine, while your server is listening only on the loopback address. Thus, no connection can be established.
Solution: Connect to the same end point your server is listening on.
IPEndPoint endPoint = new IPEndPoint(IPAddress.Loopback, 5152);
TcpListener listener = new TcpListener(endPoint);
TcpClient client = new TcpClient();
client.Connect(endPoint);
I'm having a problem with sockets.
I've written myself two simple applications, one server and one client.
The server simply waits for a UDP packet to arrive, printing out something in the console once that happens.
The client sends a UDP packet to a specific end point.
// server
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sock.Bind(new IPEndPoint(IPAddress.Any, 1337));
IPEndPoint remote = new IPEndPoint(IPAddress.Any, 0);
byte[] buf = new byte[1024];
sock.ReceiveFrom(buf, ref remote);
Console.WriteLine("Received packet.");
// client
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint remote = new IPEndPoint(IPAddress.Parse(Console.ReadLine()), UInt16.Parse(Console.ReadLine()));
byte[] buf = { 1, 2, 3, 4 }; // random data
sock.SendTo(buf, remote);
Now the weird thing is that when the client socket sends its packet to the public IP address of my router, the server socket only receives it if the client is not run on the same PC as the server. So if I start the server on my PC and then start the client on my PC, enter my public IP and port 1337, the server doesn't receive anything.
However, if I send the client application to my friend and give him my IP address and port, it works perfectly fine.
It also works if I let the client connect to my local IP instead of my public one.
Am I the only one experiencing this behaviour?
Port 1337 is forwarded to the computer the server is ran on, btw.
This seems to be a NAT configuration issue. You must have configured nat on the router to forward packets coming on the public interface with specific port (1337) to be forwarded to the server. So this works when your friend sends you a UDP packet.
But you must not (don't know if its even possible) have configured natting the other way around meaning the same UDP packet coming to the internal interface. This is the case when you send packet from server to client with both on the same machine.
When both the server and client (on a single machine or two different machines) are on your internal network it will be best to use the server's interface id than depending on natting
Most routers and modems do not normally forward UDP traffic -- see http://www.gotroot.com/blogpost4-Why-your-should-never-forward-UDP-out-of-your-firewall for an explanation. Also try attaching both the client and server to the same physical network (well, subnet) and to try sending datagrams directly to the server instead of forwarding them.