using System.Net;
using System.Text;
namespace HttpServer
{
class Program
{
// Main method
static void Main()
{
using var listener = new HttpListener();
listener.Prefixes.Add("http://localhost:10060/");
listener.Start();
Console.WriteLine("Listening on port 10060...");
// Request handler
while (true)
{
HttpListenerContext context = listener.GetContext();
HttpListenerRequest req = context.Request;
Console.WriteLine($"Received request for {req.Url}");
// TODO: Login stuff
Uri? url = req.Url;
if (url.ToString() == "http://localhost:10060/login")
{
using HttpListenerResponse resp = context.Response;
resp.Headers.Set("Content-Type", "text/plain");
string data = "Hello there!";
byte[] buffer = Encoding.UTF8.GetBytes(data);
resp.ContentLength64 = buffer.Length;
using Stream ros = resp.OutputStream;
ros.Write(buffer, 0, buffer.Length);
}
}
}
}
}
The above code is a simple http server that listens for requests. The above code works when going to localhost:10060 in the browser. However, I want to access this server via the machine's IP address on the same network through a different device. When doing so, it results in a bad request due to the invalid hostname. Is there a way to fix this?