Remote UDP send and receive - c#

Im trying to create a server/client application that will work on two or more remote computers with no local network between them.
So i searched the internet and find a TON and TONES of C# UDP client/server examples just like here.
BUT i didn't find anywhere how to send a UDP socket over the internet on remote computer with, lets say IP="130.204.159.205";
please with your answers give me some example code

The example you linked shows how to create the socket, just remove the line IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName()) and put use this constructor and pass in a byte array with your ip address 130.204.159.205
(...)
// Connect to a remote device.
try {
// Establish the remote endpoint for the socket.
// This example uses port 11000 on the local computer.
IPAddress ipAddress = new IPAddress(new byte[] { 130, 204, 159, 205});
IPEndPoint remoteEP = new IPEndPoint(ipAddress,11000);
(...)

Related

C# client connection, Socket Exception:The system detected an invalid pointer address

I've written a server and client in C# .net 4.6 that should accept both ipv6 and ipv4 connections. The relevant code for the server listener is as follows:
listener = new Socket(AddressFamily.InterNetworkV6,
SocketType.Stream, ProtocolType.Tcp);
listener.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false);
listener.DualMode = true;
// Bind the socket to the local endpoint and listen for incoming connections.
try
{
listener.Bind(new IPEndPoint(IPAddress.IPv6Any, 3425));
listener.Listen(100);
And the client connects like this:
socket = new Socket(AddressFamily.Unspecified, SocketType.Stream, ProtocolType.Tcp);
try
{
IPAddress[] ip = Dns.GetHostAddresses(ipAddress);
StatusBoxHandler.statusText = "Connecting...";
IPEndPoint remoteEP = new IPEndPoint(ip[0], port);
Debug.Log(ip[0]);
socket.Connect(remoteEP);
I've had no problems so far with 3 different people trying to connect to this server with the given client. The fourth person, who is running Windows 8.1 however is having a bit of difficulty.
He is unable to ping the server with the hostname as it says destination unreachable, and he is unable to ping the servers ipv6 address, giving the error:
PING: transmit failed, general failure.
He is however able to ping the ipv4 address successfully. The weird bit with this is that he has ipV6 enabled and I have verified this.
When attempting to connect with the client and forcing it to use the ipv4 address he obtains the error:
System.Net.Sockets.SocketException: The system detected an invalid pointer address in attempting to use a pointer argument in a call.
I've also verified that in the log it's connecting to the exact same ipv4 address that mine would use to connect, so it's not a matter of it obtaining the wrong ip address. Additionally, I've connected from the client to the server successfully with ipv6, ipv4 and the dns hostname addresses and they all work fine for my machine and two others.
Is there some sort of problem in my code that I'm missing or is there just some sort of strange unrelated issue that is only affecting his machine?
The way IP addess is being retrieved is not correct. Instead use below way
var ipHostInfo = Dns.GetHostEntry("localhost");
var ipAddress = ipHostInfo.AddressList.FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork);

Connect TcpClient to a remote Tcp server, binding to a specific local port

I built tcp client/server application for my organisation. The server opens and listens to a specific port, and each client establishes Tcp Connection to the server port. Nothing special. The application works beautifully. But today, one client wanted the Tcp client app to work over WiFi network with firewall. The WiFi firewall is configured to block all ports by default. If I want my application to work, I have to give their network administrator a list of ports to open for my application. The server listening port is configurable so it is easy. Once I configure the port, I can give them is this specific port for the server. However the client app is unable to connect to the server because each time a TcpClient establishes a connection, it creates a random local Tcp port that will be blocked by their firewall.
Their network admin will not open all ports for the machine because they said it created security risks for their organisation. Therefore, I am looking for a way to force the client to open a specific local port when it establishes a Tcp connection. I've both looked into MSDN docs and been Googling but I haven't found an adequate answer. Would you be able to suggest a workaround or a third party library that can do that? Thank heaps.
I'm not aware of any way to have this level of control with TcpClient. However, if you manually create the Socket object, you can bind to a local port of your choosing:
var sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Specify the local port to use
var endpoint = new IPEndPoint(IPAddress.Any, 9999);
sock.Bind(endpoint);
// And connect to the remote end point
sock.Connect("example.com", 80);
Of course, by doing this you limit yourself to one connection on the machine.
how about use bind() like this(if you are using c++)
struct sockaddr_in cli;
memset(&cli, 0x00, sizeof(cli));
cli.sin_family = AF_INET;
cli.sin_port = htons(YOUR PORT);
cli.sin_addr.s_addr = inet_addr(YOUR IP ADDRESS);
int on = 1;
if (setsockopt(hSocket, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on)) < 0){
perror("Set Error");
}
bind(hSocket, (struct sockaddr *)&cli, sizeof(struct sockaddr));
int nRet = connect(hSocket,(sockaddr*)&svr, sizeof(svr));

