CAsyncSocket SetSockOpt IP_MULTICAST_LOOP 问题
想实现UDP组播,从网上下了个类,class CMulticastSocket : public CAsyncSocket
基本实现了发送和接受,可是遇见了问题:不能实现发送不让自己收到,无论nLoopBack 0 和1,设置返回都是1,为错误。
SetSockOpt(IP_MULTICAST_LOOP, &nLoopBack, sizeof(int), IPPROTO_IP)
具体代码如下:请大家分析分析::
CMulticastSocket::CMulticastSocket()
{
bForceNoLoopback = FALSE;
bDataReceived = TRUE; /* Variable defined for this project. Not necessarily part of CMulticastSocket */
}
CMulticastSocket::~CMulticastSocket()
{
}
// Do not edit the following lines, which are needed by ClassWizard.
#if 0
BEGIN_MESSAGE_MAP(CMulticastSocket, CAsyncSocket)
//{{AFX_MSG_MAP(CMulticastSocket)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
#endif // 0
/////////////////////////////////////////////////////////////////////////////
// CMulticastSocket member functions
BOOL CMulticastSocket::CreateReceivingSocket(LPCTSTR strGroupIP, UINT nGroupPort)
{
/* Create socket for receiving packets from multicast group */
if(!Create(nGroupPort, SOCK_DGRAM, FD_READ))
return FALSE;
BOOL bMultipleApps = TRUE; /* allow reuse of local port if needed */
SetSockOpt(SO_REUSEADDR, (void*)&bMultipleApps, sizeof(BOOL), SOL_SOCKET);
/* Fill m_saHostGroup_in for sending datagrams */
memset(&m_saHostGroup, 0, sizeof(m_saHostGroup));
m_saHostGroup.sin_family = AF_INET;
m_saHostGroup.sin_addr.s_addr = inet_addr(strGroupIP);
m_saHostGroup.sin_port = htons((USHORT)nGroupPort);
/* Join the multicast group */
m_mrMReq.imr_multiaddr.s_addr = inet_addr(strGroupIP); /* group addr */
m_mrMReq.imr_interface.s_addr = htons(INADDR_ANY); /* use default */
if(setsockopt(m_hSocket, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char FAR *)&m_mrMReq, sizeof(m_mrMReq)) < 0)
return FALSE;
return TRUE;
}
BOOL CMulticastSocket::CreateSendingSocket(UINT nTTL, BOOL bLoopBack)
{
if(!m_SendSocket.Create(0, SOCK_DGRAM, 0)) // Create an unconnected UDP socket
return FALSE;
if(!SetTTL(nTTL)) // Set Time to Live as specified by user
AfxMessageBox("Warning! Error Setting TTL");
SetLoopBack(bLoopBack); // Enable/Disable Loopback
return TRUE;
}
BOOL CMulticastSocket::SetTTL(UINT nTTL)
{
/* Set Time to Live to parameter TTL */
if(m_SendSocket.SetSockOpt(IP_MULTICAST_TTL, &nTTL, sizeof(int), IPPROTO_IP) == 0)
return FALSE; /* Error Setting TTL */
else
return TRUE; /* else TTL set successfully */
}
void CMulticastSocket::SetLoopBack(BOOL bLoop)
{
/* Set LOOPBACK option to TRUE OR FALSE according to IsLoop parameter */
int nLoopBack = (int)bLoop;
int i = m_SendSocket.SetSockOpt(IP_MULTICAST_LOOP, &nLoopBack, sizeof(int), IPPROTO_IP);