コード例 #1
0
        /*
         * private NetworkInterface findNetworkInterface()
         * {
         *  NetworkInterface[] intfs = NetworkInterface.GetAllNetworkInterfaces();
         *  foreach (NetworkInterface intf in intfs)
         *  {
         *      //Util.log(string.Format("===== {0}:{1} =====", intf.Name, intf.NetworkInterfaceType));
         *
         *      //bypass some interfaces
         *      if (intf.NetworkInterfaceType == NetworkInterfaceType.Loopback)
         *      {
         *          Util.log(string.Format("bypass loopback interface: {0}({1})", intf.Name, intf.Id));
         *          continue;
         *      }
         *      else if (intf.Name.StartsWith("VMware Network Adapter"))
         *      {
         *          Util.log(string.Format("bypass VMWare virtual interface: {0}({1})", intf.Name, intf.Id));
         *          continue;
         *      }
         *      else if (intf.OperationalStatus.Equals(OperationalStatus.Down))
         *      {
         *          Util.log(string.Format("bypass link down interface: {0}({1})", intf.Name, intf.Id));
         *          continue;
         *      } else if (Util.hasLinkLocalIp(intf))
         *      {
         *          Util.log(string.Format("bypass linklocal interface: {0}({1})", intf.Name, intf.Id));
         *          continue;
         *      }
         *
         *      return intf;
         *  }
         *  return null;
         * }   */

        /// <summary>Start the DHCP server.</summary>
        public void start()
        {
            if (localAddress == null)
            {
                dhcpsvr = new DHCPServer();
                sendNotify(DhcpNotify.NotifyType.CONTROL, "RTDhcpServer binds to 0.0.0.0");
            }
            else
            {
                dhcpsvr = new DHCPServer(localAddress);
                sendNotify(DhcpNotify.NotifyType.CONTROL, String.Format("RTDhcpServer binds to {0}", localAddress.ToString()));
            }
            dhcpsvr.OnDiscover += discoverHandler;
            dhcpsvr.OnRequest  += requestHandler;
            dhcpsvr.OnReleased += releaseHandler;
            dhcpsvr.OnDecline  += declineHandler;
            dhcpsvr.OnInform   += informHandler;
            //dhcpsvr.SendDhcpAnswerNetworkInterface = intf;
            dhcpsvr.BroadcastAddress = IPAddress.Broadcast;

            dhcpsvr.Start();

            state = STATE_RUNNING;

            sendNotify(DhcpNotify.NotifyType.CONTROL, "RTDhcpServer is running.");
        }
コード例 #2
0
        static void Main(string[] args)
        {
            var server = new DHCPServer();

            server.ServerName      = "SharpDHCPServer";
            server.OnDataReceived += Request;
            Console.WriteLine("Running DHCP server. Press enter to stop it.");
            Console.ReadLine();
            server.Dispose();
        }
コード例 #3
0
ファイル: UnitTest1.cs プロジェクト: TFTomSun/DHCPServer
        public void Test1()
        {
            Config.InitializeEventLog();
            var configurations = DHCPServerConfigurationList.Read(Config.GetConfigurationPath());
            var config         = configurations.Single();
            var dhcpServer     = DHCPServer.FromConfig(config);

            dhcpServer.Start();
            Thread.Sleep(100000000);
        }
コード例 #4
0
        static void Main(string[] args)
        {
            var server = new DHCPServer();

            server.ServerName       = "SharpDHCPServer";
            server.OnDataReceived  += Request;
            server.BroadcastAddress = IPAddress.Parse("192.168.1.255");
            server.Start();
            Console.WriteLine("Running DHCP server. Press enter to stop it.");
            Console.ReadLine();
            server.Dispose();
        }
コード例 #5
0
        protected override void AppsInit()
        {
            foreach (NetworkInterface n in NetworkInterfaces.Values)
            {
                if (n.GetType() == typeof(GroupAdapter))
                {
                    DHCPServer s = new DHCPServer(this, n, n.LocalIP);
                    AddApp(s);
                }
            }

            RoutingTable = new SystemRoutingTable(this);
            AddApp(RoutingTable);
        }
コード例 #6
0
        static void Main(string[] args)
        {
            var lst = NetworkInterface.GetAllNetworkInterfaces();

            var eth0If = NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault(x => x.Name == "USB_ETH");
            var server = new DHCPServer();

            server.ServerName       = "SharpDHCPServer";
            server.OnDataReceived  += Request;
            server.BroadcastAddress = IPAddress.Broadcast;
            server.SendDhcpAnswerNetworkInterface = eth0If;
            server.Start();
            Console.WriteLine("Running DHCP server. Press enter to stop it.");
            Console.ReadLine();
            server.Dispose();
        }
