简体   繁体   中英

Forwarding UDP packets in C using the socket API

I am writing a content filter in C using the socket API that will intercept DNS requests, and only return the response if the domain is allowed. The pseudocode to describe this is:

  1. Redirect all DNS queries to the content filter program which is listening on UDP port X.
  2. Content filter program extracts domain being queried and determines if it is allowed or not.
  3. If it is allowed, then the content filter program forwards the original DNS request packet to the original destination DNS server while maintaining the original source and IP+port so that the DNS server can send the reply directly back to the client.
  4. If the domain is not allowed, then no reply is sent.

I currently have the program listening on UDP port X but the problem is that I can't access the IP headers, and therefore can't simply forward the DNS request to the original server while maintaining the original headers.

I have tried using socket(AF_INET, SOCK_RAW, IPPROTO_UDP) but that doesn't bind on port X (understandably), and doesn't receive any traffic.

What is the best way to go about listening on UDP port X, while still being able to access the IP headers of incoming packets?

I think recvfrom on an UDP socket should give you the correct source address. You still probably need a raw socket for forwarding the message.

The functionality for SOCK_RAW based sockets varies depending on the platform you are on. Generally, when you want to get access to the full IP datagram information, then I would recommend using the Berkeley Packet Filter to tap the data-link layer frames addressed to UDP port of interest.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM