[fpc-pascal]Send String via UDP

Thomas Schatzl 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
> Socket-Unit.
> 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.

{$mode delphi}
uses
  winsock;

type
 Int32 = Longint;
 UInt32 = DWord;

const
  MYPORT = 9034;

var
  sock : TSocket;
  send_addr : TSockAddrIn;
  hostentry : PHostEnt;
  numbytes : Int32;
  hostname : String;
  sendstring : String;
  wsadata : TWSAData;

begin
  if (paramcount < 2) then begin
    Writeln('Usage : ' + paramstr(0) + ' hostname message');
    exit;
  end;
  // initialize winsock
  if (WSAStartup($0202, wsadata) <> 0) then begin
    Writeln('Couldn''t initialize Winsock 2');
    exit;
  end;
  // resolve host
  hostname := paramstr(1);
  hostentry := getHostByName(PChar(hostname));
  if (hostentry = nil) then begin
    Writeln('Couldn''t resolve host');
    exit;
  end;
  // get socket
  sock := socket(AF_INET, SOCK_DGRAM, 0);
  if (sock = INVALID_SOCKET) then begin
    Writeln('Couldn''t retrieve socket');
    exit;
  end;
  // 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^[0])^);
  end;
  // send data
  sendstring := paramstr(2);
  numbytes := sendTo(sock, sendstring, length(sendstring), 0, send_addr,
sizeof(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),
' successfully');
  end;
  // clean up
  closesocket(sock);
  // shut down winsock
  WSACleanup;
end.

>
> 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.

Regards,
  Thomas






More information about the fpc-pascal mailing list