Use c# application (TcpListener) as a web server

I have been trying to do this for a while. I'm using the MSDN example for the TCPListener, being able to connect to it within the same newtork (i.e: from a terminal on my mobile phone).
I also understand that this works because of them being connected to the same router; I have entered to my router configurations and forwarded port 13450, which is the port I'm using on my TCP Listener constructor, to my computer's IP Address, and I've also submitted Windows firewall rules to not block this port for any external application.
After saving the port forwarding, I change IP Address on my C# Console Application to my router's IP (Default Gateway)
I've tried from hyperterminal on windows or from a terminal on my mobile phone to connect to my application (Using my router's IP and the corresponding port), but have never been able to manage this.
I would really appreciate help for this, as I cannot encounter a useful solution searching on Google
Thanks.
This is the code
Int32 port = 13450;
IPAddress localAddr = IPAddress.Parse("189.148.67.13");
// 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!");}
The IP is the public IP for my router; and on its config i've forwarded port 13450 to my local computer. Thanks

TCP Port listener not working

I need to connect a handheld with a PC. So I'm following this MSDN example which has a Client and a Server program.
Now, the handheld is connected through GPRS. If I run the Client program on the handheld and listen to the port on the PC, I see the data that the handheld send. But if I run the Server program it doesn't receive anything.
My code follows the example exactly, only modifying the port in both programs(11000) and in the client I changed the server IP to my public address.
Why am I seeing the data in my TCP listener but not in my Server program?
The problem was in the Server Code. When configuring the IPAddress it wasn't creating a correct one.
I changed this line by this one and everything is working ok now:
IPAddress ipAddress = new IPAddress(new byte[] { 192, 168, 1, 10 });
Hope it help to another facing the same problem!

C# Sockets, How to get IP addresses and port # of all listening (sockets) computers

I am using C# sockets to have a connection between a device (client) and a computer (server).
All is working good except for the fact that I am trying to avoid the user to enter the IP address and port number wherein to connect to on the device. Instead I want a listbox or drop down list of all IP addresses with listening sockets. Just wondering if there's a way to get all the IP addresses and port numbers of hosts with listening (socket)?
Thanks for any help! :)
What you're asking to do is called a port scan. It basically involves testing each IP address in a range and each port and reporting the success of that attempt. It's slow and it will cause a lot of alarms if there is any kind of threat monitoring on the network because port scanning is one of the ways attackers try to find network vulnerabilities.
So in short, this is a bad idea and probably won't be responsive enough for you to use for this purpose. Instead what you might consider is using a central server as a "directory" that each server would register with.
Or you can send out a broadcast on your subnet and wait for servers to respond. This is how some of the peer networking works in Windows for example. Note that this assumes you are the developer of the server as well and you can add in the logic necessary for the server to listen for broadcasts.
By using UDP broadcast, you can send out the data to the Server which are listening at the fixed port. The following is the working example.
foreach (IPAddress ip in allLocalNetworkAddresses.AddressList)
{
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//Allow sending broadcast messages
client.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.Broadcast, 1);
//Create endpoint, broadcast.
IPEndPoint AllEndPoint = new IPEndPoint(IPAddress.Broadcast, Port);
byte[] sendData = Encoding.ASCII.GetBytes("1");
//Send message to everyone on this network
client.SendTo(sendData, AllEndPoint);
Console.Write("Client send '1' to " + AllEndPoint.ToString() +
Environment.NewLine);

Categories

Resources