• Stars
    star
    395
  • Rank 105,243 (Top 3 %)
  • Language
    C#
  • License
    MIT License
  • Created about 11 years ago
  • Updated 6 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A DNS library written in C#

DNS

A DNS library written in C# targeting .NET Standard 2.0. Versions prior to version two (2.0.0) were written for .NET 4 using blocking network operations. Version two and above use asynchronous operations.

Available through NuGet.

Install-Package DNS

Test

Usage

The library exposes a Request and Response classes for parsing and creating DNS messages. These can be serialized to byte arrays.

Request request = new Request();

request.RecursionDesired = true;
request.Id = 123;

UdpClient udp = new UdpClient();
IPEndPoint google = new IPEndPoint(IPAddress.Parse("8.8.8.8"), 53);

// Send to google's DNS server
await udp.SendAsync(request.ToArray(), request.Size, google);

UdpReceiveResult result = await udp.ReceiveAsync();
byte[] buffer = result.Buffer;
Response response = Response.FromArray(buffer);

// Outputs a human readable representation
Console.WriteLine(response);

Client

The libray also includes a small client and a proxy server. Using the ClientRequest or the DnsClient class it is possible to send a request to a Domain Name Server. The request is first sent using UDP, if that fails (response is truncated), the request is sent again using TCP. This behaviour can be changed by supplying an IRequestResolver to the client constructor.

ClientRequest request = new ClientRequest("8.8.8.8");

// Request an IPv6 record for the foo.com domain
request.Questions.Add(new Question(Domain.FromString("foo.com"), RecordType.AAAA));
request.RecursionDesired = true;

IResponse response = await request.Resolve();

// Get all the IPs for the foo.com domain
IList<IPAddress> ips = response.AnswerRecords
	.Where(r => r.Type == RecordType.AAAA)
	.Cast<IPAddressResourceRecord>()
	.Select(r => r.IPAddress)
	.ToList();

The DnsClient class contains some conveniance methods for creating instances of ClientRequest and resolving domains.

// Bind to a Domain Name Server
DnsClient client = new DnsClient("8.8.8.8");

// Create request bound to 8.8.8.8
ClientRequest request = client.Create();

// Returns a list of IPs
IList<IPAddress> ips = await client.Lookup("foo.com");

// Get the domain name belonging to the IP (google.com)
string domain = await client.Reverse("173.194.69.100");

Server

The DnsServer class exposes a proxy Domain Name Server (UDP only). You can intercept domain name resolution requests and route them to specified IPs. The server is asynchronous. It also emits an event on every request and every successful resolution.

// Proxy to google's DNS
MasterFile masterFile = new MasterFile();
DnsServer server = new DnsServer(masterFile, "8.8.8.8");

// Resolve these domain to localhost
masterFile.AddIPAddressResourceRecord("google.com", "127.0.0.1");
masterFile.AddIPAddressResourceRecord("github.com", "127.0.0.1");

// Log every request
server.Requested += (sender, e) => Console.WriteLine(e.Request);
// On every successful request log the request and the response
server.Responded += (sender, e) => Console.WriteLine("{0} => {1}", e.Request, e.Response);
// Log errors
server.Errored += (sender, e) => Console.WriteLine(e.Exception.Message);

// Start the server (by default it listens on port 53)
await server.Listen();

Depending on the application setup the events might be executed on a different thread than the calling thread.

It's also possible to modify the request instance in the server.Requested callback.

Request Resolver

The DnsServer, DnsClient and ClientRequest classes also accept an instance implementing the IRequestResolver interface, which they internally use to resolve DNS requests. Some of the default implementations are UdpRequestResolver, TcpRequestResolver and MasterFile classes. But it's also possible to provide a custom request resolver.

// A request resolver that resolves all dns queries to localhost
public class LocalRequestResolver : IRequestResolver {
	public Task<IResponse> Resolve(IRequest request) {
		IResponse response = Response.FromRequest(request);

		foreach (Question question in response.Questions) {
			if (question.Type == RecordType.A) {
				IResourceRecord record = new IPAddressResourceRecord(
					question.Name, IPAddress.Parse("127.0.0.1"));
				response.AnswerRecords.Add(record);
			}
		}

		return Task.FromResult(response);
	}
}

