UDP packet capturing in c# - c#

Wireshark captures UDP packets in my LAN with follwoing details
Source IP 192.168.1.2
Destination IP 233.x.x.x
Source Port 24098
Destination Port 12074,12330
how can i capture it in c#?

Solved it myself
Here is my working code
class CAA
{
private Socket UDPSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
private IPAddress Target_IP;
private int Target_Port;
public static int bPause;
public CAA()
{
Target_IP = IPAddress.Parse("x.x.x.x");
Target_Port = xxx;
try
{
IPEndPoint LocalHostIPEnd = new
IPEndPoint(IPAddress.Any, Target_Port);
UDPSocket.SetSocketOption(SocketOptionLevel.Udp, SocketOptionName.NoDelay, 1);
UDPSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
UDPSocket.Bind(LocalHostIPEnd);
UDPSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 0);
UDPSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new
MulticastOption(Target_IP));
Console.WriteLine("Starting Recieve");
Recieve();
}
catch (Exception e)
{
Console.WriteLine(e.Message + " " + e.StackTrace);
}
}
private void Recieve()
{
try
{
IPEndPoint LocalIPEndPoint = new
IPEndPoint(IPAddress.Any, Target_Port);
EndPoint LocalEndPoint = (EndPoint)LocalIPEndPoint;
StateObject state = new StateObject();
state.workSocket = UDPSocket;
Console.WriteLine("Begin Recieve");
UDPSocket.BeginReceiveFrom(state.buffer, 0, state.BufferSize, 0, ref LocalEndPoint, new AsyncCallback(ReceiveCallback), state);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private void ReceiveCallback(IAsyncResult ar)
{
IPEndPoint LocalIPEndPoint = new
IPEndPoint(IPAddress.Any, Target_Port);
EndPoint LocalEndPoint = (EndPoint)LocalIPEndPoint;
StateObject state = (StateObject)ar.AsyncState;
Socket client = state.workSocket;
int bytesRead = client.EndReceiveFrom(ar, ref LocalEndPoint);
client.BeginReceiveFrom(state.buffer, 0, state.BufferSize, 0, ref LocalEndPoint, new AsyncCallback(ReceiveCallback), state);
}
public static void Main()
{
CAA o = new CAA();
Console.ReadLine();
}
public class StateObject
{
public int BufferSize = 512;
public Socket workSocket;
public byte[] buffer;
public StateObject()
{
buffer = new byte[BufferSize];
}
}
}

The Winpcap library is one of the best ways to do this. I have experience in doing this in C# and it was really easy to work with this library.
This project shows how to do it with C#.

Wireshark actually uses Winpcap to do this, and as the other answer indicates, you can use it as well.
You can also use the System.Net.Sockets.Socket class and place it in promiscuous mode. I use this to capture the IP traffic (e.g., TCP and UDP) from a given network interface. Here's an example.
using System.Net;
using System.Net.Sockets;
Socket socket =
new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
socket.Bind(new IPEndPoint(IPAddress.Parse("X.X.X.X"), 0)); // specify IP address
socket.ReceiveBufferSize = 2 * 1024 * 1024; // 2 megabytes
socket.ReceiveTimeout = 500; // half a second
byte[] incoming = BitConverter.GetBytes(1);
byte[] outgoing = BitConverter.GetBytes(1);
socket.IOControl(IOControlCode.ReceiveAll, incoming, outgoing);
Now that the socket is created and configured, you can use the Receive() method to start receiving data. Each time you call Receive(), the returned buffer will contain an IP packet. See here for the breakout of the IPv4 header, here for the UDP header, and here for the TCP header. If the Protocol field of the IP header contains a value of 17, then you have a UDP packet.
NOTE Raw sockets on Windows require that you be an administrator on your local system. The following language is contained in this MSDN article.
To use a socket of type SOCK_RAW
requires administrative privileges.
Users running Winsock applications
that use raw sockets must be a member
of the Administrators group on the
local computer, otherwise raw socket
calls will fail with an error code of
WSAEACCES. On Windows Vista and later,
access for raw sockets is enforced at
socket creation. In earlier versions
of Windows, access for raw sockets is
enforced during other socket
operations.

In order to use WinPcap for raw packet capturing in C#, you can try Pcap.Net.
It is a wrapper for WinPcap in C++/CLI and C# for easily capturing (sniffing) and injecting raw packets and it also contains an easy to use packets interpretation framework.

Using Pcap.Net in https://github.com/PcapDotNet
Especific exemple: https://github.com/PcapDotNet/Pcap.Net/wiki/Pcap.Net-Tutorial-Interpreting-the-packets
// Callback function invoked by libpcap for every incoming packet
private static void PacketHandler(Packet packet)
{
// print timestamp and length of the packet
Console.WriteLine(packet.Timestamp.ToString("yyyy-MM-dd hh:mm:ss.fff") + " length:" + packet.Length);
IpV4Datagram ip = packet.Ethernet.IpV4;
UdpDatagram udp = ip.Udp;
// print ip addresses and udp ports
Console.WriteLine(ip.Source + ":" + udp.SourcePort+ " -> " + ip.Destination + ":" + udp.DestinationPort);
}
Output:
2009-09-12 11:25:51.117 length:84
10.0.0.8:49003 -> 208.67.222.222:53
2009-09-12 11:25:51.212 length:125
208.67.222.222:53 -> 10.0.0.8:49003
2009-09-12 11:25:54.323 length:80
10.0.0.8:39209 -> 208.67.222.222:53
2009-09-12 11:25:54.426 length:75
10.0.0.8:47869 -> 208.67.222.222:53
2009-09-12 11:25:54.517 length:236
208.67.222.222:53 -> 10.0.0.8:39209
2009-09-12 11:25:54.621 length:91
208.67.222.222:53 -> 10.0.0.8:47869

Related

Catch the IpAddress from ping host c#

I want to ask if it s possible to get the IpAddress from the ping host. So if someone pings my Computer I know his IpAddress. My Code Looks like this :
while (true)
{
Socket icmpListener = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp);
icmpListener.Bind(new IPEndPoint(IPAddress.Parse("564.89.556.5"), 0));
icmpListener.IOControl(IOControlCode.ReceiveAll, new byte[] { 1, 0, 0, 0 }, new byte[] { 1, 0, 0, 0 });
byte[] buffer = new byte[4096];
EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
int bytesRead = icmpListener.ReceiveFrom(buffer, ref remoteEndPoint);
string text = "ICMPListener received " + bytesRead + " from " + remoteEndPoint;
Console.WriteLine(text);
}
After the Code Ran and someone pings me i know wich ip was pingd put not the one from the host of the ping. Thanks for the awnsers.
Try:
var ip = icmpListener.RemoteEndPoint;
If you are using a connection-oriented protocol, the RemoteEndPoint property gets the EndPoint that contains the remote IP address and port number to which the Socket is connected. If you are using a connectionless protocol, RemoteEndPoint contains the default remote IP address and port number with which the Socket will communicate. You must cast this EndPoint to an IPEndPoint before retrieving any information. You can then call the IPEndPoint.Address method to retrieve the remote IPAddress, and the IPEndPoint.Port method to retrieve the remote port number.
When using cmd to ping a machine (ping 127.0.0.1), you are pinging that maching with the default port of 80
Socket icmpListener = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp);
icmpListener.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 80));
icmpListener.IOControl(IOControlCode.ReceiveAll, new byte[] { 1, 0, 0, 0 }, new byte[] { 1, 0, 0, 0 });
while (true)
{
byte[] buffer = new byte[4096];
EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
int bytesRead = icmpListener.ReceiveFrom(buffer, ref remoteEndPoint);
Console.WriteLine("ICMPListener received " + bytesRead + " from " + remoteEndPoint);
}
Before you do anything, Open CMD as Administrator then type the following command: netsh advfirewall firewall add rule name="All ICMP v4" dir=in action=allow protocol=icmpv4:any,any This will allow the firewall rule to allow ICMP Port Unreachable packets to be received.
And Don't Forget To Run the C# program as Administrator

