c# udp broadcast package not receiving - c#

I got into UDP and decided to make a small chat just for practice.
I ran into a problem and I can't figure it out myself.
I created two c# console Programs which are exactly the same (Just Port is different)
I send a UDP broadcast package and then want to receive it on the second console program. What happens tho is that the program I send the broadcast from receives it and the other program doesn't. Same happens at the other way round.
I already switched off my firewall --> doesn't change anything.
I post you the whole code, I hope you guys can help me I would really love to keep going! Thank you so much!
class Program
{
const int PORT = 10101;
private static readonly UdpClient udpclient = new UdpClient(PORT);
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Red;
udpclient.EnableBroadcast = true;
//bool for calling async receiver just once
bool receiving = false;
Console.WriteLine("Chat 2");
//to keep while loop running --> change later
bool keepchatting = true;
#region keepchating loop
while (keepchatting)
{
if (!receiving)
{
startlistening();
}
receiving = true;
newmessage();
}
}
#endregion
//new message --> call sendmessage to broadcast text via UDP
public static void newmessage()
{
string msg;
msg = Console.ReadLine();
byte[] message = Encoding.ASCII.GetBytes(msg);
sendmessage(message);
}
//Broadcast text via UDP
public static void sendmessage(byte[] tosend)
{
UdpClient client = new UdpClient();
client.EnableBroadcast = true;
IPEndPoint ip = new IPEndPoint(IPAddress.Parse("255.255.255.255"), PORT);
client.Send(tosend, tosend.Length, ip);
client.Close();
Console.WriteLine("Sent!");
}
static IAsyncResult ar = null;
//Setup Async Receive Method
public static void startlistening()
{
ar = udpclient.BeginReceive(RecievedMessage, new object());
}
//Message
public static void RecievedMessage(IAsyncResult ar)
{
IPEndPoint ip = new IPEndPoint(IPAddress.Any, PORT);
byte[] bytes = udpclient.EndReceive(ar, ref ip);
string msg = Encoding.ASCII.GetString(bytes);
Console.WriteLine("Received: " + msg);
startlistening();
}
}

I have changed only two parts to your code, on each client set the remote port number of the other client, try this:
On one client:
const int PORT = 10101;
const int PORT_Remote = 10102;
IPEndPoint ip = new IPEndPoint(IPAddress.Parse("255.255.255.255"), PORT_Remote);
On the other client:
const int PORT = 10102;
const int PORT_Remote = 10101;
IPEndPoint ip = new IPEndPoint(IPAddress.Parse("255.255.255.255"), PORT_Remote);

I've wrote an application recently where I was sending socket messages back and forth between two applications on my laptop. I used 127.0.0.1 (default IP address for local host) for the IP address. Could you try that?

Related

C# UDPClient not receiving packets over external IP

