A
A
andrkkk2020-04-18 13:59:59
C++ / C#
andrkkk, 2020-04-18 13:59:59

How to get ip-addresses of all running servers via UDP?

Understanding winsock and UDP. I am writing on one PC, there is no local network. On the client I send a broadcast request:

sockaddr_in broadcast;
// разрешение на широковещательный запрос
int enableBroadcast = 1;
setsockopt(ClientSocket, SOL_SOCKET, SO_BROADCAST, (char*)&enableBroadcast, sizeof(enableBroadcast));
    
broadcast.sin_family = AF_INET;
broadcast.sin_port = htons(Port);
broadcast.sin_addr.s_addr = INADDR_BROADCAST;
// определенное сообщение,на которое сервер ответит информацией о себе
char testmessage[] = "test\n";
sendto(ClientSocket, testmessage,sizeof(testmessage), 0, (sockaddr*)&broadcast, sizeof(broadcast));

// принимаю информацию о сервере 
char infoAboutServer[1024]; 
ZeroMemory(infoAboutServer, 1024);
recvfrom(ClientSocket, infoAboutServer, 1024, 0, (SOCKADDR*)&server, &sizeOfserver);

Server:
char RecvBuf[1024];
while(1){
ZeroMemory(RecvBuf, BufLen);
// принимаем сообщения
recvfrom(sListen, RecvBuf, 1024, 0, (SOCKADDR*)&SenderAddr, &SenderAddrSize);
// если это сообщение-запрос информации то отправляем в ответ информацию
 if (RecvBuf == "test") {
             SenderAddr.sin_addr.s_addr = inet_addr(inet_ntoa(SenderAddr.sin_addr));
             sendto(sListen, infoMessage.c_str(), infoMessage.size(), 0, (SOCKADDR*)&SenderAddr, SenderAddrSize);           
        }        
}

I think that if several servers are running on the network, then only one first response from one of the servers will come to the client on recvfrom? If so, how to get responses from all servers?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
res2001, 2020-04-18
@andrkkk

You will receive a response from all servers that received the broadcast request.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question