Receiving UDP broadcast - c++

I have to receive an UDP broadcast (in Ubuntu if that makes any difference). Using Wireshark, I can see the packet being sent from the server machine, and I can see it being received by my client machine, but my program is completely oblivious. This is what I have:
sockaddr_in si_me, si_other;
int s;
assert((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))!=-1);
int port=6000;
int broadcast=1;
setsockopt(s, SOL_SOCKET, SO_BROADCAST,
&broadcast, sizeof broadcast);
memset(&si_me, 0, sizeof(si_me));
si_me.sin_family = AF_INET;
si_me.sin_port = htons(port);
si_me.sin_addr.s_addr = INADDR_ANY;
assert(::bind(s, (sockaddr *)&si_me, sizeof(sockaddr))!=-1);
while(1)
{
char buf[10000];
unsigned slen=sizeof(sockaddr);
recvfrom(s, buf, sizeof(buf)-1, 0, (sockaddr *)&si_other, &slen);
printf("recv: %s\n", buf);
}
It is compiled in debug mode, the asserts aren't being erased during compilation, and my program just blocks on recvfrom.
Is there any other hoop I have to jump through to receive an untargeted UDP broadcast?
Edit: just a bit more info, I have the two computers connected on a dedicated switch, no outside interference. I also have a second network card on my client computer that connects to the company network, which also works.
I can ping both the outside (Internet working) and my server machine (plus I can see the actual packets in Wireshark), but you never know what might cause this problem.

As it turns out my code is perfectly fine, as I thought it would be. There was a problem with the network setup itself.
For posterity, I had set up two static IP'd computers on their own hub, instead of using the built in DHCP server on the server machine to allocate the IP address for the other computer. Pretty localized for my problem but you never know..

To send and receive broadcast
Be sure that netmask is correct. in windows mask for broadcast packets does not matters, but not in linux.
bind socket to INADDR_ANY
setsockopt to BROADCAST
call sendto with sendaddr.sin_addr.s_addr = inet_addr("your_interface_broadcast_address").
or - call sento several times for each interface with its broadcast ip address.
call recvfrom. any time before calling recvfrom, set up length parameter.

Related

UDP client doesn't broadcast message on esp32

So I am trying to send packets via UDP as a broadcast from one ESP32 to another. The receiver is an access_point and server, the sender is a station and client.
I already read this:
ESP32 - UDP broadcaster/ receiver with native LwIP library
But it didn't help. I know that my server works because I can send packages via terminal.
But for the client it seems that the packages aren't leaving the esp.
My code:
// CLIENT:
sockaddr_in _send_addr;
_send_addr.sin_family = AF_INET,
_send_addr.sin_port = htons( 5000 );
// also tried local broadcast 192.168.4.255
_send_addr.sin_addr.s_addr = inet_addr( "255.255.255.255" );
_send_addr.sin_len = sizeof( _send_addr );
int _sock;
_sock = socket( AF_INET, SOCK_DGRAM, IPPROTO_IP );
int broadcast = 1;
setsockopt( _sock, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof(broadcast) );
void* data; // has some length
size_t len; // len of data
sendto( _sock, data, len, 0, (const struct sockaddr*) &_send_addr,
sizeof(_send_addr) );
// SERVER:
// server is bound to same port, and to ip "0.0.0.0"
// like I said normally the server shouldn't be the problem, cause he received already
I skipped the checks.
But everything is created successfully, and the sendto returns the correct number of bytes written.
I have really no idea anymore appreciate any help.
So I found the problem. There is in fact no problem with the socket.
I have bluetooth and wifi running at the same time. On esp32 both share one antenna. It seems like the BT gets a higher priority (I am running an a2dp sink). And the wifi module is unable to acquire the antenna. Hence the problem.
The following problem (and maybe a solution), can be found here:
acquire a semaphore for the esp32 antenna (bluetooth/wifi dualmode)

C++ UDP Broadcast using ::write