So here's the thing, i'm creating a server/client environment for a game where a port forwarded computer acts as a server, and clients send the first UDP message to connect and get the accept message then start sending the in-game UDP messages after successfully connecting.
The problem is, when I use the local IPs say the server using 10.0.0.7 and a client is using 10.0.0.4, everything works just fine:
Client sends connect message.
Server receives it.
Servers sends back accept message.
Client receives it
All further messages reach both ends without any problem.
But when I use the external IP:
Client sends connect message.
Server receives it.
Servers sends back accept message.
Client receives it
Both ends can send messages but the client doesn't receive any more messages.
Wanted to know at the end if the problem is somehow from the code, or from what I think it's really from, router, NAT, firewalls or anything like that.
(Note: Client sends to server's 8888 port, and server sends back through the client's local port, as it should be.)
Below is the client code, written for Unity:
void Start()
{
client = new UdpClient();
client.Connect(IPAddress.Parse("<Global IP>"), 8888);
client.BeginReceive(new AsyncCallback(ReadMessage), client);
}
private void ReadMessage(IAsyncResult result)
{
IPEndPoint ipEndPoint = null;
string message = Encoding.ASCII.GetString(client.EndReceive(result, ref ipEndPoint));
print("Got: " + message);
string[] wholeMessages = message.Split('#');
for (int w = 0; w < wholeMessages.Length - 1; w++)
{
string[] parts = wholeMessages[w].Split('$');
if (!connected && parts.Length == 3 && parts[0] == "accept" && int.TryParse(parts[1], out ID))
{
connected = true;
code = parts[2];
}
}
client.BeginReceive(new AsyncCallback(ReadMessage), client);
}
public void SendUDP(string message)
{
client.Send(Encoding.ASCII.GetBytes(message), message.Length);
}
Ok, after several trials and errors this worked for me...
//Server Code
private static UdpClient udpClient;
static void Main(string[] args)
{
Console.WriteLine("Server initiated...");
udpClient = new UdpClient(8888);
}
private static void ReadMessage()
{
while (true)
{
try
{
IPEndPoint IPEP = null;
string message = Encoding.ASCII.GetString(udpClient.Receive(ref IPEP));
}
}
}
private static void SendUDP(IPEndPoint e,string message)
{
new UdpClient().Send(Encoding.ASCII.GetBytes(message), message.Length, e);
}
//Client Code
private IPAddress ip;
void Start()
{
ip = Dns.GetHostAddresses("HOSTNAME")[0];
client = new UdpClient(new IPEndPoint(IPAddress.Any, 0));
udpThread = new Thread(new ThreadStart(ReadMessage))
{
IsBackground = true
};
udpThread.Start();
}
private void ReadMessage()
{
while (true)
{
try
{
IPEndPoint IPEP = null;
byte[] data = client.Receive(ref IPEP);
string message = Encoding.ASCII.GetString(data);
}
}
}
public void SendUDP(string message)
{
client.Send(Encoding.ASCII.GetBytes(message), message.Length, new IPEndPoint(ip, 8888));
}

Socket Programming c# / Client-Server communication

