tesses-webserver-extras/Tesses.WebServer.EasyServer/Class1.cs

74 lines
2.5 KiB
C#

using System;
using System.Collections.Generic;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Threading;
namespace Tesses.WebServer
{
public static class EasyServerExtensions
{
public static void StartServer(this IServer hdlr,int port=49299)
{
using(var ct=new CancellationTokenSource())
{
Console.CancelKeyPress += (sender,e)=>{
ct.Cancel();
};
HttpServerListener server1=new HttpServerListener(port,hdlr);
("http",port).PrintAllIps();
ConsoleColor c=Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Almost Ready to Listen");
Console.ForegroundColor=c;
server1.Listen(ct.Token);
}
}
static Random r=new Random((int)(DateTime.Now.Ticks % int.MaxValue));
public static void PrintAllIps(this (string scheme,int port) url)
{
var cl=Console.ForegroundColor;
Console.ForegroundColor=ConsoleColor.Blue;
Console.WriteLine("Interfaces:");
Console.ForegroundColor=cl;
foreach(NetworkInterface iface in NetworkInterface.GetAllNetworkInterfaces())
{
if(iface.OperationalStatus == OperationalStatus.Up){
var fg=Console.ForegroundColor;
Console.ForegroundColor=ConsoleColor.Green;
Console.Write(iface.Name);
Console.ForegroundColor=fg;
Console.Write(": ");
Console.ForegroundColor =ConsoleColor.Magenta;
List<string> ips=new List<string>();
foreach(var item in iface.GetIPProperties().UnicastAddresses)
{
if(item.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork){
if(BitConverter.IsLittleEndian)
{
ips.Add($"{url.scheme}://{item.Address.ToString()}:{url.port}/");
}
else
{
var addrBytes = item.Address.GetAddressBytes();
ips.Add($"{url.scheme}://{addrBytes[3]}.{addrBytes[2]}.{addrBytes[1]}.{addrBytes[0]}:{url.port}/");
}
}
}
Console.WriteLine(string.Join(" , ",ips));
Console.ForegroundColor =fg;
}
}
}
}
}