[fpc-pascal]Send String via UDP
tom_at_work at yline.com
Tue Jul 10 13:32:28 CEST 2001
Subject: [fpc-pascal]Send String via UDP
> I want to send a simple String via the UDP-Protocol to an unknown number
> of computers on our intranet.
> I've tried some things, but had no success in working with the
> Is there anyone who can give me an example on how do do it?
Here's a small example program. Since you didn't tell for what OS you want
your program, it is a Win32 one. For Unix / OS/2 / * you've to search the
RTL / packages / whatever for the units to be used for the different calls
and remove all WSA* stuff. Note that I didn't use the winsock unit supplied
with the RTL but the winsock 2 header translation from Alexander S. from the
contribs page since the RTL ones aren't fully compatible to the Delphi ones.
Though it might work with it too.
Int32 = Longint;
UInt32 = DWord;
MYPORT = 9034;
sock : TSocket;
send_addr : TSockAddrIn;
hostentry : PHostEnt;
numbytes : Int32;
hostname : String;
sendstring : String;
wsadata : TWSAData;
if (paramcount < 2) then begin
Writeln('Usage : ' + paramstr(0) + ' hostname message');
// initialize winsock
if (WSAStartup($0202, wsadata) <> 0) then begin
Writeln('Couldn''t initialize Winsock 2');
// resolve host
hostname := paramstr(1);
hostentry := getHostByName(PChar(hostname));
if (hostentry = nil) then begin
Writeln('Couldn''t resolve host');
// get socket
sock := socket(AF_INET, SOCK_DGRAM, 0);
if (sock = INVALID_SOCKET) then begin
Writeln('Couldn''t retrieve socket');
// fill in target address
with send_addr do begin
sin_family := AF_INET;
sin_port := htons(MYPORT);
// neat typecast from PChar to UInt32 :-)
sin_addr.s_addr := UInt32((@hostentry^.h_addr^)^);
// send data
sendstring := paramstr(2);
numbytes := sendTo(sock, sendstring, length(sendstring), 0, send_addr,
if (numbytes = SOCKET_ERROR) then begin
Writeln('Error sending string');
end else begin
Writeln('Sent ', numbytes, ' bytes to ', inet_ntoa(send_addr.sin_addr),
// clean up
// shut down winsock
> How can I reach all computers (of course with a running
> Client-Application) on the net?
> It is said I have to use 255.255.255.255 as the receiver-adress?!
With this address you reach all computers on the 'net regardless of them
having installed your client application or not afair. Guess you won't make
much friends when doing that =I
> Any hints?
Hope this helps.
More information about the fpc-pascal