// All dns requests received will be handled by the localhost request resolver
DnsServer server = new DnsServer(new LocalRequestResolver());

await server.Listen();

More Repositories

1

titlebar

Emulate OS X window title bar
JavaScript
484
star
2

electron-drag

Window dragging for electron applications
JavaScript
320
star
3

jquery-observe

Observe DOM mutations with jQuery
JavaScript
135
star
4

osx-mouse

Mouse tracking for OS X
C++
73
star
5

win-mouse

Mouse tracking for Windows
C++
52
star
6

repaint

HTML layout engine
JavaScript
47
star
7

css-shorthand-expand

Expand CSS shorthand properties
JavaScript
46
star
8

text-width

Measure the text width in browsers
JavaScript
20
star
9

audio-stream

Stream raw audio data from a MediaStream
JavaScript
19
star
10

browser-beep

Beeping sound in browser using Web Audio API
JavaScript
16
star
11

cordova-plugin-android-wifi-manager

Cordova plugin for accessing Android WifiManager
Java
15
star
12

vue-long-press-directive

Long press directive plugin for Vue.js
JavaScript
10
star
13

syntactical

Browserify transform that emits a descriptive syntax error on invalid javascript
JavaScript
9
star
14

text-height

Measure the text height in browsers
JavaScript
9
star
15

service-names-port-numbers

IANA assigned port numbers
JavaScript
9
star
16

redditor

Minimal reddit API wrapper
JavaScript
7
star
17

the-hunt

2D multiplayer game for the browser
JavaScript
5
star
18

extended-inquiry-response

Bluetooth EIR encoder and decoder
JavaScript
5
star
19

remote-procedure-call-stream

Binary RPC protocol stream
JavaScript
4
star
20

reddit-thread-stream

Writable stream for updating reddit self threads
JavaScript
4
star
21

cyclic-array

Simple cyclic array (buffer) implementation
JavaScript
4
star
22

http.m

A HTTP server library written in Objective-C
Objective-C
4
star
23

render-html

Web component for server-side rendering HTML as images
JavaScript
4
star
24

osx-mouse-stream

Streaming mouse events for OS X
JavaScript
4
star
25

audio-activity

Detect audio activity of a MediaStream
JavaScript
3
star
26

noise-protocol-stream

Node stream wrapper for Noise Protocol C implementation compiled to WebAssembly
JavaScript
3
star
27

iServe

iOS application for serving device assets over HTTP
Objective-C
2
star
28

ruby-mud

A simple package manager for client-side Javascript
Ruby
2
star
29

ejs-stream

Through stream for rendering objects with ejs templates
JavaScript
2
star
30

elite

Tournament web application
JavaScript
2
star
31

service-port

Map a service name to a port number
JavaScript
2
star
32

taco-deploy-extract

Extract tarballs into taco deployment directories
JavaScript
2
star
33

npm-install-cache

Install node_modules from cache
Shell
2
star
34

indexeddown

Leveldown API implementation on top of IndexedDB
JavaScript
2
star
35

ruby-tracker

A small BitTorrent tracker written in Ruby
Ruby
1
star
36

jett

A Java API wrapper for Ge.tt
Java
1
star
37

root.redirects

Redirection handling for root
JavaScript
1
star
38

repaint-chrome

Simple interface for repaint
JavaScript
1
star
39

bitless

A small BitTorrent client written in Python
Python
1
star
40

level-tail-stream

Tailable stream from levelup compliant store
JavaScript
1
star
41

jquery-tag

A jQuery tagging plugin for input fields
JavaScript
1
star
42

get-stats

Basic RTCPeerConnection statistics
JavaScript
1
star
43

bitless.js

A small BitTorrent client written in Javascript
JavaScript
1
star
44

pcm-stream

A transform stream for converting audio encoded as 32-bit floats to 16-bit intergers
JavaScript
1
star
45

dribler

Soccer event stream
JavaScript
1
star
46

ebml-decoder

EBML decoder stream
JavaScript
1
star
47

cordova-plugin-android-imei

Cordova plugin for retrieving IMEI of the device
Java
1
star