i created a client server program in MFC using TCP and that worked fine. But i want the server to work on any computer so for the client to connect to the server i need to use broadcasting which can only be done in UDP. so i tried changing my code but i'm having a lot of problems. can someone please look at the code and tell me if i'm missing something (never used UDP before).
heres the code for server
when i run the program the message "error with sendto: 10047" displays
heres the code for server
when i run the program the message "error with sendto: 10047" displays
Code:
WSADATA wsaData;
WSAStartup(MAKEWORD(2,2), &wsaData);
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_ANY);
char opt = 1;
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;
}
setsockopt(s, SOL_SOCKET, SO_BROADCAST, (char*)&opt, sizeof(char));
memset(&brdcastaddr,0, sizeof(brdcastaddr));
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;
Comment