2

Are there any negative security effects of setting the SO_BROADCAST option in a C UDP socket? I'm writing a C program and if I just set the broadcast option to 1 then all IP addresses work as intended, but if I don't set it then only unicast or multicast IP addresses will be accepted by the kernel.

Luc
  • 31,973
  • 8
  • 71
  • 135
user
  • 606
  • 7
  • 11
  • There is no flag field in the UDP (or even IPv4) header for "broadcast". Which bit or option are you talking about? – Luc Feb 27 '18 at 21:08
  • The `SO_BROADCAST` flag for `setsockopt` on a UDP socket in C. – user Feb 27 '18 at 21:15
  • Ah, I see (in `man 7 ip`), and you've already edited your question to clarify. Thanks! – Luc Feb 27 '18 at 21:53

1 Answers1

0

As far as I know, sending broadcast over UDP protocol is normal. So, there is not problem to use SO_BROADCAST in setsockopt(2).

Disclaimer: The only thing you SHOULD be aware of is the tiny change of optval (in setsockopt(2)) between Linux and Solaris/sunOS environment.

snippet code example:

  static int fd = -1;
/* Use the SVR4 macros to distinguish between Solaris and SunOS */
#if defined(sun) || defined(__sun) || defined(__SVR4) || defined(__svr4__)
/* Solaris || SunOS */
  char on = '1';
#else /* defined(__linux__) */
  uint32_t on = 1;
#endif
  if ((fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP))== -1)
  {
#ifndef NDEBUG
    dbg_err_fputs("Cannot open datagram: \"%s\"", strerror(errno));
#else
    dbg_err_fputs("Cannot open datagram");
#endif
  }


#ifdef SO_BROADCAST
  if (setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on)) == -1)
  {
#ifndef NDEBUG
    dbg_err_fputs("Cannot set brodcast flag in socket optname: \"%s\"", strerror(errno));
#else
    dbg_err_fputs("Cannot set broadcast flag in socket optname");
#endif
  }
#endif /* SO_BROADCAST */

If your development platform is a Solaris/sunOS, then you will have to add some flags at the end of the command during compilation: -lnsl -lsocket. Depending on the Solaris/SunOS version, the socket will only work if you add the -lxnet flag... If error persists: -lresolv.

slayer
  • 402
  • 3
  • 14