コード例 #7
0
        static void Main(string[] args)
        {
            var server = new DHCPServer();

            server.OnDHCPDiscover += new DHCPServer.DHCPProcessDelegate(async(discovery, localEndPoint, remoteEndPoint) =>
            {
                return(await GenerateLease(discovery, localEndPoint, remoteEndPoint));
            });

            server.OnDHCPRequest += new DHCPServer.DHCPProcessDelegate(async(discovery, localEndPoint, remoteEndPoint) =>
            {
                return(await GenerateLease(discovery, localEndPoint, remoteEndPoint));
            });

            Task.Factory.StartNew(() => { server.Start(); });
            Thread.Sleep(600000);
        }
コード例 #8
0
        private void server_OnStatusChange(object sender, DHCPStopEventArgs e)
        {
            DHCPServer server = (DHCPServer)sender;

            if (server.Active)
            {
                //Log(EventLogEntryType.Information, string.Format("{0} transfers in progress", server.ActiveTransfers));
            }
            else
            {
                if (e.Reason != null)
                {
                    Log(EventLogEntryType.Error, string.Format("Stopped, reason: {0}", e.Reason));
                }
                CleanupAndRetry();
            }
        }
コード例 #9
0
        //Based on ClusterM's Sharp-DHCP-Server
        //Credit and thanks goes to ClusterM, and jogibear9988

        public void Run(IBackgroundTaskInstance taskInstance)
        {
            var server = new DHCPServer(new System.Net.IPAddress(new byte[] { 192, 168, 137, 1 }));

            server.ServerName       = "sharpDHCPWifiToEthernet";
            server.BroadcastAddress = IPAddress.Broadcast.ToString();

            BackgroundTaskDeferral deferral = taskInstance.GetDeferral();

            taskInstance.Canceled += (o, e) => { server.Dispose(); deferral.Complete(); };

            server.OnDataReceived += (sender, dhcpRequest) =>
            {
                try
                {
                    var type = dhcpRequest.GetMsgType();
                    var ip   = new System.Net.IPAddress(new byte[] { 192, 168, 137, 11 });

                    var replyOptions = new DHCPReplyOptions();
                    replyOptions.SubnetMask        = IPAddress.Parse("255.255.255.0");
                    replyOptions.DomainName        = server.ServerName;
                    replyOptions.ServerIdentifier  = IPAddress.Parse("192.168.137.1");
                    replyOptions.RouterIP          = IPAddress.Parse("192.168.137.1");
                    replyOptions.DomainNameServers = new IPAddress[]
                    { IPAddress.Parse("8.8.8.8"), IPAddress.Parse("8.8.4.4") };


                    if (type == DHCPMsgType.DHCPDISCOVER)
                    {
                        dhcpRequest.SendDHCPReply(DHCPMsgType.DHCPOFFER, ip, replyOptions);
                    }
                    if (type == DHCPMsgType.DHCPREQUEST)
                    {
                        dhcpRequest.SendDHCPReply(DHCPMsgType.DHCPACK, ip, replyOptions);
                    }
                }
                catch
                {
                }
            };

            server.Start();
        }
コード例 #10
0
 private void CleanupAndRetry()
 {
     lock (m_Lock)
     {
         if (!m_Disposed)
         {
             // stop server
             if (m_Server != null)
             {
                 m_Server.OnStatusChange -= server_OnStatusChange;
                 m_Server.OnTrace        -= server_OnTrace;
                 m_Server.Dispose();
                 m_Server = null;
             }
             // initiate retry timer
             m_RetryTimer.Change(RetryTime, Timeout.Infinite);
         }
     }
 }
コード例 #11
0
        private void Resurrect(object state)
        {
            lock (m_Lock)
            {
                if (!m_Disposed)
                {
                    try
                    {
                        m_Server                     = new DHCPServer(Program.GetClientInfoPath(m_Config.Name, m_Config.Address));
                        m_Server.EndPoint            = new IPEndPoint(IPAddress.Parse(m_Config.Address), 67);
                        m_Server.SubnetMask          = IPAddress.Parse(m_Config.NetMask);
                        m_Server.PoolStart           = IPAddress.Parse(m_Config.PoolStart);
                        m_Server.PoolEnd             = IPAddress.Parse(m_Config.PoolEnd);
                        m_Server.LeaseTime           = (m_Config.LeaseTime > 0) ? TimeSpan.FromSeconds(m_Config.LeaseTime) : Utils.InfiniteTimeSpan;
                        m_Server.OfferExpirationTime = TimeSpan.FromSeconds(Math.Max(1, m_Config.OfferTime));
                        m_Server.MinimumPacketSize   = m_Config.MinimumPacketSize;

                        List <OptionItem> options = new List <OptionItem>();
                        foreach (OptionConfiguration optionConfiguration in m_Config.Options)
                        {
                            options.Add(optionConfiguration.ConstructOptionItem());
                        }
                        m_Server.Options = options;

                        List <ReservationItem> reservations = new List <ReservationItem>();
                        foreach (ReservationConfiguration reservationConfiguration in m_Config.Reservations)
                        {
                            reservations.Add(reservationConfiguration.ConstructReservationItem());
                        }
                        m_Server.Reservations = reservations;

                        m_Server.OnStatusChange += server_OnStatusChange;
                        m_Server.OnTrace        += server_OnTrace;
                        m_Server.Start();
                    }
                    catch (Exception)
                    {
                        CleanupAndRetry();
                    }
                }
            }
        }
