How to bind / connect multiple UDP sockets

My original UDP socket is bound to 127.0.0.1:9898.

The first time I get notification of incoming data using epoll / kqueue, I do recvfrom () and I populate a struct sockaddr called peer_name that contains peer information (ip: port).

Then I create a new UPD socket using socket (),

then I bind () this newly created socket to the same ip: port (127.0.0.1:9898) as my original socket.

then I will connect my newly created socket using connect () to the peer that just sent me something. I have information in a sockaddr structure called peer_name .

Then I add my new socket to my epoll / kqueue vector and wait for notification.

I would expect ONLY to receive a UDP frame from the peer to which I am connected "".

1 / does netstat -a -p udp Suppose to show me IP: Peer PORT, is my new socket connected to ""?

2 / I'm probably doing something wrong, because after creating my new socket this socket accepts all incoming UDP packets destined for IP: PORT I am bound to an independent source IP address: PORT.

I would like to see a working example of what I'm trying to do :) or any hint of what I'm doing wrong.

thanks!

+4
source share
2 answers

http://www.softlab.ntua.gr/facilities/documentation/unix/unix-socket-faq/unix-socket-faq-5.html

“Does the connect () call affect the behavior on the socket? Yes, in two ways. First, only datagrams are returned from your“ connected partner. ”All the others arriving at your port are not delivered to you.

But most importantly, a UDP socket must be connected to receive ICMP errors. Pp. 748-749 of "TCP / IP Illustrated, Volume 2" provides all the details on why this is so. "

+4
source

connect (2) in the UDP socket sets only the default destination address for the socket (where the data will be sent if you use write (2) or send (2) to the socket). This has no other effect: you can still send packets to other addresses using sendto (2) or sendmsg (2) , and you will still see packets sent from any address.

Thus, in fact, it makes no sense to open a new socket on the port - for each packet you receive, you need to look at the source address to see if it comes from the address that you already saw (and thus belongs to this logical stream) or a new address (new logical thread).

+1
source

Source: https://habr.com/ru/post/1311764/


All Articles