Test if Socket is connected in C# - c#

Hi i am writing a simple server program that is listening for connections. My Question is, How can I test if the socket is connected or not. Here is my code
using System;
using System.Net;
using System.Net.Sockets;
class server
{
static int port = 0;
static String hostName = Dns.GetHostName();
static IPAddress ipAddress;
static bool listening = true;
public static void Main(String[] args)
{
IPHostEntry ipEntry = Dns.GetHostByName(hostName);
//Get a list of possible ip addresses
IPAddress[] addr = ipEntry.AddressList;
//The first one in the array is the ip address of the hostname
ipAddress = addr[0];
TcpListener server = new TcpListener(ipAddress,port);
Console.Write("Listening for Connections on " + hostName + "...");
do
{
//start listening for connections
server.Start();
} while (listening);
//Accept the connection from the client, you are now connected
Socket connection = server.AcceptSocket();
Console.Write("You are now connected to the server");
connection.Close();
}
}

I think you got your beans messed up here. Underneath, at the OS level, there are two distinct notions: a listening socket - that's the TcpListener, and a connected socket - that's what you get after successful accept().
Now, the listening TCP socket is not connected, but bound to the port (and possibly address) on the local machine. That's where a server waits for connection requests from clients. Once such request arrives the OS creates a new socket, which is connected in a sense that it has all four parts that are required for communication - local IP address and port, and remote address and port - filled in.
Start with some introductory text, something like this one. Even better - start with a real one.

server.Start()should be outside the loop. It's only called once and the listening socket will remain open until Stop is called.
AcceptSocket will block until a client have connected. If you want to be able to accept multiple sockets, then keep looping it.

Related

