廣播(broadcast)是指封包在計算機網路中傳輸時,目的位址為網路中所有裝置的一種傳輸方式。實際上,這裡所說的「所有裝置」也是限定在乙個範圍之中,稱為「廣播域」
接收端傳送端
int yes=1;
setsockopt(sock,sol_socket,so_broadcast,&yes,sizeof(yes));
#include#include#include#include#include#include#include#includeint main(int argc,char *ar**)
//create socket
int sock=socket(af_inet,sock_dgram,0);
if(sock<0)
else
//setsockopt
int yes=1;
setsockopt(sock,sol_socket,so_broadcast,&yes,sizeof(yes));
//set sendto who
struct sockaddr_in s_addr;
s_addr.sin_family=af_inet;
s_addr.sin_port=htons(atoi(ar**[2]));
s_addr.sin_addr.s_addr=inet_addr(ar**[1]);
int addr_len=sizeof(s_addr);
char buf[128];
strcpy(buf,"i am a broadcast package\n");
//sendto
int len=sendto(sock,buf,strlen(buf),0,(struct sockaddr*)&s_addr,addr_len);
if(len>0)
else
close(sock);
return 0;
}
廣播會去尋找區域網內的主機,如果找到主機就使用dhcp協議給這個主機分配乙個ip位址。但是如果廣播被占領了,dhcp就識別不到主機了,因此也就不能分配ip位址了#include#include#include#include#include#include#include#includeint main(int argc,char *ar**)
//create socket
int sock=socket(af_inet,sock_dgram,0);
if(sock<0)
else
struct sockaddr_in local;
local.sin_family=af_inet;
local.sin_port=htons(atoi(ar**[1]));
local.sin_addr.s_addr=inaddr_any;
//bind address
if(bind(sock,(struct sockaddr*)&local,sizeof(local))<0)
else
struct sockaddr_in peer;
char buf[128];
int len;
socklen_t addr_len=sizeof(peer);
while(1)//recvfrom message
else
}close(sock);
return 0;
}
Linux UNIX網路程式設計筆記(四) UDP程式設計
udp客戶 伺服器的套接字函式 recvfrom 函式 接收資料,類似標準read include include ssize t recvfrom int sockfd,void buf,size t len,int flags,struct sockaddr from,size t addrle...
linux網路程式設計 廣播
recv include include include include include include include see notes include include include include define myport 5009 define myaddr 192.168.1.34 v...
linux網路程式設計 udp
udp udp收發 udp 協議不需要建立連線,類似於傳送簡訊,因此 udp 的程式設計方式比 tcp 更加簡單。udp 有其自己特有的接受與傳送資料的函式 socket af inet,sock dgram,0 建立socket bind socket fd,struct sockaddr ser...