-->

Build a DNS Proxy in C

2020-07-27 06:00发布

问题:

I want to build a simple DNS Proxy in C, which accepts DNS Queries from UDP Port 53, forwards the query to Google's DNS server TCP port 53 to do the lookup, and then returns the answer offered by Google.

Yes, this is a school project and I'm so confused that I don't know where to get started.

Thanks for helping!!

回答1:

You've struck lucky with the requirements - because you're going from UDP -> TCP, it's actually a lot simpler than doing UDP -> UDP.

Specifically, what I mean is that because the outward facing side is using a connection orientated socket, you know straight away that the response you receive must pertain to the query you just sent, so long as you use a new TCP socket for each query.

If the outward facing side had been UDP it becomes a lot harder to figure out which query each response relates to - there's no guarantee in the protocol that responses arrive in the same order as the queries.

If multithreading isn't a requirement, then (in pseudo-code)

"open" a UDP socket
"bind" that socket to port 53
while (true) {
    "recvfrom" a packet from the UDP socket
     ... and remember the address it was received from
    "open" a TCP socket
    "connect" it to Google's DNS
    "write" the length of the original query (two bytes, network order - RFC 1035)
    "write" the contents of the original query
    "read" a two byte length header
    "read" that many bytes from the TCP socket
    "close" the TCP socket
    "sendto" those bytes back over the UDP socket to the original client address
}


回答2:

first of all you need to chose an API for writing messages on to a network. For windows, you have Winsock API. For unix-like systems you have the BSD Sockets API.
Although most of the courses use the BSD API.

Now your steps may be:

  • have a look at rfc for DNS implementation. You can only focus on format of request and response messages, as you may need to change some fields.
  • Now write a client server code which consists of two modules:
    • Server side code to receive a DNS query request, may need to change some fields.
    • Pass it on to the Module that interacts with Google's DNS server.
    • Capture the response and forward it back to requesting client. (again you may need to change some fields)


标签: c dns