Unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
NMUDP, StdCtrls ,WINSOCK;
type
TForm1 = class(TForm)
Button1: TButton;
Memo1: TMemo;
u1: TNMUDP;
procedure u1DataReceived(Sender: TComponent; NumberBytes: Integer;
FromIP: String; Port: Integer);
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
type
tAddr=array[1..4] of byte;
tsin=TSOCKADDRin;
var
Form1: TForm1;
gs,gr:tsocket;
gsin:tsin;
gtd,gtd_recv:taddr;
gi:integer;
implementation
{$R *.DFM}
function get_socket(var s:tsocket;sock_type:integer):integer;
var
af,typ,procol:integer;
wsdata:twsadata;
wver:word;
res:integer;
buf:array[1..10] of byte;
l,i:integer;
begin
af:=PF_INET;
TYP:=sock_type;
PROCOL:=0;
wver:=makeword(1,1);
res:=wsastartup(wver,wsdata);
s:=socket(af,typ,procol);
get_socket:=res;
fillchar(buf,sizeof(buf),0);
buf[1]:=1;
buf[2]:=1;
l:=sizeof(buf);
buf[1]:=1;l:=sizeof(buf);
res:=setsockopt(GR,sol_socket,SO_BROADCAST,
pchar(@buf),l);
end;
function bind_socket(var s:tsocket;var sin:tsockaddrin):integer;
var
i,res:integer;
alport:integer;
begin
alport:=IPPORT_RESERVED;
alport:=1234;
for i:=1 to IPPORT_RESERVED div 2 do
begin
sin.sin_port:=htons(alport);
RES:=BIND(S,SIN,SIZEOF(SIN));
if res=0 then break;
alport:=alport-1;
end;
gi:=alport;
if res<>0 then res:=wsagetlasterror;
bind_socket:=res;
end;
function get_host_addr(var sin:TSOCKADDRin;var td:taddr):integer;
var
i,alport:integer;
st:string;
hp
hostent;
server:array[1..80] of char;
begin
fillchar(td,sizeof(td),0);
i:=sizeof(server);
gethostname(@server,i);
hp:=gethostbyname(@server);
move(hp^.h_addr_list^,sin.sin_addr.s_addr,hp^.h_length);
SIN.SA_FAMILY:=hp^.h_addrtype;
alport:=IPPORT_RESERVED;
sin.sin_port:=htons(alport);
sin.sin_addr.s_un_b.s_b1:=hp^.h_addr_list^[0];
sin.sin_addr.s_un_b.s_b2:=hp^.h_addr_list^[1];
sin.sin_addr.s_un_b.s_b3:=hp^.h_addr_list^[2];
sin.sin_addr.s_un_b.s_b4:=hp^.h_addr_list^[3];
move(hp^.h_addr_list^[0],td[1],4);
end;
procedure TForm1.u1DataReceived(Sender: TComponent; NumberBytes: Integer;
FromIP: String; Port: Integer);
var
st:string;
l:longint;
begin
setlength(st,NumberBytes);
l:=NumberBytes;
u1.ReadBuffer(st[1],l);
memo1.Lines.Add(FromIP + ':' + inttostr(Port) + #$0d#$0a +st );
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
get_Socket(gr,SOCK_DGRAM);
get_host_addr(Gsin,Gtd);
bind_socket(gr,Gsin);
end;
procedure TForm1.Button1Click(Sender: TObject);
var
st :string;
res:integer;
begin
st:='hello';
Gsin.sin_port:=htons(5000);
res:=sendto(gr,st[1],length(st),0,Gsin,sizeof(Gsin));
end;
end.