UDP broadcast in C

柔情痞子 提交于 2019-12-03 17:11:57

Disable loopback so you do not receive your own datagrams:

char loopch=0;

if (setsockopt(sd, IPPROTO_IP, IP_MULTICAST_LOOP,
               (char *)&loopch, sizeof(loopch)) < 0) {
  perror("setting IP_MULTICAST_LOOP:");
  close(sd);
  exit(1);
}

from: http://publib.boulder.ibm.com/infocenter/iseries/v5r3/index.jsp?topic=%2Frzab6%2Frzab6x1multicast.htm

You are on the right track, you need to see if a received package is from your self, and then discard it.

The simplest way to get the local hosts address is to use gethostname and gethostbyname. These will however not work well if your host has multiple hostnames or IP addresses. Search SO (or Google) for how to get all possible network addresses.

your program's broadcast destination port should be blocked on your machine to avoid receiving self broadcasts.

in your iptables you can drop the (TCP or UDP as required ) packets received on that port.

recvfrom will give you an address. Use that.

As for what addresses to match against, on many systems (probably the ones you care about) you can get local IP addresses with getifaddrs. However this is not in POSIX.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!