so i created a client server program using tcp that works fine. but now i want to use broadcasting (which uses udp) so i'm changing to change my code but i keep running into problems.
when i run my code the error message "ERROR binding: 10047"
and that error means this:
Address family not supported by protocol family.
An address incompatible with the requested protocol was used. All sockets are created with an associated address family (that is, AF_INET for Internet Protocols) and a generic protocol type (that is, SOCK_STREAM). This error is returned if an incorrect protocol is explicitly requested in the socket call, or if an address of the wrong family is used for a socket, for example, in sendto.
here is the code:
int port = 7171;
if (param)
port = reinterpret_cast<short>(param);
SOCKET s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (s == -1)
{
closesocket(s);
return 1;
}
sockaddr_in brdcastaddr;
int len = sizeof(brdcastaddr);
char sbuf[1024];
brdcastaddr.sin_family = AF_INET;
brdcastaddr.sin_port = htons(port);
brdcastaddr.sin_addr.s_addr = INADDR_BROADCAST;
char opt = 1;
setsockopt(s, SOL_SOCKET, SO_BROADCAST, (char*)&opt, sizeof(char));
memset(&brdcastaddr,0, sizeof(brdcastaddr));
int bind_ret = bind(s, (sockaddr*)&brdcastaddr, sizeof(brdcastaddr));
if (bind_ret == -1)
{
CString text;
text.Format(_T("ERROR binding: %d"), WSAGetLastError());
AfxMessageBox(text);
closesocket(s);
return 1;
}
int ret = sendto(s, sbuf, strlen(sbuf), 0, (sockaddr*)&brdcastaddr, len);
if(ret < 0)
{
CString text;
text.Format(_T("ERROR with sendto: %d"), WSAGetLastError());
AfxMessageBox(text);
return 1;
}
int listen_ret = listen(s, 5);
if (listen_ret == -1)
{
CString text;
text.Format(_T("ERROR listening: %d"), WSAGetLastError());
AfxMessageBox(text);
closesocket(s);
return 1;
}
while (true)
{
sockaddr_in client_addr;
int len = sizeof(client_addr);
SOCKET client_sock = accept(s, (sockaddr*)&client_addr, &len);
ClientInfo info;
info.sock = client_sock;
info.addr = inet_ntoa(client_addr.sin_addr);
{
Mutex<CriticalSection>::Lock lock(client_cs);
clients.push_back(info);
}
unsigned tid;
_beginthreadex(NULL, 0, tcp_servers_client, reinterpret_cast<void*>(client_sock), 0, &tid);
}
closesocket(s);
return 0;