UDP (datagram) socket usage.
Alex Tweedly
alex at tweedly.net
Sun Dec 26 19:13:33 EST 2004
I'm having a little bit of trouble with using UDP (datagram) sockets,
and hope someone can tell me either what I'm missing, or an alternative
way to do what I want.
When I started using Rev, I ported over some of my very basic networking
scripts, and thought I had got enough of them working to know what I was
doing. Turns out there was one piece I missed, and I can't figure out
how to do it in Rev.
I did both server and client for TCP, and the "peer-to-peer style UDP",
and I did the UDP server-side - but I never got around to doing the UDP
client-side part of it (because for that I just used the program I
already had set up and running on another machine that didn't have Rev
on it).
What I've always done for "client-server" style UDP is used a pair of
adjacent port numbers - one for client->server, the other for
server->client. I think you can often get away with just one - but
using the pair means you can do much of your testing on a single machine.
Server pseudo-code:
> accept datagram connections on port "4567" with message "gotPacket"
> on gotPacket pRemote, pData
> put pRemote into pRemote
> set the itemDel to ":"
> add 1 to item 2 of pRemote
> open datagram socket to pRemote
> write "reply with " & param(2) to socket pRemote
> close socket pRemote
> end gotPacket
Now the echo client version, using standard system calls, is simply
> s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
> r = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
>
> s.connect( (HOST,PORT) )
>
> # get the source port allocated, and listen on adjacent one
> reply_host, reply_port = s.getsockname()
> reply_port += 1
> r.bind( (reply_host, reply_port) )
>
> while 1 :
> str = raw_input('type it')
> s.send(str)
> data = r.recv(1024)
> print "Back came ", data
>
> s.close()
Most of this translates simply into Rev - except I can't find the
equivalent of getsockname(), which tells me the local IP address and
port number which will be filled in as source addr, source port in the
UDP packet. The server uses this to determine where to send its reply;
source addr is, of course, just the IP address of the client machine
(which I can get from hostAddress() once I have connected the socket) -
but I don't see a way to find which source port will be chosen. Without
that, I don't know which port to bind to in order to receive the server
responses.
Is there a way to find that ?
Or, alternatively, is there a different way to set up a client-server
UDP pair ? i.e. have a pre-defined port number used on the server,
which is also configured in every client, but allocate the client ports
dynamically.
Thanks
-- Alex.
--
No virus found in this outgoing message.
Checked by AVG Anti-Virus.
Version: 7.0.298 / Virus Database: 265.6.4 - Release Date: 22/12/2004
More information about the use-livecode
mailing list