Click here to Skip to main content
15,905,590 members

Comments by 3iii (Top 2 by date)

3iii 25-Aug-14 11:39am View    
Hi bling!
At the moment I'm trying to open a socket to receive any messages, but (!!!) from a specific port....I do it by following way:

SOCKADDR_IN UDPserveraddr;
memset(&UDPserveraddr,0, sizeof(UDPserveraddr));
UDPserveraddr.sin_family = AF_INET;
UDPserveraddr.sin_port = htons(4001);
UDPserveraddr.sin_addr.s_addr = INADDR_ANY;


int len = sizeof(UDPserveraddr);
// Bind the socket.
iResult = ::bind(sockListener, (SOCKADDR*)&UDPserveraddr, sizeof(SOCKADDR_IN));
if (iResult == SOCKET_ERROR) {
wprintf(L"sockListener: bind failed with error %u\n", WSAGetLastError());
::closesocket(sockListener);
WSACleanup();
return 1;
}
else
{
wprintf(L"sockListener: bind returned success\n");
}


//As next step I call the following function
//(it contain code that I show in my question above)
//
SendBroadcast();

//Further there is a cycle where I'm trying to get a message from a few devices ....

while (true)
{
fd_set fds;
struct timeval timeout;
timeout.tv_sec = 50;
timeout.tv_usec = 0;

FD_ZERO(&fds);
FD_SET(sockListener, &fds);
int rc = select(0, &fds, NULL, NULL, &timeout);

if(rc > 0)
{
int buffersize = 340 /*1024*/;
char rbuf[340 /*1024*/];
memset( &rbuf, '\0', buffersize );

SOCKADDR_IN clientaddr;
int len = sizeof(clientaddr);


int nchars = recvfrom(sockListener,rbuf, buffersize, 0,
(sockaddr*)&clientaddr, &len);
if(nchars > 0)
{
char *p = inet_ntoa(clientaddr.sin_addr);
int serverportno = ntohs(clientaddr.sin_port);

//wprintf(L"\r\nBroadcast Server: %s \r\n%s\r\n\r\n", p, rbuf);
printf("Buffer: %s", rbuf);
struct sockaddr_in *si_other_in =
(struct sockaddr_in *)&clientaddr;
std::cout << "\nPkg arrived: "
<< nchars << " "
<< inet_ntoa(si_other_in->sin_addr)
<< ":"
<< ntohs(si_other_in->sin_port)
<< std::endl;
}//
}
else if(rc == 0)
{
printf("\nEmpty");
}
else if(rc < 0)
{
printf("\nError");
}

}//while

// Close the socket when finished receiving datagrams
wprintf(L"\nFinished receiving. Closing socket.\n");

iResult = ::closesocket(sockListener);

Unfortunately I only get the first 4 bytes of one of the messages while listening .... (which I see in the console) ....
But in the Wireshark sniffer I see that they come !!! Each response has <340 bytes (data)

I will be grateful to you if you can help me! Thanks in advance :)
3iii 24-Aug-14 5:39am View    
Firstly thank you bling for your comment
But why you say : "you don't (yet) know the IP/port"?
I know from which port the message will be sent, but you're right the IP I don't know, because it's UDP...(I send the broadcast message on the unknown number of devices)
Maybe you have any example to solve this problem?