傳送端:
#include
#include
#include
#include
#include
#include
#define portnum 5000
#define groupip "224.0.1.1"
int main()
/* build address */
memset((void*)&addr, 0, sizeof(addr));
addr.sin_family = af_inet;
addr.sin_addr.s_addr = inet_addr(groupip); /* multicast group ip */
addr.sin_port = htons(portnum);
len = sizeof(addr);
while (1)
printf("send to %s:%u\n",
inet_ntoa(addr.sin_addr.s_addr), ntohs(addr.sin_port));
sleep(2); /* wait 2 sec. */
}close(sock_id);
return 0;}
接收端
#include
#include
#include
#include
#include
#include
#define portnum 5000
#define groupip "224.0.1.1"
#define buflen 1024
#define testnum 10
int main()
memset((void*)&addr, 0, sizeof(addr));
addr.sin_family = af_inet;
addr.sin_addr.s_addr = htonl(inaddr_any);
addr.sin_port = htons(portnum);
if (bind(sock_id, (struct sockaddr *)&addr, sizeof(addr)) < 0)
/* step 2: fill in a struct ip_mreq */
memset((void*)&ipmr, 0, sizeof(ipmr));
ipmr.imr_multiaddr.s_addr = inet_addr(groupip); /* multicast group ip */
ipmr.imr_inte***ce.s_addr = htonl(inaddr_any);
/* step 3: call setsockopt with ip_add_membership to support receiving multicast */
if (setsockopt(sock_id, ipproto_ip, ip_add_membership, &ipmr, sizeof(ipmr)) < 0)
/* step 4: call recvfrom to receive multicast packets */
len = sizeof(sender);
count = 0;
while (count < testnum)
printf("%d. receive from %s:%u\n", count,
inet_ntoa(sender.sin_addr.s_addr), ntohs(sender.sin_port));
printf("\tpacket data: %s\n", buf);
}/* step 5: call setsockopt with ip_drop_membership to drop from multicast */
if (setsockopt(sock_id, ipproto_ip, ip_drop_membership, &ipmr, sizeof(ipmr)) < 0)
/* step 6: close the socket */
close(sock_id);
return 0;}
加入乙個組播組
網路中的一台主機如果希望能夠接收到來自網路中其它主機發往某乙個組播組的資料報,那麼這麼主機必須先加入該組播組,然後就可以從組位址接收資料報。在廣域網中,還涉及到路由器支援組播路由等,但本文希望以乙個最為簡單的例子解釋清楚協議棧關於組播的乙個最為簡單明瞭的工作過程,甚至,我們不希望涉及到igmp包。我...
加入乙個多播組 最簡單的情況
應用程式通過命令字ip add membership把乙個socket加入到乙個多播組,ip add membership是乙個ip層的命令字,其呼叫使用的引數是結構體struct ip mreq,其定義如下 struct ip mreq 該結構體的兩個成員分別用於指定所加入的多播組的組ip位址,和...
linux下組播的實現
目前有三種通訊方式 單播 unicast 廣播 broadcast 組播 multicast 單播解決了點對點通訊的需求 廣播是點對多點的通訊,其存在兩個缺點 1 只能在同一網段內實現廣播 2 不能指定目的主機,所有網段內的主機都將收到廣播報文,存在頻寬浪費。組播組可以是永久的也可以是臨時的。組播組...