Linux系統下UDP傳送和接收廣播訊息小例子

2021-06-18 11:36:17 字數 2499 閱讀 4974

分類: 網路通訊

2013-01-07 10:54

1336人閱讀收藏

舉報 [cpp]view plain

copy

print?

// 傳送端

#include 

#include 

#include 

#include 

#include 

#include 

#include 

#include 

#include 

using

namespace std;  

int main()  

const

int opt = 1;  

//設定該套接字為廣播型別,

int nb = 0;  

nb = setsockopt(sock, sol_socket, so_broadcast, (char *)&opt, sizeof(opt));  

if(nb == -1)  

struct sockaddr_in addrto;  

bzero(&addrto, sizeof(struct sockaddr_in));  

addrto.sin_family=af_inet;  

addrto.sin_addr.s_addr=htonl(inaddr_broadcast);  

addrto.sin_port=htons(6000);  

int nlen=sizeof(addrto);  

while(1)  

;  int ret=sendto(sock, smsg, strlen(smsg), 0, (sockaddr*)&addrto, nlen);  

if(ret<0)  

else

}  return 0;  

}  

// 傳送端

#include #include #include #include #include #include #include #include #include using namespace std;

int main()

const

int opt = 1;  

//設定該套接字為廣播型別,

int nb = 0;  

nb = setsockopt(sock, sol_socket, so_broadcast, (char *)&opt, sizeof(opt));  

if(nb == -1)  

if(bind(sock,(struct sockaddr *)&(addrto), sizeof(struct sockaddr_in)) == -1)   

int len = sizeof(sockaddr_in);  

char smsg[100] = ;  

while(1)  

else

sleep(1);  

}  return 0;  

}  

// 接收端

#include #include #include #include #include #include #include #include #include using namespace std;

int main()

{ setvbuf(stdout, null, _ionbf, 0);

fflush(stdout);

// 繫結位址

struct sockaddr_in addrto;

bzero(&addrto, sizeof(struct sockaddr_in));

addrto.sin_family = af_inet;

addrto.sin_addr.s_addr = htonl(inaddr_any);

addrto.sin_port = htons(6000);

// 廣播位址

struct sockaddr_in from;

bzero(&from, sizeof(struct sockaddr_in));

from.sin_family = af_inet;

from.sin_addr.s_addr = htonl(inaddr_any);

from.sin_port = htons(6000);

int sock = -1;

if ((sock = socket(af_inet, sock_dgram, 0)) == -1)

{

cout<<"socket error"<

自已在linux虛擬機器下測試可以成功, 前提是要把主機設定在同一網段內, 還有就是不要忘記關閉linux的防火牆.. 可以使用setup命令進行設定。

(我在測試的時候只能傳送不收接收,折磨了我半天,後來才想到是linux防火牆的問題。。)

關於虛擬機器的網絡卡配置,建議選擇橋接模式。nat的模式的話,是受限制的,可能會收不到廣播訊息。

祝你成功。。

Linux系統下UDP傳送和接收廣播訊息小例子

cpp view plain copy 傳送端 include include include include include include include include include using namespace std int main const int opt 1 設定該套接字為廣播...

C 接收和傳送UDP資料

除了點對點,通常udp資料的傳遞方式有兩種,一種是broadcast,一種是multicast。中文一般把它們翻譯作廣播和組播。前者是簡單的在區域網裡面廣播 後者是借助路由器將資料傳送到包括英特網在內的任何多個位址。在c 裡面,處理udp通訊最簡單的方法就是使用udpclient。具體使用方法我也不...

C 接收和傳送UDP資料

除了點對點,通常udp資料的傳遞方式有兩種,一種是broadcast,一種是multicast。中文一般把它們翻譯作廣播和組播。前者是簡單的在區域網裡面廣播 後者是借助路由器將資料傳送到包括英特網在內的任何多個位址。在c 裡面,處理udp通訊最簡單的方法就是使用udpclient。具體使用方法我也不...