I am writing a UDP client/server application. The server is a broadcast server, that broadcasts on a particular port to two clients on the same subnet. Each client receives a datagram and sends a response to the server. Each client knows the ip address of the server in advance.
My client is basically as in the client example of http://man7.org/linux/man-pages/man3/getaddrinfo.3.html, i.e. it uses the connect() function to specify the endpoint of all outgoing packets. By using connected UDP, the client can use read() and write() to the socket file descriptor rather than sendto/recvfrom.
For my server, I want to adopt a similar approach - configure the socket for broadcasting, and call read/write on the file descriptor. I can bind() the socket to listen for incoming datagrams on the specified port, and these are collected fine.
Minus error checking, my server code looks like this:
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
int broadcast = 1;
setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof int);
struct sockaddr_in servaddr;
memset((char*) &servaddr, 0, sizeof servaddr);
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(PORT);
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
int success = bind(sockfd, (struct sockaddr*) &servaddr, sizeof servaddr);
int BUFSIZE = 256;
char buf[BUFSIZE];
while (1)
{
// this works fine
int bytes_read = read(sockfd, buf, BUFSIZE);
// WANT TO BROADCAST HERE
int bytes_written = write(sockfd, buf, bytes_read);
}
However, when I try and broadcast a packet in the write() line, I get a 'Destination address not specified' error. I could call connect() to set the destination address, but I don't think connect() works on a broadcast socket.
Is there a way of broadcasting using write() rather than sendto?
The problem with using connect() for broadcast is that (in addition to modifying the behavior of send()/write()), connect() will install a filter on the socket so that it only receives packets whose source-IP field matches the IP address specified in the argument to connect().
That means if you call connect() on your socket with a broadcast-address as its argument, then your socket will only receive packets coming from that broadcast-address -- but packets are never (AFAIK) tagged as coming from a broadcast address -- rather, their Source-IP field is set to the IP address of the computer that sent the packet, as usual. The upshot is that if you connect() your socket to a broadcast address, you won't receive any packets on that socket.

UDP Broadcasting using winsock on a win 10 machine not working

I'm making a LAN multiplayer game using c++ and winsock, were I've created my own protocol for connecting two machines to eachother. The protocol involves broadcasting a message over the local LAN, which strangely isn't working on one of the two machines I'm using to test my code. The strange part is that it's as mentioned working on one machine, whereas not on the other. I've used wireshark to monitor outgoing packets, and the packets isn't being sent on the failing machine, even though that sendto() is returning the correct amount of bytes. The only difference between the machines is that one (the failing one) is using win10 and the other win8.
Is there any difference in the winsock library/networking layer between windows 10 and windows 8 that could cause this? Else, do you have any other ideas of what could cause the failure?
The code for sending a broadcast looks like this:
sockaddr_in send_addr;
send_addr.sin_family = AF_INET;
send_addr.sin_port = htons(PORT);
send_addr.sin_addr.s_addr = inet_addr("255.255.255.255");
int iResult = sendto(sock,
reinterpret_cast<char*>(&packet),
sizeof(Packet),
0,
(SOCKADDR *)&send_addr,
sizeof(send_addr));
if (iResult == SOCKET_ERROR)
{
printf("Failed to send broadcastmsg");
}
And the code to recieve it looks like this:
sockaddr_in sender_addr;
int sender_addrLen = sizeof(sender_addr);
Packet recvdPacket = {};
int iResult = recvfrom(sock,
reinterpret_cast<char*>(&recvdPacket),
sizeof(recvdPacket),
0,
(SOCKADDR*)&sender_addr,
&sender_addrLen);
if (iResult > 0)
{
return recvdPacket;
}
return Packet{};
You need to enable broadcast setting SO_BROADCAST before sending a broadcast message: https://msdn.microsoft.com/en-us/library/windows/desktop/ms740476(v=vs.85).aspx ,
Why do we need SocketOptions.SO_BROADCAST to enable broadcast?
char broadcast = 1;
setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof(broadcast))
Also you should use directed broadcast (for example, 192.168.0.255) instead of Internet broadcast (255.255.255.255). I believe you don't need Internet broadcast.
Also, can you print the value returned by sendto? is iResult == sizeof(Packet)?
Last, which is the size of Packet? Is it a class? you are reinterpreting &packet as a char *. You must be sure there is no error there.
Could broadcast be blocked in the Win10 PC? I don't know if it's possible.
Consider using multicast.

Receiving broadcast packet addressed to 255.255.255.255 in C++