Sending UDP Broadcast for populating USR-TCP232 LAN Modules information

I am using USR-TCP232 LAN Modules for an embedded project.
I have a tool to query those modules made by the manufacturer, it works great.
But, I want it in my code in C#. So, I decided to make one for myself. I believe I am so close but I guess a small glitch which gives me hard times and I need somebody to put some shed light on.
I can send a UDP broadcast and I can observe the traffic via "WireShark".
It is quite similar with the original tool. But, I can't receive the answered data sent by the devices on the network in my code.
Console application in C#
using System;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading;
namespace UDPer
{
class Program
{
static void Main(string[] args)
{
UDPer udp = new UDPer();
udp.Starter();
ConsoleKeyInfo cki;
do
{
if (Console.KeyAvailable)
{
cki = Console.ReadKey(true);
switch (cki.KeyChar)
{
case 's':
udp.Send("0123456789012345678901234567890123456789");
break;
case 'x':
udp.Stop();
return;
}
}
Thread.Sleep(10);
} while (true);
}
}
class UDPer
{
private Socket udpSock;
private byte[] buffer;
public void Starter()
{
//Setup the socket and message buffer
udpSock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
udpSock.Bind(new IPEndPoint(IPAddress.Any, 0));
udpSock.EnableBroadcast = true;
buffer = new byte[1024];
udpSock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
//udpSock.ExclusiveAddressUse = false; // only if you want to send/receive on same machine.
//The socket must not be bound or connected.
//Start listening for a new message.
EndPoint newClientEP = new IPEndPoint(IPAddress.Any, 0);
udpSock.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref newClientEP, DoReceiveFrom, udpSock);
}
public void Stop()
{
try
{
udpSock.Close();
Console.WriteLine("Stopped listening");
}
catch { /* don't care */ }
}
private void DoReceiveFrom(IAsyncResult iar)
{
try
{
//Get the received message.
Socket recvSock = (Socket)iar.AsyncState;
recvSock.EnableBroadcast = true;
EndPoint clientEP = new IPEndPoint(IPAddress.Any, 0);
int msgLen = recvSock.EndReceiveFrom(iar, ref clientEP);
byte[] localMsg = new byte[msgLen];
Array.Copy(buffer, localMsg, msgLen);
//Start listening for a new message.
EndPoint newClientEP = new IPEndPoint(IPAddress.Any, 0);
udpSock.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref newClientEP, DoReceiveFrom, udpSock);
//Handle the received message
Console.WriteLine("Recieved {0} bytes from {1}:{2}",
msgLen,
((IPEndPoint)clientEP).Address,
((IPEndPoint)clientEP).Port);
//Do other, more interesting, things with the received message.
string message = Encoding.ASCII.GetString(localMsg);
Console.WriteLine("Message: {0} ", message);
}
catch (ObjectDisposedException)
{
//expected termination exception on a closed socket.
}
}
public void Send(string message)
{
UdpClient udp = new UdpClient(1500);
var ipEndPoint = new IPEndPoint(IPAddress.Broadcast, 1500);
byte[] data = Encoding.ASCII.GetBytes(message);
udp.Send(data, data.Length, ipEndPoint);
udp.Close();
}
}
}
Wireshark capture
Note that: This Wireshark capture is exactly the same as the original tool does.
Some definitions:
My PC where C# application resides: 192.168.65.82
LAN Module IP Address: 192.168.65.8
Ports must be 1500 which is all OK.
Send payload for querying LAN Modules;
"0123456789012345678901234567890123456789"
So, I have tried tons of different options one by one but no jo so far.
What am I missing here?
A socket always has a dedicated port. Passing an IPEndPoint with port number 0 doesn't mean that you receive packets send to any port. Instead you are binding to a port assigned by the underlying service provider.
udpSock.Bind(new IPEndPoint(IPAddress.Any, 0));
If you do not care which local port is used, you can create an IPEndPoint using 0 for the port number. In this case, the service provider will assign an available port number between 1024 and 5000
https://msdn.microsoft.com/en-us/library/system.net.sockets.socket.bind(v=vs.110).aspx
You need to use
udpSock.Bind(new IPEndPoint(IPAddress.Any, 1500));

