2

My IDE: xCode, OS X 10.10.4

int s = socket(AF_INET, SOCK_DGRAM, 0);
bool bc = true;
int ret = setsockopt(s, SOL_SOCKET, SO_BROADCAST, (const void*)&bc, sizeof(bool));
if(ret < 0){
    perror("set opt err:");
}
sockaddr_in tarAddr;
memset(&tarAddr, 0, sizeof(sockaddr_in));
tarAddr.sin_family = AF_INET;
tarAddr.sin_port = htons(5000);
tarAddr.sin_addr.s_addr = INADDR_BROADCAST;

char szMsg[100] = {0};
strcpy(szMsg, "hello");

int len = sizeof(sockaddr);
ret = sendto(s, szMsg, strlen(szMsg), 0, (sockaddr*)&tarAddr, len);
if(ret < 0){
    perror("sendto err:");
}
close(s);

The above code is about send udp message to broadcast, but the result info is:

set opt err: Invalid argument
sendto err: Permission denied

and the same code go fine in vc++/windows.

Tadeusz Kopec for Ukraine
  • 12,283
  • 6
  • 56
  • 83
liuhui
  • 49
  • 5

3 Answers3

1

Maybe the argument sizeof(bool) returns an invalid value. As you can see in the following link, it is not defined that sizeof(bool)should deliver 1.

Is sizeof(bool) defined?

I also think that you don't have to cast the pointer in the function call. It would be enough only to have the &.

Can you provide some code of the sendto()function to determine the other error?

Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
Frodo
  • 749
  • 11
  • 23
1

I changed bc to int and this solve the problem

1

As has been insinuated, your optval is wrong.

From the socket manpage:

The socket options listed below can be set by using setsockopt(2) and read with getsockopt(2) with the socket level set to SOL_SOCKET for all sockets. Unless otherwise noted, optval is a pointer to an int.

You're giving it a pointer to a bool instead.

Fortunately, the function is able to detect this (possibly sizeof(bool) differs from sizeof(int) on your platform, or otherwise its reinterpreting a bool as an int simply results in a value it doesn't recognise; it's UB anyway), so you get a nice error telling you that your argument is wrong.

Remember, the function doesn't know the type of your data (as it gets a void*), so even if it wanted to be able to accept an int or a bool or llama it would have no way of doing so.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055