コード例 #12
0
ファイル: Program.cs プロジェクト: geeksonsecurity/dhcpshot
        public static async void StartServer(string interfaceIp, string targetIp)
        {
            Console.WriteLine($"Looking for interface for IP {interfaceIp}");
            var intf = NetworkInterface.GetAllNetworkInterfaces()
                       .Where(
                x => x.GetIPProperties().UnicastAddresses
                .Any(y => y.Address.Equals(IPAddress.Parse(interfaceIp)))
                ).FirstOrDefault();

            if (intf == null)
            {
                Console.WriteLine($"Interface for IP {interfaceIp} not found!");
                return;
            }
            Console.WriteLine($"Starting DHCP server on interface {intf.Name}");
            var server = new DHCPServer();

            if (targetIp == null)
            {
                var rnd      = new Random();
                var ip_bytes = interfaceIp.Split(".");
                var lastByte = int.Parse(ip_bytes[3]);
                int newByte  = rnd.Next(2, 254);
                while (newByte == lastByte)
                {
                    newByte = rnd.Next(2, 254);
                }
                ip_bytes[3] = newByte.ToString();
                targetIp    = string.Join(".", ip_bytes);
            }
            Console.WriteLine($"Client will receive IP {targetIp}");
            server.OnDataReceived += delegate(DHCPRequest dhcpRequest)
            {
                Request(dhcpRequest, IPAddress.Parse(targetIp), interfaceIp);
            };
            server.BroadcastAddress = IPAddress.Broadcast;
            server.SendDhcpAnswerNetworkInterface = intf;
            server.Start();
            Console.WriteLine("Running DHCP server... Press CTRL-C to exit");
            await LoadingIndicator();
        }
コード例 #13
0
        private void Resurrect(object state)
        {
            lock (m_Lock)
            {
                if (!m_Disposed)
                {
                    try
                    {
                        m_Server = DHCPServer.FromConfig(m_Config);

                        m_Server.OnStatusChange += server_OnStatusChange;
                        m_Server.OnTrace        += server_OnTrace;
                        m_Server.Start();
                    }
                    catch (Exception)
                    {
                        CleanupAndRetry();
                    }
                }
            }
        }
コード例 #14
0
        protected void Dispose(bool disposing)
        {
            if (disposing)
            {
                lock (m_Lock)
                {
                    if (!m_Disposed)
                    {
                        m_Disposed = true;

                        m_RetryTimer.Change(Timeout.Infinite, Timeout.Infinite);
                        m_RetryTimer.Dispose();

                        if (m_Server != null)
                        {
                            m_Server.OnStatusChange -= server_OnStatusChange;
                            m_Server.Dispose();
                            m_Server.OnTrace -= server_OnTrace;
                            m_Server          = null;
                        }
                    }
                }
            }
        }
コード例 #15
0
 public DHCPServerConfigurationWriter(TrafficHandler thToSave) : base(thToSave)
 {
     thHandler = (DHCPServer)thToSave;
 }
コード例 #16
0
        /// <summary>
        /// Constructor for the class, it initializes various objects
        /// </summary>
        /// <param name="node">Takes in a structured node</param>
        public RpcAddressResolverAndDNS(StructuredNode node, DHCPServer dhcp, MemBlock local_ip)
            : base(MemBlock.Reference(dhcp.BaseIP), MemBlock.Reference(dhcp.Netmask))
        {
            _node = node;
              _rpc = _node.Rpc;
              _dns_a = new Hashtable();
              _dns_ptr = new Hashtable();
              _ip_addr = new Hashtable();
              _addr_ip = new Hashtable();
              _blocked_addrs = new Hashtable();
              mcast_addr = new ArrayList();

              _dhcp = dhcp;
              _local_ip = local_ip;

              _rpc.AddHandler("RpcIpopNode", this);
        }
コード例 #17
0
        /// <summary>
        /// Constructor for the class, it initializes various objects
        /// </summary>
        /// <param name="node">Takes in a structured node</param>
        public ManagedAddressResolverAndDNS(StructuredNode node, DHCPServer dhcp, MemBlock local_ip, string dns_server, bool RA)
            : base(MemBlock.Reference(dhcp.BaseIP), MemBlock.Reference(dhcp.Netmask), dns_server, RA)
        {
            _node = node;
              _dns_a = new Hashtable();
              _dns_ptr = new Hashtable();
              _ip_addr = new Hashtable();
              _addr_ip = new Hashtable();
              _blocked_addrs = new Hashtable();
              mcast_addr = new ArrayList();

              _dhcp = dhcp;
              _local_ip = local_ip;
        }
コード例 #18
0
 public DHCPServerConfigurationLoader(TrafficHandler thHandler)
     : base(thHandler)
 {
     this.thHandler = (DHCPServer)thHandler;
 }