- Home /
[Beginner] /C#/UDP/LocalHost/ receiving data the IPEndPoint.Port is different
When i send data to 127.0.0.1 port X (= server local port), the udp "listener" receive an IPEndPoint whith port Y(?). What i mean is: when i try to use Debug.Log(IPEndPoint.Port) on the received_IPEndPoint in unity editor there is the port Y and not the port X. What is y? Why i receive data even the port isnt the same?
Answer by dajohnso · Apr 12, 2021 at 08:09 PM
The Communications is 2 way. When you connect to a port on the server talks back on a different port. Not looking at any code that could be it. The X port is the listener port but local port will be something else (usually 10000+)
I dont understand what u mean. When i send data using another udpclient i use the method Send without connection, and in the IPEndPoint the port is the localPort of the listener. So why the IPEndPoint port chenge when the listener receive data if he take data from port X? Mybe i dont understand how udp really works. I mean if i set the listener on port X i can receive data only on this port? Thx
maybe i found the solution, the recevie method return the ip and port of the sender.
You may want to have a look at this SO question. Also if you are not familiar with the UDP protocol, have a look over here. The UDP header literally just contains those 4 fields which occupy exactly 64 bits. The packet includes your own source port, the destination port, the length of the packet and a checksum of the data. After that header your actual data follows. Of course an UDP packet is commonly wrapped in an IP packet. Though every packet has a local port from which you are sending the packet out, and a remote port which is the target port. When the other side receives the packet, they can use your source port as their destination for a reply message.
Also keep in $$anonymous$$d that since we usually all are located behind NAT routers, the router will actually temporarily open your own source port in order for the other side to get past the router and actually reach your PC. NAT routers may assign a different source port in order to differentiate multiple clients on the same network. That's the actual hack that NAT routers do. They "abuse" the port as a part of the address.