Tcp Socket server in C#

I have found this piece of code on the internet: it does not open a server listening on port 11000, as I hoped.
What can be the problem? I normally code in Delphi, so I am little lost. I have made a corresponding client in Delphi, which works.
I am using demo version of C# 2015.
public static void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and
// listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
// Start listening for connections.
while (true)
{
//Console.WriteLine("Waiting for a connection...");
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
data = null;
// An incoming connection needs to be processed.
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf("#") > -1)
{
break;
}
}
// Show the data on the console.
//Console.WriteLine("Text received : {0}", data);
// Echo the data back to the client.
byte[] msg = Encoding.ASCII.GetBytes(data);
handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
//Console.WriteLine("\nPress ENTER to continue...");
//Console.Read();
}
The problem might be here: Whats the IP address of ipHostInfo.AddressList[0] ? It might be the loop-back. I never restrict my server endpoint to an ip-adress unless I need to, but then I will specify it in a configfile.
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 11000);
As per Jeroen's answer, encountered per .NET's Synchronous Server Socket Example. When listening/connecting to localhost, one should rather use
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
instead of
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
Thanks for feedback. I found som other, older code:
TcpListener serverSocket = new TcpListener(11000);
that does the job. I know it is depreciated, but it works, actually.

Can't connect to TCP port on Android