I have a device that is discovered by sending a broadcast packet to 255.255.255.255 on port 4930 and the device responds by sending a packet back to 255.255.255.255 on port 4930.
I have a snippet of C++ code which can send a packet to 255.255.255.255 on port 4930 (both source and destination port), but it can't receive a packet back from the broadcast address 255.255.255.255.
I can see the device is working fine, wireshark can see the packets coming back and forth and the propriety software supplied with the device can discover the device just fine, the problem is with the C++ program so please keep on topic with your responses.
Now, as I have said I can send a packet just find, but firstly I can't bind to the IP address 255.255.255.255 to receive the packets. I can change the multicast address to 239.255.255.250 and the socket will bind but I need the address 255.255.255.255.
My snippet of code is below, I am using VC++2010
bool CPTUProgramDlg::FindPTU(u_short port, const char * Destaddress){
{
//Data to send
char packet_data[10] = {0x44,0x43,0x55,0x44,0x5f,0x50,0x49,0x4e,0x47,0x00};
int packet_size=10;
SOCKET sock;
struct sockaddr_in addr;
sock = socket(AF_INET, SOCK_DGRAM, 0);
// set SO_BROADCAST on a socket to true (1): (so we can transmit to 255 addr)
//In order to use broadcast the options of socket must change
char broadcastON = 1;
setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &broadcastON, sizeof broadcastON);
if (sock < 0)
return false;
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = inet_addr(Destaddress); // Specify dest IP
sendto(sock, packet_data, packet_size, 0, (struct sockaddr*)&addr, sizeof(addr));
if (bind(sock,(struct sockaddr*) &addr,sizeof(addr)) != -1){
char Buff[512];
recv(sock,Buff,512,0);
}
closesocket(sock);
}
return 1;
}
Wireshark screenshot to prove packets are being send:
From the wireshark output its seen that the special device is using broadcast to communicate and will use the same port number as source and destination.
Normal socket communication will require using matching port numbers but broadcast messages cannot be exchanged over the same socket, especially when the port numbers do not match as seen with wireshark.
Binding on 255.255.255.255 (INADDR_BROADCAST) should generally work but may be limited by your OS privileges and permissions.
You may try to solve the problem by using two sockets - one for receiving and one for sending. Of course the listening socket have to be setup first and bound to 0.0.0.0 (INADDR_ANY) and port 4930. In this case there is no easy way to filter by destination address (as I wrongly written in my comment) because most standard socket APIs do not provide a way to get the destination addess from the socket. On Linux there is an exception - IP_PKTINFO at SOL_IP...
By using recvfrom you will get the source unicast address of the responding device(s). You have to note that if you have more that one such device on your network you will get more than one response.

Nothing received from recvfrom on windows

I have some problems on Windows 8 using recvfrom. I have a socket which is bound to INADDR_ANY (0.0.0.0), and i'd like to receive some packets on it.
The problem is that I see those packets in Wireshark, but recvfrom never tells me that the received size is greater than 0. I've tried biding the socket to 127.0.0.1 or even to my local IPv4 address, I never get anything. The port used is 7321 (locally)
I use the ENet library for the creation of the socket, and then I used that socket in recvfrom. Here's the code that never returns the expected packets.
uint8_t* buffer; // max size needed normally (only used for stun)
buffer = (uint8_t*)(malloc(sizeof(uint8_t)*2048));
memset(buffer, 0, 2048);
socklen_t from_len;
struct sockaddr addr;
from_len = sizeof(addr);
int len = recvfrom(m_host->socket, (char*)buffer, 2048, 0, &addr, &from_len); //m_host is of type ENetHost, the socket in it is a file descriptor like standard sockets
As I said, it's a bit weird as Wireshark shows me the packets (which are STUN responses if you want to know).
Can someone help me find out what is missing that may be causing this issue?
Your addr variable is declared as a sockaddr. It needs to be declared as a sockaddr_in (works with IPv4 only) or SOCKADDR_STORAGE (works with both IPv4 and IPv6), and then typecast it to sockaddr* when passing it to recvfrom().
Aside from that, you say that recvfrom() is not returning >= 0. So what is it actually returning? If it returns 0, then a 0-length packet was received (impossible for TCP, but possible for UDP). If it returns -1 (aka SOCKET_ERROR), then an error occured so use WSAGetLastError() to find out what that error actually is.
I can think of 2 possible reasons you are having the problem:
1) You might not have the port correct on your sendto & recvfrom socket. So say you are sending packets to port 6000, but your recvfrom is listening on port 6001 or something. Just double check both programs are using the same port.
2) Windows firewall. I would run the program as an admin just to be safe, but also make sure you allow your program through windows firewall to communicate using private or public networks.