I have a problem with a c++ socket.
I'm using CAsyncSocket from MFC that i want to join a multicast group.
Also I need to have multiple listener on this group and here is where i get in trouble.
I found some examples on the web but it doesn't seems to work.
Here is my code:
//create socket on port 17233
BOOL bRet = Create(17233,SOCK_DGRAM, FD_READ);
//set reuse socket option
BOOL bMultipleApps = TRUE;
bRet = SetSockOpt(SO_REUSEADDR, (void*)&bMultipleApps, sizeof(BOOL), SOL_SOCKET);
//join multicast group
ip_mreq m_mrMReq; // Contains IP and interface of the host group
m_mrMReq.imr_multiaddr.s_addr = inet_addr((LPCSTR)"224.30.0.1"); /* group addr */
m_mrMReq.imr_interface.s_addr = htons(INADDR_ANY); /* use default */
int uRes =setsockopt(m_hSocket, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char FAR *)&m_mrMReq, sizeof(m_mrMReq));
There are no errors when i run this.
But when i try to run another instance of the app it fails to create a new socket on that port because the port is in use.
I have done this in C# and it worked fine like this:
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, port);
s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
s.Bind(ipep);
IPAddress ip = IPAddress.Parse(mcastGroup);
s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip, IPAddress.Any));
s.SetSocketOption(SocketOptionLevel.IP,SocketOptionName.MulticastTimeToLive, int.Parse("1"));
So if any body sees a problem with my code or have some tips i will gladly appreciated.
EDIT 1:
Is CAsyncSocket a TCP socket?
EDIT 2:
After reading Can two applications listen to the same port?
I think i made a confusion. I need a Multicast UDP port that can be access by multiple application using SO_REUSEADDR
Edit for Clarification:
BOOL bRet = Create(17233,SOCK_DGRAM, FD_READ)
Creates an UDP socket and bind's to to port 17223.
For SetSockOpt(SO_REUSEADDR, (void*)&bMultipleApps, sizeof(BOOL), SOL_SOCKET);
to work you need to set it before binding as @Hasturkun said.
The final working code looks like this:
BOOL bRet = Socket(SOCK_DGRAM, FD_READ);
if(bRet != TRUE)
{
UINT uErr = GetLastError();
std::cout<<"Error:"<<uErr<<std::endl;
return FALSE;
}else{
std::cout<<"Create sock: OK"<<std::endl;
}
//add reuse
BOOL bMultipleApps = TRUE; /* allow reuse of local port if needed */
SetSockOpt(SO_REUSEADDR, (void*)&bMultipleApps, sizeof(BOOL), SOL_SOCKET);
//bind
bRet = Bind(17233, NULL);
if(bRet != TRUE)
{
UINT uErr = GetLastError();
std::cout<<"Error(BIND):"<<uErr<<std::endl;
}else{
std::cout<<"BIND sock: OK"<<std::endl;
}
Thanks,
Gabriel
;