关于广播(100分)

  • 主题发起人 主题发起人 jingtao
  • 开始时间 开始时间
J

jingtao

Unregistered / Unconfirmed
GUEST, unregistred user!
unit UdpBroadStr;

interface
uses
Windows,WinSock;
function MyUdpBroadStr(Port:integer;Str:String):Boolean;
implementation
function MyUdpBroadStr(Port:integer;Str:String):Boolean;
var WSData:TWSAData;
UdpSock:TSocket;
UdpSockAddr:TSockAddr;
i:integer;
BroadCast:Boolean;
Buf:Array[1..1024] of Char;
begin
Result:=False;
// if WSAStartup($101,{MakeWord(2,2),}WSData)<>0 then Exit; //初始化Wsock32.dll
UdpSock:=Socket(AF_INET,SOCK_DGRAM,0); //初始化socket
if UdpSock = SOCKET_ERROR then Exit;
BroadCast:=True;
if setsockopt(UdpSock,SOL_SOCKET,SO_BROADCAST, @BroadCast,sizeof(BroadCast))=SOCKET_ERROR then Exit;
//绑定要发送的Udp包的socketaddr_in结构
ZeroMemory(@UdpSockAddr,sizeof(sockaddr_in));
UdpSockAddr.sin_family:=AF_INET;
UdpSockAddr.sin_port:=htons(Port);
UdpSockAddr.sin_addr.S_addr:=INADDR_BROADCAST;
for i:=1 to Length(Str) do Buf:=Str;
Sendto(UdpSock,Buf,Length(Str),0,UdpSockAddr,sizeof(UdpSockAddr));//向网络广播Udp包
if UdpSock<>NULL then CloseSocket(UdpSock);
// WSACleanUp;
Result:=True;
end;
var
Re:integer;
Initialization
Re:=WSAStartup($101,Wsa); //初始化Wsock32.dll,MakeWord(2,2),
if Re<>0 then MessageBox(0,'WSAStartup Failed',MpgServerName,MB_ICONERROR);
finalization
WSACleanup;
end.


其中
if setsockopt(UdpSock,SOL_SOCKET,SO_BROADCAST, @BroadCast,sizeof(BroadCast))=SOCKET_ERROR then Exit;

在WIN2K下无问题
9X就出错.
WHY?
 
是以前写的一个程序
以前直接根据网段指定毕比如说192.168.0.255就没有问题
近来无事修改了一下,结果就...
http://tty.yyun.net/lovejingtao/htm/netplay.zip
 
已经解决问题
 
if setsockopt(UdpSock,SOL_SOCKET,SO_BROADCAST, @BroadCast,sizeof(BroadCast))=SOCKET_ERROR then Exit;

BroadCast是不是应该为Integer,不是Boolean[?]
 
BroadCast应该是Integer,值取1

procedure Tfrmmain.FormCreate(Sender: TObject);
var
TempWSAData: TWSAData;
optval: integer;
begin
// 初始化SOCKET
if WSAStartup($101, TempWSAData)=1 then
showmessage('StartUp Error!');

s := Socket(AF_INET, SOCK_DGRAM, 0);
if (s = INVALID_SOCKET) then //Socket创建失败
begin
showmessage(inttostr(WSAGetLastError())+' Socket创建失败');
CloseSocket(s);
//exit;
end;
//发送方SockAddr绑定
addr.sin_family := AF_INET;
addr.sin_addr.S_addr := INADDR_ANY;
addr.sin_port := htons(UDPPORT);
if Bind(s, addr, sizeof(addr)) <> 0 then
begin
showmessage('bind fail');
end;

optval:= 1;
if setsockopt(s,SOL_SOCKET,SO_BROADCAST,pchar(@optval),sizeof(optval)) = SOCKET_ERROR then
begin
showmessage('无法进行UDP广播');
end;

{mreq.imr_multiaddr.S_addr := INADDR_ALLHOSTS_GROUP;
mreq.imr_interface.S_addr := INADDR_ANY;
if setsockopt(s,IPPROTO_IP,IP_ADD_MEMBERSHIP,pchar(@mreq),sizeof(mreq)) = SOCKET_ERROR then
begin
showmessage('无法进行UDP组播');
end;}


WSAAsyncSelect(s, frmmain.Handle , WM_SOCK, FD_READ);
//接收端SockAddrIn设定
FSockAddrIn.SIn_Family := AF_INET;
FSockAddrIn.SIn_Port := htons(UDPPORT);

label3.Caption := '端口:'+inttostr(UDPPORT);
end;
 
取integer或者bool都可以的
 
啊?我不会。
 
同样的问题,求解!!!
 
后退
顶部