I have an Android app (really Xamarin app) and I'm using Socket to listen on port 8888 on the Android app.
So, I want to connect to this port from another computer by tcp (from PC TO Android).
And, I receive the following error:
No connection could be made because the target machine actively refused it.
error 10061
My code (I got it from MS examples) works for two console apps. But if Android is server it doesn't work.
I try ping phone from pc, and it is OK.
My question: maybe should open a port? Or something else? How can I do this?
I will gladly to listen any ideas. Thanks.
My server code. C#, Xamarin.
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using Android.Runtime;
using Java.Lang;
using Byte = System.Byte;
using Exception = System.Exception;
using String = System.String;
using StringBuilder = System.Text.StringBuilder;
// State object for reading client data asynchronously
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 1024;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}
public class AsynchronousSocketListener
{
// Thread signal.
public static ManualResetEvent allDone = new ManualResetEvent(false);
public AsynchronousSocketListener()
{
}
public static void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
IPAddress ipAddress = new IPAddress(new byte[] { 127, 0, 0, 1 });
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 8888);
// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and listen for incoming connections.
try
{
listener.Bind(remoteEP);
listener.Listen(100);
while (true)
{
// Set the event to nonsignaled state.
allDone.Reset();
// Start an asynchronous socket to listen for connections.
Console.WriteLine("Waiting for a connection...");
listener.BeginAccept(
new AsyncCallback(AcceptCallback),
listener);
// Wait until a connection is made before continuing.
allDone.WaitOne();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
public static void AcceptCallback(IAsyncResult ar)
{
// Signal the main thread to continue.
allDone.Set();
// Get the socket that handles the client request.
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
// Create the state object.
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
public static void ReadCallback(IAsyncResult ar)
{
String content = String.Empty;
// Retrieve the state object and the handler socket
// from the asynchronous state object.
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
// Read data from the client socket.
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
// There might be more data, so store the data received so far.
state.sb.Append(Encoding.ASCII.GetString(
state.buffer, 0, bytesRead));
// Check for end-of-file tag. If it is not there, read
// more data.
content = state.sb.ToString();
if (content.IndexOf("<EOF>") > -1)
{
// All the data has been read from the
// client. Display it on the console.
Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",
content.Length, content);
// Echo the data back to the client.
Send(handler, content);
}
else
{
// Not all data received. Get more.
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
}
}
private static void Send(Socket handler, String data)
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data);
// Begin sending the data to the remote device.
handler.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), handler);
}
private static void SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket handler = (Socket)ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = handler.EndSend(ar);
Console.WriteLine("Sent {0} bytes to client.", bytesSent);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
My client code. Just simple C# console app:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class SynchronousSocketClient
{
public static void StartClient() {
// Data buffer for incoming data.
byte[] bytes = new byte[1024];
Console.WriteLine("Start!");
// 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[] { 10, 0, 1, 173 });
// IPAddress ipAddress = new IPAddress(new byte[] { 127, 0, 0, 1 });
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 8888);
// Create a TCP/IP socket.
Socket sender = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp );
// Connect the socket to the remote endpoint. Catch any errors.
try {
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.ErrorCode);
Console.WriteLine("SocketException : {0}",se.SocketErrorCode);
Console.WriteLine("SocketException : {0}",se.ToString());
} catch (Exception e) {
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
} catch (Exception e) {
Console.WriteLine( e.ToString());
}
}
}
There are two separate scenarios for socket-based data transport (in a typical local lan setting where there is an ordinary isp router in place):
Any client app (including browser) that connects to a well-known server endpoint (specific ip address and port) and just connects to establish a tcp session, and never listens. This is no problem. The router allows allows outgoing connection attempts.
Any client app that wants to connect to another client app that is listening. This is more difficult in that the router in a local lan setting does not typically allow any incoming connection attempts to a local host. Further the router is probably doing NAT translation so it has an addressable internet-facing ip address and has configured a specific external port to route to a specific internal host machine that is presumably listening at a local address and port.
There are several ways to determine what this endpoint addressing mapping configuration is but none of them are very convenient. The key point is that the router will only open an internal host to communications from the external internet if that host has previously tried to tcp connect to that external host (whether it be a server or a peer client app). This works for the browser/website server configuration because the client is always doing the connecting so the router opens the communication channel for that specific addressed external server and allows incoming data to be received by the client (browser). It is a similar situation for udp data transport. The router will only open the internal host to external incoming udp data if the internal client has recently sent a message to that specific peer. Http (a Tcp variant) provides the client/server protocol that uses this router convention for browser/website connectivity and communications. But for the peer client that wants to act as both a client and a server, there are significant barriers. Of course local lan socket communications are no problem, as local ip addresses are available for any internal lan peer.

Get sender ip from multicast packet

How do you get the IP of the sender of a Multicast UDP packet? The current code is setup in a synchronous/blocking manner (see note below). Here is the code:
private void receive()
{
string mcastGroup = SetMcastGroup();
s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
s.EnableBroadcast = true;
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 5000);
s.Bind(ipep);
IPAddress ip = IPAddress.Parse(mcastGroup);
s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip, IPAddress.Any));
while (true)
{
try
{
byte[] b = new byte[4096];
s.Receive(b);
string str = Encoding.ASCII.GetString(b, 0, b.Length);
//this.SetText(ipep.Address + ": " + str.Trim());
this.SetText(senderIP() + ": " + str.Trim());
}
catch{}
}
}
Note: This question comes from chat, as such is not my code. I am only asking because I understand the problem.
Since you are using UDP you don't establish a connection with the remote endpoint (unlike TCP where you would have one socket per connection). Therefore you must get the address of the remote endpoint when you receive the datagram. To do this call receiveFrom instead of receive()
http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.receivefrom.aspx

Categories