开发者

Filter UDP packets from a particular IP

I have a program which transmits(broadcasts) and receives UDP packets simultaneously using pthreads. What I want to do is to remove packets which have been sent by me. How do I do that? My receive code currently looks as follows:

void *receive_thread_body(void *arg)
{
  long msg = 0;

  while(msg<500)
  {
    f开发者_开发知识库d_set socket_set;
    FD_ZERO(&socket_set);
    FD_SET(b_sock,&socket_set);
    struct timeval tm;
    tm.tv_usec = 10;
    tm.tv_sec = 0;

    int ret = select(b_sock+1,&socket_set,0,0,&tm);

    if(ret == -1)
    {
      std::cout<<"select failed";
    }

    if(FD_ISSET(b_sock,&socket_set) != 0)
    {
      int recvStringLen = recvfrom(b_sock, &msg, sizeof(msg), 0, NULL, 0);
      if(recvStringLen < 0)
      {
        std::cout<<"recvfrom failed";
      }
      else
      {
        printf("\t\t\tRX: %d\n",msg);
      }
    }
  }
}


You need to fill the last two parameters of the recvfrom call - that will be the sender's address.

Then compare it to the list of your own addresses for matches (see here for example for relevant info).

This method is agnostic to the way of sending - you can use it on connection or connection-less sockets, and of course on broadcast or multicast (or unicast) transmissions.


If you are talking about Multicast, unset the IP(V6)?_MULTICAST_LOOP option (which may be enabled by default) to not receive what you send. Note that this will prevent other applications on the same host to receive what you sent.

int zero = 0;
err = setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &zero, sizeof zero);

I haven't heard of an equivalent for broadcast. But broadcast is so old that it was replaced by Multicast in the IPv6 standard.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