Skip to content

Instantly share code, notes, and snippets.

@philipmat
Created September 11, 2020 14:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save philipmat/52f246ed39d17944053a74beb6b3c268 to your computer and use it in GitHub Desktop.
Save philipmat/52f246ed39d17944053a74beb6b3c268 to your computer and use it in GitHub Desktop.
HTTP Listener - creates a netcat-like listener on a local port. Returns 201 to all requests
void Main() {
var cts = new CancellationTokenSource();
var task = StartListener(cts.Token);
do {
Thread.Sleep(1);
} while (true);
cts.Cancel();
task.Wait();
}
async Task StartListener(CancellationToken token) {
// netsh http add urlacl url=http://+:8080/ user=us\af59986
// if that doesn't work, run as Admin or https://stackoverflow.com/a/45177071
// var url = "http://localhost:8080/";
// var url = "http://30.239.173.11:8080/";
var url = "http://*:80/";
var listener = new HttpListener();
listener.Prefixes.Add(url);
try {
listener.Start();
} catch (Exception ex) {
Console.WriteLine($"failed to listen on {url}: {ex}");
}
$"Listening on {url}".Dump();
token.Register(() => listener.Abort());
while (!token.IsCancellationRequested) {
HttpListenerContext context;
try {
context = await listener.GetContextAsync().ConfigureAwait(false);
await HandleRequest(context); // Note that this is *not* awaited
} catch {
// Handle errors
}
}
}
async Task HandleRequest(HttpListenerContext context) {
// Handle the request, ideally in an asynchronous way.
// Even if not asynchronous, though, this is still run
// on a different (thread pool) thread
string content = "";
if (context.Request.HasEntityBody) {
using (System.IO.Stream body = context.Request.InputStream) {
using (System.IO.StreamReader reader = new StreamReader(body, context.Request.ContentEncoding)) {
content = await reader.ReadToEndAsync();
}
}
}
new {
UrlCalled = context.Request.Url,
Method = context.Request.HttpMethod,
Body = content,
}.Dump();
context.Response.StatusCode = 201;
context.Response.Close();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment