MaxGold MaxGold - 7 months ago 59
Android Question

android ad-hoc udp broadcast hangs on send(ndk)

I'm trying to send a broadcast message in my ad-hoc network - 192.168.2.x, using native c code.
But the app hangs on sendto(). btw the hang is not connected to the while, that wraps it, as I can see in debug, it only tries sendto() ones and hangs.
Is there something wrong with my code?

int broadcast(char* msg){
int bcast_sock;
struct sockaddr_in their_addr; // connector's address information
if((bcast_sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
LOGE("ERROR BROADCASTING , socket wasn't created");

int broadcastEnable=1;
int ret=setsockopt(bcast_sock, SOL_SOCKET, SO_BROADCAST, &broadcastEnable, sizeof(broadcastEnable));
if(ret < 0)
LOGE("ERROR BROADCASTING, Coulnt set broadcast enable through socket options");

their_addr.sin_family = AF_INET; // host byte order
their_addr.sin_port = htons(BROADCAST_PORT); // short, network byte order
their_addr.sin_addr.s_addr = htonl(INADDR_BROADCAST);
memset(&(their_addr.sin_zero), '\0', 8); // zero the rest of the struct

while(-1 == (int)sendto(bcast_sock, msg, strlen(msg), 0,
(struct sockaddr *)&their_addr, sizeof(struct sockaddr)));
return 0;

A couple of notes:

  • This of course are rooted phones.

  • If I broadcast using java broadcast, it works fine, I'm able to receive the broadcast ie:

    int receiverPort = 4949;
    sendPacket = new DatagramPacket(data, data.length, IPAddress, receiverPort);

  • Non broadcast messages are also being sent and received using native code.

  • The CPU usage becomes ~ 95% .

  • I've also tried simply sending to

any ideas?


I solved it by changing address conversion from:

their_addr.sin_addr.s_addr = htonl(INADDR_BROADCAST);



where IP = ""

Thanks for the help epx