in reply to Sending AND Receiving on the Same Port

What I haven't found is anything on how to send AND receive on the same port.

It's impossible for a socket to do otherwise.

Maybe the bit you are missing is that you need to use the same socket for sending and receiving? Unlike (most?) pipes, sockets are bidirectional.

  • Comment on Re: Sending AND Receiving on the Same Port

Replies are listed 'Best First'.
Re^2: Sending AND Receiving on the Same Port
by HalNineThousand (Beadle) on Feb 24, 2011 at 01:29 UTC

    Okay, I get that. I've been playing around with it.

    Now there's only one other issue: My first message is a broadcast message, so I have the socket set to broadcast. It appears the issue is that I can't listen on the same socket I broadcast on.

    Am I right on this? If so, how do I sent out a broadcast message, then listen for a reply on the same port? Since it seems if I broadcast, I can't also listen, in the time it takes to make a new socket, won't data be incoming and lost?

      It appears the issue is that I can't listen on the same socket I broadcast on. Am I right on this?

      That makes no sense. Each message is completely independent in UDP. You can send to anyone and receive from anyone with a single socket.

      in the time it takes to make a new socket, won't data be incoming and lost?

      Why would someone be sending to a socket you haven't created yet?

        I can see how each message is separate, but when I create a socket to broadcast, I have to specify it's for broadcasting:

        $sender = IO::Socket::INET->new( PeerAddr => inet_ntoa(INADDR_BROADCAST), Broadcast => 1, PeerPort => '7071', Proto => 'udp' ) or die "cannot connect: $!\n";

        So once I do this, doesn't that change the nature of the socket? I don't see a method in IO::Socket::INET or IO::Socket that lets me change the Broadcast flag to 0 after I send a broadcast. I've been trying with sockopt(), but it won't set or change any values.

        Thank you for all the help on this!

        Once I studied your code and altered mine and got tests working, I found other issues with xinetd and UDP, so, in the long run, I had to send the "Where are you" message on one port, then the server had to reply on a different port. I tried using the same port for the server, but I couldn't open a 2nd socket there using the same port.

        While the solution didn't come directly from what you showed me, your code helped me fix what I had wrong there and let to me finding the root issue.

        Thanks!