I am trying to make 2 programs (in console application) in .NET that communicate together through the web (the code is from a video that you can find below, I am just trying to make the code work before adapting it). Forgive me, I'm not an experienced programmer.
I have a server and a client, they work perfectly when I run both of them on my computer (locally).
I can connect multiple clients to the server, send requests and get a response.
I am facing the problem when i run the server on a computer and the client on an other one and I try to connect through the internet.
I can connect to the server but communication does not work, there is no data exchange when try to request time as an example. I think that the problem is mostly coming from the network itself than the code.
Here's the code for the server:
class Program
{
private static Socket _serverSocket;
private static readonly List<Socket> _clientSockets = new List<Socket>();
private const int _BUFFER_SIZE = 2048;
private const int _PORT = 50114;
private static readonly byte[] _buffer = new byte[_BUFFER_SIZE];
static void Main()
{
Console.Title = "Server";
SetupServer();
Console.ReadLine(); // When we press enter close everything
CloseAllSockets();
}
private static void SetupServer()
{
// IPAddress addip = GetBroadcastAddress();
Console.WriteLine("Setting up server...");
_serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_serverSocket.Bind(new IPEndPoint(IPAddress.Any , _PORT));
_serverSocket.Listen(5);
_serverSocket.BeginAccept(AcceptCallback, null);
Console.WriteLine("Server setup complete");
}
/// <summary>
/// Close all connected client (we do not need to shutdown the server socket as its connections
/// are already closed with the clients)
/// </summary>
private static void CloseAllSockets()
{
foreach (Socket socket in _clientSockets)
{
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
_serverSocket.Close();
}
private static void AcceptCallback(IAsyncResult AR)
{
Socket socket;
try
{
socket = _serverSocket.EndAccept(AR);
}
catch (ObjectDisposedException) // I cannot seem to avoid this (on exit when properly closing sockets)
{
return;
}
_clientSockets.Add(socket);
socket.BeginReceive(_buffer, 0, _BUFFER_SIZE, SocketFlags.None, ReceiveCallback, socket);
Console.WriteLine("Client connected, waiting for request...");
_serverSocket.BeginAccept(AcceptCallback, null);
}
private static void ReceiveCallback(IAsyncResult AR)
{
Socket current = (Socket)AR.AsyncState;
int received;
try
{
received = current.EndReceive(AR);
}
catch (SocketException)
{
Console.WriteLine("Client forcefully disconnected");
current.Close(); // Dont shutdown because the socket may be disposed and its disconnected anyway
_clientSockets.Remove(current);
return;
}
byte[] recBuf = new byte[received];
Array.Copy(_buffer, recBuf, received);
string text = Encoding.ASCII.GetString(recBuf);
Console.WriteLine("Received Text: " + text);
if (text.ToLower() == "get time") // Client requested time
{
Console.WriteLine("Text is a get time request");
byte[] data = Encoding.ASCII.GetBytes(DateTime.Now.ToLongTimeString());
current.Send(data);
Console.WriteLine("Time sent to client");
}
else if (text.ToLower() == "exit") // Client wants to exit gracefully
{
// Always Shutdown before closing
current.Shutdown(SocketShutdown.Both);
current.Close();
_clientSockets.Remove(current);
Console.WriteLine("Client disconnected");
return;
}
else
{
Console.WriteLine("Text is an invalid request");
byte[] data = Encoding.ASCII.GetBytes("Invalid request");
current.Send(data);
Console.WriteLine("Warning Sent");
}
current.BeginReceive(_buffer, 0, _BUFFER_SIZE, SocketFlags.None, ReceiveCallback, current);
}
}
And here the client code:
class Program
{
private static readonly Socket _clientSocket = new Socket
(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
private const int _PORT = 50114;
static void Main()
{
Console.Title = "Client";
ConnectToServer();
RequestLoop();
Exit();
}
private static void ConnectToServer()
{
int attempts = 0;
while (!_clientSocket.Connected)
{
try
{
attempts++;
Console.WriteLine("Connection attempt " + attempts);
_clientSocket.Connect("IpAddr", _PORT);
}
catch (SocketException)
{
Console.Clear();
}
}
Console.Clear();
Console.WriteLine("Connected");
}
private static void RequestLoop()
{
Console.WriteLine(#"<Type ""exit"" to properly disconnect client>");
while (true)
{
SendRequest();
ReceiveResponse();
}
}
/// <summary>
/// Close socket and exit app
/// </summary>
private static void Exit()
{
SendString("exit"); // Tell the server we re exiting
_clientSocket.Shutdown(SocketShutdown.Both);
_clientSocket.Close();
Environment.Exit(0);
}
private static void SendRequest()
{
Console.Write("Send a request: ");
string request = Console.ReadLine();
SendString(request);
if (request.ToLower() == "exit")
{
Exit();
}
}
/// <summary>
/// Sends a string to the server with ASCII encoding
/// </summary>
private static void SendString(string text)
{
byte[] buffer = Encoding.ASCII.GetBytes(text);
_clientSocket.Send(buffer, 0, buffer.Length, SocketFlags.None);
}
private static void ReceiveResponse()
{
var buffer = new byte[2048];
int received = _clientSocket.Receive(buffer, SocketFlags.None);
if (received == 0) return;
var data = new byte[received];
Array.Copy(buffer, data, received);
string text = Encoding.ASCII.GetString(data);
Console.WriteLine(text);
}
}
static void Main()
{
Console.Title = "Client";
ConnectToServer();
RequestLoop();
Exit();
}
private static void ConnectToServer()
{
int attempts = 0;
while (!_clientSocket.Connected)
{
try
{
attempts++;
Console.WriteLine("Connection attempt " + attempts);
_clientSocket.Connect("IpAddr", _PORT);
}
catch (SocketException)
{
Console.Clear();
}
}
Console.Clear();
Console.WriteLine("Connected");
}
"IpAddr" is a placeholder for the public IP of the router.
This is the video my current code is based on: https://www.youtube.com/watch?v=xgLRe7QV6QI
I took the code directly from it (you can find the 2 code files on the site linked in description).
I run the server, it awaits for a connection. I then run the clients which tries to connect to the server. I connects and on the server it shows the successful connection. The client then sends a request like "get time" and the server is supposed to catch it and respond:
byte[] data = Encoding.ASCII.GetBytes(DateTime.Now.ToLongTimeString());
current.Send(data);
Back to network side:
Here is a list of all the things I have tried, that were the usual main causes of the problem after looking for a solution for about a full day:
I already have a static public IP for the router (so the public IP never changes). Even though, I created a dynamic dns on noip.com.
I gave a static lease to the computer the server runs on, so it has always the same local ip.
I created rules in the windows firewall to make sure the port I use is opened. I did this on both computers trying to communicate.
I forwarded the port on the router so it points to the local ip of the computer the server runs on. (I tried with a lot of different ports, no chance)
I tried activating the "DMZ" on the router but it's most likely not a solution
I tried to create a ASP.NET website which page returns a string, publish it with IIS 7.5 and set it up. Works on localhost but using the public ip like "xx.xxx.xxx.xx:PORT/default/index" I get an error. Yet it shows the website name in the error. Also, when using the local IP of the computer, it doesn't work either (something like 192.168.1.180).
Thanks for you help.
I learned about message framing, Thank you CodeCaster.
For people who are curious about it, here is an interesting link i found about it: http://blog.stephencleary.com/2009/04/message-framing.html
But before trying to change the code, I ran the server on an AWS vps and it worked instantly, the problem was probably comming from my isp or my router. I am just wondering how can it work without handling message framing.

UdpClient on local machine

I'm new to C# UDP coding and I have some 'strange' behaviour when using an UDP client locally on my pc.
I want to send UDP data from one port (11000) on my pc to another port (12000) on the same pc.
This is a snippet from my code :
public class MyClass
{
//Creates a UdpClient for reading incoming data.
private UdpClient udpClient;
private Thread thread;
private const String IPADDR = "127.0.0.1";
public MyClass()
{
udpClient = new UdpClient(11000);
udpClient.Connect(IPAddress.Parse(IPADDR), 12000);
this.thread = new Thread(new ThreadStart(this.Execute));
this.thread.Name = "Udp";
this.thread.Start();
SendData("The quick brown fox jumps over the lazy dog");
}
private void Execute()
{
try
{
// Blocks until a message returns on this socket from a remote host.
IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
Byte[] receiveBytes = this.udpClient.Receive(ref remoteIpEndPoint);
Console.WriteLine("Data received");
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public void SendData(String data)
{
Console.WriteLine("Sending...");
try
{
this.udpClient.Send(System.Text.Encoding.ASCII.GetBytes(data), data.Length);
}
catch (Exception e)
{
Console.WriteLine(String.Format("Exception {0}", e.Message));
}
}
}
If I run this, I get an exception :
Sending...
System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
at System.Net.Sockets.Socket.ReceiveFrom(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags, EndPoint& remoteEP)
at System.Net.Sockets.UdpClient.Receive(IPEndPoint& remoteEP)
at test.MyClass.Execute() in C:\Temp\test\Class1.cs:line 40
The exception seems to occur on this line :
Byte[] receiveBytes = this.udpClient.Receive(ref remoteIpEndPoint);
At the moment of the SendData(), the Receive is throwing the exception. When not doing the send, I don't get the exception. It looks like the send is causing the receive to return with an exception.
When I use the real ip address of my pc, I have the same behaviour. However, when I use any other ip address, even if it's unassigned to any pc (e.g. 192.168.10.10), it's working well : it sends the string and the Receive() keeps waiting for incoming data.
The error happens because there is no socket open on the port to which you are sending.
For the purposes of simply testing UDP communications, you can fix your code example simply by changing the port to which you are sending. I.e. change the Connect() method call to this:
udpClient.Connect(IPAddress.Parse(IPADDR), 11000);
This will cause the socket to send to itself. Your code will work successfully with just this change.
For the record, here is about the simplest possible demonstration code that uses UdpClient:
UdpClient client = new UdpClient(0, AddressFamily.InterNetwork);
byte[] datagram = Encoding.ASCII.GetBytes("hello world!");
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)client.Client.LocalEndPoint).Port);
client.Send(datagram, datagram.Length, ipEndPoint);
datagram = client.Receive(ref ipEndPoint);
Console.WriteLine("Received: \"" + Encoding.ASCII.GetString(datagram) + "\"");
Of course, in a real network I/O situation, you will have two endpoints, each bound to its own local port, sending to the other endpoint's port. So neither your code example, nor this simpler one I present is very useful as an actual working program. But it does allow you to learn some things about how the socket API works.
You are trying to send from one socket (UdpClient which is socket wrapper) to itself. Thats not how the things work in UDP (nor in other IP protocols). You need 2 sockets. One for sending one for receiving. Connect method is poorly named since UDP protocol is conectionless but thats not your fault.
Other than that you need to put socket in listening state before sending to it. So you first need to start thread that listens and then send.
You need to better design your program but this will work:
class Program
{
static void Main(string[] args)
{
MyClass mc = new MyClass();
}
}
public class MyClass
{
//Creates a UdpClient for reading incoming data.
private UdpClient udpClient;
private UdpClient recipient;
private Thread thread;
private const String IPADDR = "127.0.0.1";
public MyClass()
{
recipient = new UdpClient(new IPEndPoint(IPAddress.Parse(IPADDR), 12000));
this.thread = new Thread(new ThreadStart(this.Execute));
this.thread.Name = "Udp";
this.thread.Start();
udpClient = new UdpClient(11000);
udpClient.Connect(IPAddress.Parse(IPADDR), 12000);
SendData("The quick brown fox jumps over the lazy dog");
}
private void Execute()
{
try
{
// Blocks until a message returns on this socket from a remote host.
IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Parse(IPADDR), 11000);
Byte[] receiveBytes = this.recipient.Receive(ref remoteIpEndPoint);
Console.WriteLine("Data received: " + Encoding.ASCII.GetString(receiveBytes));
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public void SendData(String data)
{
Console.WriteLine("Sending...");
try
{
this.udpClient.Send(System.Text.Encoding.ASCII.GetBytes(data), data.Length);
}
catch (Exception e)
{
Console.WriteLine(String.Format("Exception {0}", e.Message));
}
}
}

UDP sending / receiving on a free port

In a project there is a device that listens on a specific UDP port and answers to the senders port.
For the sender and receiver I want the system to choose a free port, so I have the following code:
[Please excuse the vast masses of code, but this is the smallest example to show what behaviour occurs]
Sending code:
public class UdpSender
{
public int Port = 0; // some initially random port
public UdpClient UdpServer { get; set; }
public UdpSender()
{
UdpServer = CreateUdpClient();
// save the portnumber chosen by system to reuse it
Port = ((IPEndPoint)(UdpServer.Client.LocalEndPoint)).Port;
}
private UdpClient CreateUdpClient()
{
if (UdpServer != null)
{
UdpServer.Close();
}
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, Port);
var udpServer = new UdpClient();
udpServer.ExclusiveAddressUse = false;
udpServer.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
udpServer.Client.Bind(localEndPoint);
return udpServer;
}
public void Send(byte[] arr)
{
UdpServer = CreateUdpClient();
int remotePortNumber = 6565;
var remoteEndPoint = new IPEndPoint(IPAddress.Broadcast, remotePortNumber);
try
{
UdpServer.Send(arr, arr.Length, remoteEndPoint);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
UdpServer.Close();
}
}
Receiving code:
public class UDPListener
{
private static int portNumber;
private UdpClient udpClient = null;
public List<DeviceData> DeviceList = new List<DeviceData>();
public UDPListener(int port)
{
portNumber = port;
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, portNumber);
udpClient = new UdpClient();
udpClient.ExclusiveAddressUse = false;
udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
udpClient.Client.Bind(localEndPoint);
udpClient.Client.ReceiveBufferSize = 1 << 23;
}
public void StartListening()
{
this.udpClient.BeginReceive(Receive, new object());
}
private void Receive(IAsyncResult ar)
{
IPEndPoint ip = new IPEndPoint(IPAddress.Any, portNumber);
byte[] bytes = udpClient.EndReceive(ar, ref ip);
string message = Encoding.ASCII.GetString(bytes);
DeviceList.Add(new DeviceData(message));
StartListening();
}
}
Bringing it together:
public class DeviceFinder
{
public IEnumerable<DeviceData> Find()
{
var sender = new UdpSender();
int port = sender.Port;
var listener = new UDPListener(port);
listener.StartListening();
sender.Send(new byte[] { 0x1, 0x2, 0x3, 0x4, 0x5, 0x6 });
System.Threading.Thread.Sleep(5000); // wait some time for answers
return listener.DeviceList;
}
}
The Receive method is never called with this approach. But in Wireshark, I can see an answer coming from the device.
What is wrong about this approach?
Before using this approach, I have used a fixed port and the call to CreateUdpClient was added also. Seems to have something to with that, but I cannot figure it out.
Before I just created a UdpClient with the fixed port just inside the receive / send method.
The previous version can be seen in this question. This works perfectly. But I fear if the fixed port is already in use, it does not work, hence this new approach.
Just specify zero as your own port number. The system will allocate one when you bind or send. The source port number will accompany the datagram to the peer, who should reply to it.

C# UDP Server/Client - NAT

Iam trying to send a message (via UDP) from my client to my server. The server should answer this message and if the client receives this answer he should print out a message.
If i run the client and server on my local network everything works fine.
If i try to connect through the internet from another PC outside my network the server receives the request of the client, sends an answer back, but the client never receives this answer. The client and the server are both behind a NAT but i portforwarded the ports at the server´s NAT and the server got its own DNS. I already tried NAT traversal but it gives me the same IP and port adress as the IPEndPoint of the server, after receiveing the request of the client, does.
I´ve got no idea how to fix this, so any guidance would be much appreciated.
Client
public static void Main()
{
Thread receiveThread = new Thread(new ThreadStart(ReceiveData));
receiveThread.Start();
object[] oData = {1};
sendData(oData, 0,0, "Li");
while (true)
{
Console.ReadLine();
}
}
private void receiveData()
{
string receivePort = 8080;
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
client.ReceiveTimeout = 1000;
IPEndPoint end = new IPEndPoint(IPAddress.Any, receivePort);
client.Bind(end);
while (true)
{
try
{
byte[] data = new byte[1024];
client.Receive(data, 0, data.Length, SocketFlags.None);
object[] receivedObj = Deserialize(data);
string sType = (string)receivedObj[3];
if (sType == "Li")
{
console.WriteLine("received Li");
}
}
catch (Exception err)
{
Console.WriteLine(err.ToString());
}
}
}
public static void sendData(object[] oData, int iFrom, int iTo, string sType)
{
string sendPort = 17171;
UdpClient client = new UdpClient();
string IP = "ThisIsTheDNSofmyServer.com"; //ServerDNS
//string IP = "192.168.xxx.xxx"; //serverIP in LAN
if (IP.StartsWith("T"))
{
IP = (Dns.GetHostAddresses(IP))[0].ToString();
}
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(IP), sendPort);
oData[1] = iFrom;
oData[2] = iTo;
oData[3] = sType;
Byte[] data = Serialize(oData);
client.Send(data, data.Length, remoteEndPoint);
}
The server´s code is almost the same:
public static void Main()
{
Thread receiveThread = new Thread(new ThreadStart(ReceiveData));
receiveThread.Start();
while (true)
{
Console.ReadLine();
}
}
private static void ReceiveData()
{
int receivePort = 17171;
UdpClient client = new UdpClient(receivePort);
while (true)
{
try
{
IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
byte[] data = new byte[1024];
data = client.Receive(ref anyIP);
object[] receivedObj = Deserialize(data);
//if I receive data send an Answer
sendData(receivedObj, 0,0,"Li",anyIP.Address.ToString());
}
catch (Exception err)
{
Console.WriteLine(err.ToString());
}
}
}
private static void sendData(object[] oData, int iFrom, int iTo, string sType, string IP)
{
int sendPort = 8080;
object[] paket = { oData, iFrom, iTo, sType };
UdpClient client = new UdpClient();
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(IP), sendPort);
client.Send(data, data.Length, remoteEndPoint);
}
i believe this is a port cofniguration issue,
8080 is almost likely to be configured as alternate http
"The UdpClient you use to receive datagrams must be created using the multicast port number" from MSDN
Hope this helps and good luck
Krishna
You do not need to do anything unordinary to traverse NAT in the setup you described, you just need to send it from the server back to your client; specifically: you must send back to the end point, i.e. IP and port, you received it on.
client.Send(data, data.Length, remoteEndPoint); // remoteEndPoint is the IPEndPoint you got the datagram on

Categories