關於雙網絡卡繫結socket接收組播的問題
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>
#include <errno.h>
#define BUFLEN 1000
int
main (
int
argc,
char
**argv)
{
struct
sockaddr_in peeraddr,ia;
int
sockfd;
char
recmsg[BUFLEN + 1];
unsigned
int
socklen, n;
struct
ip_mreq mreq;
/* 建立 socket 用於UDP通訊 */
sockfd = socket (AF_INET, SOCK_DGRAM, 0);
if
(sockfd < 0)
{
printf
(
"socket creating err in udptalk\n"
);
exit
(1);
}
/* 設定要加入組播的地址 */
bzero(&mreq,
sizeof
(
struct
ip_mreq));
inet_pton(AF_INET,
"226.1.1.1"
,&ia.sin_addr);
//組播地址
/* 設定組地址 */
bcopy (&ia.sin_addr.s_addr, &mreq.imr_multiaddr.s_addr,
sizeof
(
struct
in_addr));
/* 設定傳送和接收源主機的地址資訊 */
// mreq.imr_interface.s_addr = htonl (INADDR_ANY);
//這樣寫是否能繫結到對應的網絡卡上
mreq.imr_interface.s_addr = inet_addr(
"192.168.2.110"
);
/* 把本機加入組播地址,即本機網絡卡作為組播成員,只有加入組才能收到組播訊息 */
if
(setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq,
sizeof
(
struct
ip_mreq)) == -1)
{
perror
(
"setsockopt"
);
exit
(-1);
}
socklen =
sizeof
(
struct
sockaddr_in);
memset
(&peeraddr, 0, socklen);
peeraddr.sin_family = AF_INET;
peeraddr.sin_port = htons (9999);
//組播埠
inet_pton(AF_INET,
"226.1.1.1"
, &peeraddr.sin_addr);
//組播地址
int
opt = 1;
// sockfd為需要埠複用的套接字
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (
const
void
*)&opt,
sizeof
(opt));
/* 繫結自己的埠和IP資訊到socket上 */
if
(bind(sockfd, (
struct
sockaddr *) &peeraddr,
sizeof
(
struct
sockaddr_in)) == -1)
{
printf
(
"Bind error\n"
);
exit
(0);
}
/* 迴圈接收網路上來的組播訊息 */
for
(;;)
{ bzero (recmsg, BUFLEN + 1);
n = recvfrom (sockfd, recmsg, BUFLEN, 0, (
struct
sockaddr *) &peeraddr, &socklen);
if
(n < 0)
{
printf
(
"recvfrom err in udptalk!\n"
);
exit
(4);
}
else
{
/* 成功接收到資料報 */
recmsg[n] = 0;
fflush
(stdout);
printf
(
"peer:"
);
}
}
}