Reputation: 112
This isn't a problem as much as it is a curiosity. I created a simple send/receive C# application using UDP, mostly following the MSDN examples on UdpClient. I have a textbox acting as a log for when things are sent or received; it prints the timestamp and what was sent/received from where.
The curiosity comes in with the port numbers. When the program is listening on some port and it receives a packet, the port on the packet received doesn't match up with the port it was listening on.
For example, here's a screenshot of the application (note: this still happens even if using different computers to send/receive):
It's receiving the packets just fine, which is why this isn't really a "problem" because it is working. I'm just curious why the port on the received packets is showing different than the port it is listening on. I'm wondering if perhaps it's just garbage data?
Here's the code that runs when data is received (using the AsyncCallback that I picked up from MSDN):
private void ReceiveCallback(IAsyncResult ar)
{
try {
// Pull the socket from the AsyncResult parameter
UdpState state = (UdpState)(ar.AsyncState);
UdpClient udp = state.udp;
IPEndPoint end = state.endpoint;
// Grab and convert the message into a string
byte[] recvBytes = udp.EndReceive(ar, ref end);
string recvString = Encoding.ASCII.GetString(recvBytes);
/* Here's where it's logging the IPEndPoint onto the console.
* Is the port meaningless when receiving a packet, and that's why it's
* always something random? Or is there some meaning to it that I'm
* unaware of? */
ConsoleLog(end.ToString() + " Recv: " + recvString);
// Start the listen cycle again so this will be called again
listener.BeginReceive(new AsyncCallback(ReceiveCallback), state);
} catch (ObjectDisposedException) {
// Do nothing - Expected error when the UDP Listener is closed.
}
}
Is the port number when receiving packets just meaningless garbage data, or does it have some sort of use?
Upvotes: 1
Views: 1816
Reputation: 2399
Every UDP packet has a source and destination ip address and port, what you are seeing is the source port address.
A well known port is used to send data to, the machine sending data assigns a free port to the source port of the packet so that it can receive data from the server on that port.
Upvotes: 2
Reputation: 21548
There's a port number at each end of the connection: the published port number that your process is listening on, and the originating (client) port number (which could be on a different machine).
Upvotes: 1