Connect to a remote endpoint using UDP Socket in Xamarin (C#) only works when activating a VPN

I have a UDP Socket connection working between devices with local IPs (192.168.x.x), that I want to switch to a connection with an external server, with the following configuration:
Create socket
private Socket _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
private const int bufSize = 4096 * 4;
private State state = new State();
private EndPoint epFrom = new IPEndPoint(IPAddress.Any, 0);
private AsyncCallback recv = null;
private static int PORT = 27000;
Openning device as a server to listen through the socket
_socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.ReuseAddress, true);
_socket.Bind(new IPEndPoint(IPAddress.Any, port));
Receive(); // Function to receive datagrams through the socket, irrelevant to this issue
Connect socket to remote endpoint
// {address:port} of an external server
_socket.Connect(new IPEndPoint(IPAddress.Parse(address), port));
Send data to socket
_socket.BeginSend(data, 0, data.Length, SocketFlags.None, (ar) =>
{
try
{
_socket.EndSend(ar);
}
catch (Exception ex)
{
Console.WriteLine("[UDP] Error Send: " + ex.ToString());
}
}, state);
The code above works fine for local IP addresses, the problem came when trying to use as a remote ip endpoint a public IP of a remote server.
The datagram seemed to be sent but it never arrived to the server. I tried to connect the phone to a VPN and the local IP changed from a 192.168.x.x to a 10.0.x.x, and then the connection to the external server worked.
Therefore, connection with an external IP only worked when the device's IP was a private IP of class A, but it didn't work with a class C range (https://www.meridianoutpost.com/resources/articles/IP-classes.php).
I want to find a solution to be able to connect to external IP address without having to connect a third party VPN software.
If someone has the same question, I have already solved it.
To access external IPs with local class C IPs and no VPN you should do UDP hole punching instead of trying to establish a connection.
Erase the .Connect() and the .Bind() methods, and, instead of using BeginSend/EndSend, use the SendTo or SendToAsync methods with the server's public IP as the endpoint destination.
Additionally, I recommend changing:
SocketOptionName.ReuseAddress
to:
SocketOptionName.PacketInformation

How to set up TCP communication between two computers

I am trying to use the TCP protocol with the System.Net.Sockets library to have one computer send a string to the other. Here is part of my host code. Is the listener object supposed to be declared with the client IP address or the host IP address (like it is in the code below)?
IPAddress ipAddr = Dns.GetHostEntry(Dns.GetHostName()).AddressList[0]; //Automatically retrieves IPAddress.
int port = 135; //specify port number.
TcpListener listener = new TcpListener(ipAddr, port);
Also, here is a piece of my client code. Which constructor do I use?
TcpClient client = new TcpClient();
The listener object listens on the host's IP. The constructor takes it as an argument because you could have several IP's on the computer and it doesn't know which one you want to listen on.
As far as the client goes, you can pick whichever constructor you want. By using the parameterized constructors, you can connect right away, whereas the default requires a call to one of the overloads of Connect. It mostly depends on if you actually want to connect at instantiation time.
See MSDN for the overloads you can use.
Here is a TCP server sample code:
int port = 135; //specify port number.
TcpListener listener = new TcpListener(IPAddress.Any, port);
// Start listening for client requests
listen.Start();
And then you can select to use polling method to create a simple sync TCP server.
The client (PowerShell):
$Address = [System.Net.Dns]::GetHostAddresses("<hostName>")
$Port = 135
$client = New-Object System.Net.Sorckets.TcpClient
$Client.Connect($Address, $Port)

How to access UDP Server using external IP Address

I have the following UDP server listening on Port 11000:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace UDPServer
{
class Program
{
static byte[] dataToSend = new byte[] { 1, 2, 3, 4, 5 };
// get the ip and port number where the client will be listening on
static IPEndPoint GetClientInfo()
{
// wait for client to send data
using (UdpClient listener = new UdpClient(11000))
{
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, 11000);
byte[] receive_byte_array = listener.Receive(ref groupEP);
return groupEP;
}
}
static void Main(string[] args)
{
var info = GetClientInfo(); // get client info
/* NOW THAT WE HAVE THE INFO FROM THE CLIENT WE ARE GONG TO SEND
DATA TO IT FROM SCRATCH!. NOTE THE CLIENT IS BEHIND A NAT AND
WE WILL STILL BE ABLE TO SEND PACKAGES TO IT
*/
// create a new client. this client will be created on a
// different computer when I do readl udp punch holing
UdpClient newClient = ConstructUdpClient(info);
// send data
newClient.Send(dataToSend, dataToSend.Length);
}
// Construct a socket with the info received from the client
static UdpClient ConstructUdpClient(IPEndPoint clientInfo)
{
var ip = clientInfo.Address.ToString();
var port = clientInfo.Port;
// this is the part I was missing!!!!
// the local end point must match. this should be the ip this computer is listening on
// and also the port
UdpClient client = new UdpClient(new IPEndPoint(IPAddress.Any, 11000));
// lastly we are missing to set the end points. (ip and port client is listening on)
// the connect method sets the remote endpoints
client.Connect(ip, port);
return client;
}
}
I also have opened a port in my router so when data is received from my router's gateway address, it will map to my hosting computer on 192.168.1.101:1000 as shown here:
I also have the following client defined, which is running on another machine (192.168.1.108) on the LAN:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
namespace UDPClient
{
class Program
{
static void Main(string[] args)
{
string ipOfServer = "205.172.111.250";
int portServerIsListeningOn = 11000;
// send data to server
Socket sending_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPAddress send_to_address = IPAddress.Parse(ipOfServer);
IPEndPoint sending_end_point = new IPEndPoint(send_to_address, portServerIsListeningOn);
sending_socket.SendTo(Encoding.ASCII.GetBytes("Test"), sending_end_point);
// get info
var port = sending_socket.LocalEndPoint.ToString().Split(':')[1];
// now wait for server to send data back
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, int.Parse(port));
byte[] buffer = new byte[1024];
sending_socket.Receive(buffer); // <----- we can receive data now!!!!!
}
}
}
Please notice the ipOfServer. This is my external gateway (not really since I obfuscated it, but it is not 192.168.1.101 - the internal IP of my UDP server).
When I direct the client to send to the internal LAN IP of 192.168.1.101:11000, the UDP Server connects.
However, when I use the gateway's IP address and port, the UDP Server does not connect. Since I have the port directed to 192.168.1.101:1000 in the NAT, I'm not sure what gives.
I know the NAT setting are good since I also have port 80 for HTTP and port 808 for net.tcp all working from anywhere, even outside of my network.
Please give me some insight as to what I am doing wrong.
Kind regards
It's hard to know exactly what's wrong without having access to your actual network setup. However, the scheme of creating a socket just to receive some data which is discarded, only to then create a new socket which you then "connect" to the client, seems wrong. You probably shouldn't be using Connect() with a UDP socket in the first place, and if you feel you must, you should just connect the original socket, once you have received some data.
In any case, it's really the client side of things that you need to worry about. You have already set up the router to forward datagrams inbound for the server, so the server should always be able to receive on that port. It's the return traffic to the client that is in question; the fact is, not all routers support this scenario, and always require port forwarding for UDP traffic (TCP traffic is easier because there is an on-going connection the router can maintain with the client).
I recommend that you make the server simpler – just create a single socket used to receive datagrams (and so of course don't dispose it with using). I'd also advise not using Connect() as all that will do is unnecessarily restrict the server. I.e. it will prevent the server's socket from being able to handle more than one client. If you really want to do some per-client filtering, a better mechanism is for the server to always receive all datagrams, and then check the receive-from address itself to decide how to deal with the datagram.

UDP networking with multiple network

I'm currently developing a network application on my machine with 2 network interfaces with the following setup -
I want to send UDP message by using the first configuration with IP 192.168.1.2.
using (var udpClient = new UdpClient(5556))
{
udpClient.Connect(IPAddress.Parse("192.168.1.2"), 5556);
// DO STUFF
}
When I try this I get the following error -
No connection could be made because the target machine actively
refused it
Strange this is that when I disable my other network that this works perfectly but with 2 connections (LAN & WiFi) it doesn't work anymore...
I guess that it is sending on wrong adapter?
Is this because my Default gateway is the same or what am I doing wrong?
I'm new to developing network-based applications...
You have to specify an IPEndPoint with networking card IP like this:
var endpoint = new IPEndPoint(IPAddress.Parse("192.168.1.2"), portNum);
UdpClient client = new UdpClient(endpoint);
You are not telling UdpClient which IP to use.
UdpClient has a constructor that can take an IPEndPoint.
const string ip = "192.168.1.2";
const int port = 5556;
var listenEndpoint = new IPEndPoint(IPAddress.Parse(ip), port);
var udpClient = new UdpClient(listenEndpoint);
I'm not that good in C# but I think I understand the problem. You are binding your udpClient to port 5556 but you're not specifying the IP address. The OS will select the IP address for you. I suppose it could be either 192.168.1.2 or 192.168.1.5, you cannot tell which one.
Then with the same udpClient you are trying to connect to a remote host listening on 192.168.1.2, port 5556. And probably nobody is listening there. This is why you receive the error.
I would do the following (sorry for my bad C# skills):
Have two udpClient's, in one thread or program/process:
var udpClient1 = new UdpClient("192.168.1.2", 5556);
This one will listen on IP addres 192.168.1.2, port 5556.
in second thread or program/process:
var udpClient2 = new UdpClient(); //doesn't matter which (IP, port) the OS will bind it to.
udpClient2.Connect(IPAddress.Parse("192.168.1.2"), 5556); //connect to peer/server listening in (IP=192.168.1.2, port=5556)
You could handle both udpClient1 and udpClient2 in the same thread also.
The important is that if you connect to and (IP, port) there has to be some application/process listening there. Otherwise, the remote host will send an ICMP message indicating the datagram cannot be delivered. The connection is refused.

UDP hole punching. Have server talk to client

I been reading a lot on how to implement UDP hole punching but fore some reason I cannot make it work.
For those that are not familiar of what udp hole punching is here is my own definition:
The goal is to be able to transfer data between two clients (Client A
and client B) with the help of a server. So client A connects to the server and sends its info. Client B does the same. The server has the nessesary info so that Client A is able to send data to Client B and vise versa . Therefore the server gives that info to both clients. Once both clients have that info about each other it is possible to start sending and receiving data between those clients without the help of the server.
My goal is to be able to do what I just described (udp hole punching). Before doing so I think it will be helpful to be able to connect from the server to the client. In order to do so I plan to send the server the info about the client. Once the server receives that info attempt to connect to the client from scratch. Once I am able to perform that I should have everything I need to start implementing the real udp hole punching.
Here is how I have things set up:
The top router has the server and bottom router connected to LAN ports. The bottom router (NAT) is connected to the top router via it's WAN port. And the client computer is connected to the bottom router to one of its LAN ports.
So in that connection the client is able to see the server but the server is not able to see the client.
So the algorithm I have done in pseudo code is:
Client connects to server.
Client send some UDP packages to the server in order to open some ports on the NAT
Send information to the server on what ports the client is listening to.
Once the server receives that info attempt to connect to the client from scratch.
Here is the implementation in code:
Server:
static void Main()
{
/* Part 1 receive data from client */
UdpClient listener = new UdpClient(11000);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, 11000);
string received_data;
byte[] receive_byte_array = listener.Receive(ref groupEP);
received_data = Encoding.ASCII.GetString(receive_byte_array, 0, receive_byte_array.Length);
// get info
var ip = groupEP.Address.ToString();
var port = groupEP.Port;
/* Part 2 atempt to connect to client from scratch */
// now atempt to send data to client from scratch once we have the info
Socket sendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint endPointClient = new IPEndPoint(IPAddress.Parse(ip), port);
sendSocket.SendTo(Encoding.ASCII.GetBytes("Hello"), endPointClient);
}
Client:
static void Main(string[] args)
{
/* Part 1 send info to server */
Socket sending_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPAddress send_to_address = IPAddress.Parse("192.168.0.132");
IPEndPoint sending_end_point = new IPEndPoint(send_to_address, 11000);
sending_socket.SendTo(Encoding.ASCII.GetBytes("Test"), sending_end_point);
// get info
var port = sending_socket.LocalEndPoint.ToString().Split(':')[1];
/* Part 2 receive data from server */
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, int.Parse(port));
byte[] buffer = new byte[1024];
sending_socket.Receive(buffer);
}
For some reason it worked a few times! It works when the client receives data successfully on the line: sending_socket.Receive(buffer);
Things to note:
If on the server on the second part I used the instance variable listner instead of creating the new variable sendSocket and send the bytes through that variable the client is able to receive the data being sent. Remember that the second part of the server is going to be implemented by a second client B that's why I am initializing variables again from scratch...
Edit:
Here is a different way of looking at the same problem. When I initialize a new object instead of using the same object the client does not receives the response.
I have a object of type UdpClient. I am able to send data with that object to the other peer. If I create another object of the same type with the same properties and attempt to send data it does not work! I might be missing to initialize some variables. I am able to set private variables with reflection so I should not have a problem. anyways here is the server code:
public static void Main()
{
// wait for client to send data
UdpClient listener = new UdpClient(11000);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, 11000);
byte[] receive_byte_array = listener.Receive(ref groupEP);
// connect so that we are able to send data back
listener.Connect(groupEP);
byte[] dataToSend = new byte[] { 1, 2, 3, 4, 5 };
// now let's atempt to reply back
// this part does not work!
UdpClient newClient = CopyUdpClient(listener, groupEP);
newClient.Send(dataToSend, dataToSend.Length);
// this part works!
listener.Send(dataToSend, dataToSend.Length);
}
static UdpClient CopyUdpClient(UdpClient client, IPEndPoint groupEP)
{
var ip = groupEP.Address.ToString();
var port = groupEP.Port;
var newUdpClient = new UdpClient(ip, port);
return newUdpClient;
}
the client code basically sends data to the server and then waits for a response:
string ipOfServer = "192.168.0.132";
int portServerIsListeningOn = 11000;
// send data to server
Socket sending_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPAddress send_to_address = IPAddress.Parse(ipOfServer);
IPEndPoint sending_end_point = new IPEndPoint(send_to_address, portServerIsListeningOn);
sending_socket.SendTo(Encoding.ASCII.GetBytes("Test"), sending_end_point);
// get info
var port = sending_socket.LocalEndPoint.ToString().Split(':')[1];
// now wait for server to send data back
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, int.Parse(port));
byte[] buffer = new byte[1024];
sending_socket.Receive(buffer); // <----- keeps waiting in here :(
note that the client is behind a router (NAT) otherwise I will not have this problem. The reason why I will like to copy udpClient is so that I can send that variable to another computer enabling the other computer to send data to the client.
So my question is why is the original object listener able to send data but newClient is not able to? The client keeps waiting at line sending_socket.Receive(buffer); even after the server executes the line: newClient.Send(dataToSend, dataToSend.Length);. the client successfully receives data when listener sends the data but not newClient. Why is this if both variables have the same destination IP and port? how do the variables differ?
Note:
If the server and client are on the same network then the copy works and variable newClient is able to send data to the client. To simulate this problem the client must be behind a NAT (router). An example of such network may consist of two routers. let's call them router X and router Y. You also need a Server call that S. and a client C. so S can be connected to one of the LAN ports of X. C can be connected to one of the LAN ports of Y. Finally connect the WAN port of Y to one of the LAN ports of X.
Hmm, I think you are confusing several things here. For one thing, it's really called UDP hole punching. Let me try to explain how this should work.
NAT routers usually do port mapping when forwarding packets from the inside private network to the outside internet.
Say you created a UDP socket on a machine behind NAT, and sent a datagram to some external IP/port. When the IP packet carrying that datagram leaves the sending machine, its IP header has the source address field set to local not-globally-routable private IP address (like 192.168.1.15), and UDP header has the source port field set to whatever port was assigned to the socket (either explicitly via binding, or implicitly picked by the OS from the ephemeral ports). I'll call this source port number P1.
Then when the NAT router sends that packet out on the outside network, it overwrites the source IP address to its own external IP address (otherwise there's no way to route packets back), and often overwrites the source UDP port to some other value (maybe because some other host on the private network uses the same source port, which creates ambiguity). The mapping between the original source port and that new port number (let's label it P2) is preserved in the router to match return packets. This mapping might also be specific to the target IP address and target UDP port.
So now you have "punched a hole" in the router - UDP packets sent back to the router to port P2 are forwarded to internal machine on UDP port P1. Again, depending on NAT implementation, this could be restricted to only packets from the original target IP address and target UDP port.
For client-to-client communication you'll have to tell external IP/port of one to the other through the server, hoping that the NAT router maps same internal source ports to same external source ports. Then the clients will send packets to each other using those.
Hope this helps.
Finally found the answer! Here is the implemenation with just a client and a server. My next attempt will be to use 3 computers. anyways hope this helps:
Server code:
class Program
{
static byte[] dataToSend = new byte[] { 1, 2, 3, 4, 5 };
// get the ip and port number where the client will be listening on
static IPEndPoint GetClientInfo()
{
// wait for client to send data
using (UdpClient listener = new UdpClient(11000))
{
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, 11000);
byte[] receive_byte_array = listener.Receive(ref groupEP);
return groupEP;
}
}
static void Main(string[] args)
{
var info = GetClientInfo(); // get client info
/* NOW THAT WE HAVE THE INFO FROM THE CLIENT WE ARE GONG TO SEND
DATA TO IT FROM SCRATCH!. NOTE THE CLIENT IS BEHIND A NAT AND
WE WILL STILL BE ABLE TO SEND PACKAGES TO IT
*/
// create a new client. this client will be created on a
// different computer when I do readl udp punch holing
UdpClient newClient = ConstructUdpClient(info);
// send data
newClient.Send(dataToSend, dataToSend.Length);
}
// Construct a socket with the info received from the client
static UdpClient ConstructUdpClient(IPEndPoint clientInfo)
{
var ip = clientInfo.Address.ToString();
var port = clientInfo.Port;
// this is the part I was missing!!!!
// the local end point must match. this should be the ip this computer is listening on
// and also the port
UdpClient client = new UdpClient(new IPEndPoint( IPAddress.Any, 11000));
// lastly we are missing to set the end points. (ip and port client is listening on)
// the connect method sets the remote endpoints
client.Connect(ip, port);
return client;
}
}
client code:
string ipOfServer = "192.168.0.139";
int portServerIsListeningOn = 11000;
// send data to server
Socket sending_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPAddress send_to_address = IPAddress.Parse(ipOfServer);
IPEndPoint sending_end_point = new IPEndPoint(send_to_address, portServerIsListeningOn);
sending_socket.SendTo(Encoding.ASCII.GetBytes("Test"), sending_end_point);
// get info
var port = sending_socket.LocalEndPoint.ToString().Split(':')[1];
// now wait for server to send data back
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, int.Parse(port));
byte[] buffer = new byte[1024];
sending_socket.Receive(buffer); // <----- we can receive data now!!!!!
Have you considered using UPnP on the client to configure NAT traversal to allow incoming packets on a particular port? The client would then only need to communicate the inbound IP and port to the server, and wait for the server to send packets.
http://en.wikipedia.org/wiki/Universal_Plug_and_Play
Seems you are able to connect with the server first time.After successful connection you need to close and disconnect the connection each time.Please check this sample code
http://codeidol.com/csharp/csharp-network/Connectionless-Sockets/A-Simple-UDP-Application/

Categories

Resources