Exemple #1
0
        static void Main(string[] args)
        {
            // Discover DHCP Servers
            try
            {
                foreach (var dhcpServer in DhcpServer.Servers.ToList())
                {
                    DumpDhcpInfo(dhcpServer);
                    Console.WriteLine();
                }
            }
            catch (DhcpServerException ex) when(ex.ApiError == "DDS_NO_DS_AVAILABLE")
            {
                Console.WriteLine("No DHCP Servers could be automatically discovered");
            }

            // Directly Connect to DHCP Server
            var server = DhcpServer.Connect("localhost");

            DumpDhcpInfo(server);

            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine();
            Console.WriteLine("<Press any key to continue>");
            Console.ReadKey(true);
        }
Exemple #2
0
        static void Main(string[] args)
        {
            // Directly Connect to DHCP Server
            var server = DhcpServer.Connect("localhost");

            CreateScope(server);
        }
Exemple #3
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 name_server, bool forward_queries) :
            base(MemBlock.Reference(dhcp.BaseIP), MemBlock.Reference(dhcp.Netmask),
                 name_server, forward_queries)
        {
            _node          = node;
            _dns_a         = new Dictionary <string, string>();
            _dns_ptr       = new Dictionary <string, string>();
            _ip_addr       = new Dictionary <MemBlock, Address>();
            _addr_ip       = new Dictionary <Address, MemBlock>();
            _blocked_addrs = new Dictionary <Address, MemBlock>();
            mcast_addr     = new List <Address>();
            _tx_counters   = new Dictionary <Address, int>();
            _rx_counters   = new Dictionary <Address, int>();

            _dhcp            = dhcp;
            _local_ip        = local_ip;
            _sync            = new object();
            _udp_translators = new IProtocolTranslator <UdpPacket>[] {
                new MDnsTranslator(local_ip),
                new SipTranslator(local_ip),
                new SsdpTranslator(local_ip)
            };
            _resolver = new WriteOnce <IDnsResolver>();
        }
        public HttpResponseMessage scopelist()
        {
            // Connect to DHCP Server
            var       dhcpServer = DhcpServer.Connect(dhcp_host);
            ScopeList mylist     = new ScopeList();

            // Retrieving scopes list and add each one to response
            foreach (var scope in dhcpServer.Scopes)
            {
                if (scope.State == DhcpServerScopeState.Enabled || scope.State == DhcpServerScopeState.EnabledSwitched)
                {
                    mylist.scopes.Add(new Scope(scope.Address.ToString()));
                }
            }
            // Returning Json string from mylist omiting null values
            return(new HttpResponseMessage()
            {
                Content = new StringContent(
                    JsonConvert.SerializeObject(mylist, new JsonSerializerSettings {
                    NullValueHandling = NullValueHandling.Ignore
                }),
                    Encoding.UTF8,
                    "application/json"
                    )
            });
        }
Exemple #5
0
        static void Main(string[] args)
        {
            var        logger = new ConsoleLogger();
            DhcpServer server;

            try
            {
                var serverSettings = new DhcpServerSettings
                {
                    ServerIp = IPAddress.Parse(args[0])
                };
                server = new DhcpServer(serverSettings);
                logger.AddSource(server);
                server.Discovered += ShowMessage;
                server.Requested  += ShowMessage;
                server.Start();
                while (true)
                {
                    ;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Exemple #6
0
        static void ConfigureFailover(DhcpServer dhcpServer, DhcpServerScope scope)
        {
            // Sample snippets only

            // creating a failover relationship
            //  - matching scopes are created on the partner server
            //      including all settings supported by this library

            // create with an existing relationship
            var existingRelationship = dhcpServer.FailoverRelationships.GetRelationship("DHCPServer1-DHCPServer2");

            scope.ConfigureFailover(existingRelationship);

            // create with a new relationship (name and settings are default)
            var partnerServer = DhcpServer.Connect("MyPartnerDhcpServer");
            var relationship  = scope.ConfigureFailover(partnerServer, "A Shared Secret", DhcpServerFailoverMode.HotStandby);

            // create with a new relationship (define a name)
            var namedRelationship = scope.ConfigureFailover(partnerServer: partnerServer,
                                                            name: "Relationship Name",
                                                            sharedSecret: "A Shared Secret",
                                                            mode: DhcpServerFailoverMode.HotStandby);

            // create with a new relationship (define settings)
            var customizedRelationship = scope.ConfigureFailover(partnerServer: partnerServer,
                                                                 name: "Relationship Name",
                                                                 sharedSecret: "A Shared Secret",
                                                                 mode: DhcpServerFailoverMode.HotStandby,
                                                                 modePercentage: 10,
                                                                 maximumClientLeadTime: TimeSpan.FromHours(2),
                                                                 stateSwitchInterval: TimeSpan.FromMinutes(10));

            // create load-balance failover
            var loadBalancedRelationship = scope.ConfigureFailover(partnerServer, "A Shared Secret", DhcpServerFailoverMode.LoadBalance);

            // retrieve scope failover relationship
            var scopeRelationship = scope.GetFailoverRelationship();

            // replicate failover
            //  - all supported settings are pushed to the partner server
            scope.ReplicateFailoverPartner();

            // replicate all scopes in a failover relationship
            relationship.ReplicateRelationship();

            // deconfigure failover
            //  - scopes are removed from the partner server
            //      (whichever isn't being used to deconfigure the failover)
            scope.DeconfigureFailover();

            // enumerate scopes associated with a relationship
            foreach (var relationshipScope in relationship.Scopes)
            {
                Console.WriteLine(relationshipScope);
            }

            // delete failover relationship
            //  (all associated scopes must be deconfigured first)
            relationship.Delete();
        }
 public privateNetManager()
 {
     Peers       = new Dictionary <string, NetworkPeerService>();
     dhcpManager = new DhcpServer();
     dhcpManager.ClearAcls();
     dhcpManager.AllowAny     = true;
     dhcpManager.OnNewClient += new EventHandler <OnNewDHCPClientEvent>(dhcpManager_OnNewClient);
 }
Exemple #8
0
    public static DhcpServer GetInstance(string localIPStr)
    {
        DhcpServer instace = new DhcpServer(localIPStr);

        if (instace.localIP == null)
        {
            instace = null;
        }
        return(instace);
    }
Exemple #9
0
    private static DhcpServer ConvertFromNative(DHCP_SERVER_INFO nativeServer)
    {
        var server = new DhcpServer
        {
            IpAddress  = new DhcpIpAddress(nativeServer.ServerAddress),
            Name       = nativeServer.ServerName,
            AdLocation = nativeServer.DsLocation
        };

        return(server);
    }
Exemple #10
0
        private static void ScanIpScope(string dhcpServerIp)
        {
            DhcpServer             dhcpServer       = Dhcp.DhcpServer.Connect(dhcpServerIp);
            List <DhcpServerScope> dhcpServerScopes = dhcpServer.Scopes.ToList();



            foreach (DhcpServerScope dhcpServerScope in dhcpServerScopes)
            {
                foreach (DhcpServerClient dhcpServerClient in dhcpServerScope.Clients)
                {
                    ScanIp(dhcpServerClient.IpAddress.ToString(), dhcpServerClient.Name);
                    Console.WriteLine($"{dhcpServerClient.IpAddress} - {dhcpServerClient.Name}");
                }
            }
        }
Exemple #11
0
            public void Save(WidgetConfig config)
            {
                config["HostName"]       = HostName.ToString();
                config["LogonDomain"]    = LogonDomain.ToString();
                config["IpAddress"]      = IpAddress.ToString();
                config["MachineDomain"]  = MachineDomain.ToString();
                config["MacAddress"]     = MacAddress.ToString();
                config["BootTime"]       = BootTime.ToString();
                config["Cpu"]            = Cpu.ToString();
                config["DefaultGateway"] = DefaultGateway.ToString();
                config["DhcpServer"]     = DhcpServer.ToString();
                config["DnsServer"]      = DnsServer.ToString();
                config["FreeSpace"]      = FreeSpace.ToString();

                config["LabelColor"] = ColorTranslator.ToHtml(LabelColor);
                config["ValueColor"] = ColorTranslator.ToHtml(ValueColor);
            }
Exemple #12
0
        static void Main(string[] args)
        {
            // Discover DHCP Servers
            foreach (var dhcpServer in DhcpServer.Servers.ToList())
            {
                DumpDhcpInfo(dhcpServer);
                Console.WriteLine();
            }

            // Directly Connect to DHCP Server
            var server = DhcpServer.Connect("192.168.1.1");

            DumpDhcpInfo(server);

            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine();
            Console.WriteLine("<Press any key to continue>");
            Console.ReadKey(true);
        }
        public HttpResponseMessage exclude(String scope)
        {
            // Connect to DHCP Server
            var     dhcpServer           = DhcpServer.Connect(dhcp_host);
            Boolean bFound               = false;
            ScopeExcludeRangeList mylist = new ScopeExcludeRangeList();

            // Browsing through scopes
            foreach (var searchscope in dhcpServer.Scopes)
            {
                if (searchscope.Address.ToString().Equals(scope))
                {
                    // Found the scope given in parameter
                    bFound = true;
                    // Browsing through exclude ranges for this scope
                    foreach (var myex in searchscope.ExcludedIpRanges)
                    {
                        // Adding start and end values from this exclude range
                        mylist.excluderanges.Add(new ScopeRange(myex.StartAddress.ToString(), myex.EndAddress.ToString()));
                    }
                }
            }

            if (bFound)
            {
                // Returning Json string from mylist omiting null values
                return(new HttpResponseMessage()
                {
                    Content = new StringContent(
                        JsonConvert.SerializeObject(mylist, new JsonSerializerSettings {
                        NullValueHandling = NullValueHandling.Ignore
                    }),
                        Encoding.UTF8,
                        "application/json"
                        )
                });
            }
            else
            {
                // Scope given in parameter was not found
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Scope not found"));
            }
        }
Exemple #14
0
        /// <summary>Someone told us we didn't have a mapping... let's fix that.</summary>
        protected override bool MappingMissing(MemBlock ip)
        {
            if (!base.MappingMissing(ip))
            {
                return(false);
            }

            // Easiest approach is to simply update the mapping...
            DhcpServer dhcp_server = GetDhcpServer();

            try {
                dhcp_server.RequestLease(ip, true, AppNode.Node.Address.ToString(),
                                         _ipop_config.AddressData.Hostname);
            } catch (Exception e) {
                ProtocolLog.WriteIf(IpopLog.DhcpLog, e.Message);
            }

            return(true);
        }
        public HttpResponseMessage range(String scope)
        {
            // Connect to DHCP Server
            var     dhcpServer = DhcpServer.Connect(dhcp_host);
            Boolean bFound     = false;
            String  mys        = "";
            String  mye        = "";

            // Browsing through scopes
            foreach (var myscope in dhcpServer.Scopes)
            {
                if (myscope.Address.ToString().Equals(scope))
                {
                    // Found the scope given in parameter
                    bFound = true;
                    // Store start and end of this scope range
                    mys = myscope.IpRange.StartAddress.ToString();
                    mye = myscope.IpRange.EndAddress.ToString();
                }
            }
            if (bFound)
            {
                // Creating range from previous start and end
                ScopeRange myrange = new ScopeRange(mys, mye);
                // Returning Json string from myrange omiting null values
                return(new HttpResponseMessage()
                {
                    Content = new StringContent(
                        JsonConvert.SerializeObject(myrange, new JsonSerializerSettings {
                        NullValueHandling = NullValueHandling.Ignore
                    }),
                        Encoding.UTF8,
                        "application/json"
                        )
                });
            }
            else
            {
                // Scope given in parameter was not found
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Scope not found"));
            }
        }
Exemple #16
0
        /// <summary> Occassionally nodes will get a true return from a allocation
        /// attempt, in order to prevent this, we reissue all dhcp requests after
        /// getting "connected" to the overlay.</summary>
        protected void StateChangeHandler(Node n, Node.ConnectionState state)
        {
            List <MemBlock> ips = null;

            lock (_sync) {
                if (state == Node.ConnectionState.Connected)
                {
                    if (_connected)
                    {
                        return;
                    }
                    AppNode.Node.StateChangeEvent -= StateChangeHandler;
                    _connected = true;
                }
                else
                {
                    return;
                }

                ips = new List <MemBlock>(_ip_to_ether.Keys.Count);
                foreach (MemBlock ip in _ip_to_ether.Keys)
                {
                    ips.Add(ip);
                }
            }

            WaitCallback callback = delegate(object o) {
                // Get a new Dhcp server so we get new state!
                DhcpServer dhcp_server = GetDhcpServer();
                foreach (MemBlock ip in ips)
                {
                    try {
                        dhcp_server.RequestLease(ip, true, AppNode.Node.Address.ToString(),
                                                 _ipop_config.AddressData.Hostname);
                    } catch (Exception e) {
                        ProtocolLog.WriteIf(IpopLog.DhcpLog, e.Message);
                    }
                }
            };

            ThreadPool.QueueUserWorkItem(callback, null);
        }
    /// <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 name_server, bool forward_queries) :
      base(MemBlock.Reference(dhcp.BaseIP), MemBlock.Reference(dhcp.Netmask),
          name_server, forward_queries)
    {
      _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;
      _sync = new object();
      _udp_translators = new IProtocolTranslator<UdpPacket>[] {
        new MDnsTranslator(local_ip),
        new SipTranslator(local_ip),
        new SsdpTranslator(local_ip)
      };
    }
Exemple #18
0
        static void DumpDhcpInfo(DhcpServer dhcpServer)
        {
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("{0} (v{1}.{2} - {3})", dhcpServer.Name, dhcpServer.VersionMajor, dhcpServer.VersionMinor, dhcpServer.IpAddress);

            // Configuration
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine(" Configuration:");
            Console.ForegroundColor = ConsoleColor.Gray;
            var config = dhcpServer.Configuration;

            Console.WriteLine("{0,30}: {1}", "Api Protocol Support", config.ApiProtocolSupport.ToString());
            Console.WriteLine("{0,30}: {1}", "Database Name", config.DatabaseName);
            Console.WriteLine("{0,30}: {1}", "Database Path", config.DatabasePath);
            Console.WriteLine("{0,30}: {1}", "Backup Path", config.BackupPath);
            Console.WriteLine("{0,30}: {1}", "Backup Interval", config.BackupInterval);
            Console.WriteLine("{0,30}: {1}", "Database Logging Enabled", config.DatabaseLoggingEnabled);
            Console.WriteLine("{0,30}: {1}", "Cleanup Interval", config.DatabaseCleanupInterval);

            // Audit Logging
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine(" Audit Log:");
            Console.ForegroundColor = ConsoleColor.Gray;
            var auditLog = dhcpServer.AuditLog;

            Console.WriteLine("{0,30}: {1}", "Log Directory", auditLog.AuditLogDirectory);
            Console.WriteLine("{0,30}: {1}", "Disk Check Interval", auditLog.DiskCheckInterval);
            Console.WriteLine("{0,30}: {1}", "Max Log Files Size", auditLog.MaxLogFilesSize);
            Console.WriteLine("{0,30}: {1}", "Min Space On Disk", auditLog.MinSpaceOnDisk);

            // DNS Settings
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine(" DNS Settings:");
            Console.ForegroundColor = ConsoleColor.Gray;
            var dnsSettings = dhcpServer.DnsSettings;

            Console.WriteLine("{0,44}: {1}", "Dynamic DNS Updates Enabled", dnsSettings.DynamicDnsUpdatesEnabled);
            Console.WriteLine("{0,44}: {1}", "Dynamic DNS Updates Only When Requested", dnsSettings.DynamicDnsUpdatedOnlyWhenRequested);
            Console.WriteLine("{0,44}: {1}", "Dynamic DNS Updates Always", dnsSettings.DynamicDnsUpdatedAlways);
            Console.WriteLine("{0,44}: {1}", "Discard Records When Leases Deleted", dnsSettings.DiscardRecordsWhenLeasesDeleted);
            Console.WriteLine("{0,44}: {1}", "Update Records for Down-Level Clients", dnsSettings.UpdateRecordsForDownLevelClients);
            Console.WriteLine("{0,44}: {1}", "Disable Dynamic PTR Record Updates", dnsSettings.DisableDynamicPtrRecordUpdates);

            // Binding Elements
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine(" Binding Elements:");
            Console.ForegroundColor = ConsoleColor.Gray;
            foreach (var be in dhcpServer.BindingElements.ToList())
            {
                Console.WriteLine("   {0} {1}", be.InterfaceDescription, be.InterfaceGuidId.ToString());
                Console.WriteLine("{0,30}: {1}", "Unmodifiable Endpoint", be.CantModify);
                Console.WriteLine("{0,30}: {1}", "Is Bound", be.IsBound);
                Console.WriteLine("{0,30}: {1}", "Adapter Primary IP Address", be.AdapterPrimaryIpAddress);
                Console.WriteLine("{0,30}: {1}", "Adapter Subnet Address", be.AdapterSubnetAddress);
            }

            // Enum Default Options
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine(" All Options:");
            Console.ForegroundColor = ConsoleColor.Gray;
            foreach (var option in dhcpServer.AllOptions.ToList())
            {
                Console.WriteLine("   {0}", option.ToString());
            }

            // Enum Default Options
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine(" Default Options ({0}):", dhcpServer.DefaultVendorClassName);
            Console.ForegroundColor = ConsoleColor.Gray;
            foreach (var option in dhcpServer.Options.ToList())
            {
                Console.WriteLine("   {0}", option.ToString());
            }

            // Enum Default Global Option Values
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine(" Global Option Values:");
            Console.ForegroundColor = ConsoleColor.Gray;
            foreach (var value in dhcpServer.AllGlobalOptionValues.ToList())
            {
                Console.WriteLine("   {0}", value.ToString());
            }

            // Enum Classes
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine(" Classes:");
            Console.ForegroundColor = ConsoleColor.Gray;
            Console.WriteLine("{0,30}: {1}", "Default Vendor Class Name", dhcpServer.DefaultVendorClassName);
            Console.WriteLine("{0,30}: {1}", "Default User Class Name", dhcpServer.DefaultUserClassName);

            foreach (var c in dhcpServer.Classes.ToList())
            {
                Console.WriteLine("   {0}", c.Name);
                Console.WriteLine("      Comment: {0}", c.Comment);
                Console.WriteLine("      Type: {0}", c.IsVendorClass ? "Vendor Class" : "User Class");
                Console.WriteLine("      Data: {0}", c.DataText);

                // Enum Class Options
                Console.WriteLine("      Options");
                foreach (var option in c.Options.ToList())
                {
                    Console.WriteLine("         {0}", option.ToString());
                }
            }

            // Server Clients
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("      Server Clients:");
            Console.ForegroundColor = ConsoleColor.Gray;
            foreach (var client in dhcpServer.Clients.ToList())
            {
                Console.WriteLine("          {0}", client);
            }

            // Enum Scopes
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine(" Scopes:");
            Console.ForegroundColor = ConsoleColor.Gray;
            foreach (var scope in dhcpServer.Scopes.ToList())
            {
                Console.WriteLine("   {0}", scope.Address);
                Console.WriteLine("      IP Range: {0}", scope.IpRange);
                Console.WriteLine("      Mask: {0}", scope.Mask);
                Console.WriteLine("      State: {0}", scope.State);
                Console.WriteLine("      Name: {0}", scope.Name);
                Console.WriteLine("      Comment: {0}", scope.Comment);
                Console.WriteLine("      Primary Host: {0}", scope.PrimaryHostIpAddress);
                Console.WriteLine("      Lease Duration: {0}", scope.LeaseDuration);
                Console.WriteLine("      Delay Offer: {0} milliseconds", scope.TimeDelayOffer.TotalMilliseconds);
                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine("      Excluded IP Ranges:");
                Console.ForegroundColor = ConsoleColor.Gray;
                foreach (var ipRange in scope.ExcludedIpRanges)
                {
                    Console.WriteLine("        {0}", ipRange);
                }
                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine("      Options:");
                Console.ForegroundColor = ConsoleColor.Gray;
                foreach (var value in scope.AllOptionValues.ToList())
                {
                    Console.WriteLine("        {0}", value.ToString());
                }
                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine("      Reservations:");
                Console.ForegroundColor = ConsoleColor.Gray;
                foreach (var reservation in scope.Reservations.ToList())
                {
                    Console.WriteLine("        {0}", reservation);
                    Console.WriteLine("        Client: {0}", reservation.Client);
                    Console.WriteLine("          Options:");
                    Console.ForegroundColor = ConsoleColor.Gray;
                    foreach (var value in reservation.OptionValues.ToList())
                    {
                        Console.WriteLine("            {0}", value.ToString());
                    }
                }
                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine("      Clients:");
                Console.ForegroundColor = ConsoleColor.Gray;
                foreach (var client in scope.Clients.ToList())
                {
                    Console.WriteLine("        {0}", client);
                }
            }
        }
Exemple #19
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main(String[] args)
        {
            DhcpServerConfigurationSection dhcpConfig = ConfigurationManager.GetSection("dhcpServer") as DhcpServerConfigurationSection;
            DhcpServer server = new DhcpServer();

            if (dhcpConfig != null)
            {
                if (dhcpConfig.NetworkInterface >= 0)
                {
                    server.DhcpInterface = NetworkInterface.GetAllNetworkInterfaces()[dhcpConfig.NetworkInterface];
                }

                server.StartAddress  = InternetAddress.Parse(dhcpConfig.StartAddress.Trim());
                server.EndAddress    = InternetAddress.Parse(dhcpConfig.EndAddress.Trim());
                server.Subnet        = InternetAddress.Parse(dhcpConfig.Subnet.Trim());
                server.Gateway       = InternetAddress.Parse(dhcpConfig.Gateway.Trim());
                server.LeaseDuration = dhcpConfig.LeaseDuration;
                server.OfferTimeout  = dhcpConfig.OfferTimeout;
                server.DnsSuffix     = dhcpConfig.DnsSuffix;

                foreach (InternetAddressElement dnsServer in dhcpConfig.DnsServers)
                {
                    server.DnsServers.Add(InternetAddress.Parse(dnsServer.IPAddress.Trim()));
                }

                foreach (PhysicalAddressElement macAllow in dhcpConfig.MacAllowList)
                {
                    if (macAllow.PhysicalAddress.Trim() == "*")
                    {
                        server.ClearAcls();
                        server.AllowAny = true;
                        break;
                    }
                    else
                    {
                        server.AddAcl(PhysicalAddress.Parse(macAllow.PhysicalAddress), false);
                    }
                }

                foreach (PhysicalAddressElement macDeny in dhcpConfig.MacDenyList)
                {
                    if (macDeny.PhysicalAddress.Trim() == "*")
                    {
                        server.ClearAcls();
                        server.AllowAny = false;
                        break;
                    }
                    else
                    {
                        server.AddAcl(PhysicalAddress.Parse(macDeny.PhysicalAddress), true);
                    }
                }

                foreach (PhysicalAddressMappingElement macReservation in dhcpConfig.MacReservationList)
                {
                    server.addReservation(macReservation.PhysicalAddress, macReservation.IPAddress);
                }
            }

            if (args.Length > 0 && (ContainsSwitch(args, "console") || ContainsSwitch(args, "debug")))
            {
                if (ContainsSwitch(args, "debug"))
                {
                    Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));
                }

                DhcpHost host = new DhcpHost(server);
                host.ManualStart(args);

                Console.WriteLine("DHCP Service Running.");
                Console.WriteLine("Hit [Enter] to Terminate.");

                Console.ReadLine();

                host.ManualStop();
            }
            else
            {
                ServiceBase[] ServicesToRun;

                ServicesToRun = new ServiceBase[] { new DhcpHost(server) };

                ServiceBase.Run(ServicesToRun);
            }
        }
        public HttpResponseMessage lease(String scope)
        {
            // Connect to DHCP Server
            var            dhcpServer = DhcpServer.Connect(dhcp_host);
            Boolean        bFound     = false;
            ScopeLeaseList mylist     = new ScopeLeaseList();

            // Browsing through scopes
            foreach (var searchscope in dhcpServer.Scopes)
            {
                if (searchscope.Address.ToString().Equals(scope))
                {
                    // Found the scope given in parameter
                    bFound = true;
                    // MS DHCP return AddressState as full byte (state, Name protection and DNS informations)
                    // We just want the first 2 bits : state so logical and with 3 (0000011)
                    byte allactive = 3;
                    // Get active DHCP client leases
                    var activeClients = searchscope.Clients
                                        .Where(c => (Convert.ToByte(c.AddressState) & allactive) == 1)
                                        .Where(c => c.Type == DhcpServerClientTypes.DHCP);

                    // Browsing through leases
                    foreach (var client in activeClients)
                    {
                        // Retrieving client name
                        String myname = "";
                        if (client.Name == null)
                        {
                            // If no name, send something anyway
                            myname = "EMPTYNAME";
                        }
                        else
                        {
                            myname = client.Name;
                        }
                        // Retrieving client hardware address
                        String myhw = client.HardwareAddress.ToString();

                        // Applying Adrezo formatting
                        if (adrezo_format)
                        {
                            // Keeping only the host part in name
                            int firstpoint = myname.IndexOf('.');
                            if (firstpoint > 0)
                            {
                                myname = myname.Substring(0, firstpoint);
                            }
                            // Limit client name to 20 chars
                            if (myname.Length > 20)
                            {
                                myname = myname.Substring(0, 20);
                            }
                            // Removing : from mac address string
                            myhw = myhw.Replace(":", "");
                            //Limit mac to 12 chars
                            if (myhw.Length > 12)
                            {
                                myhw = myhw.Substring(0, 12);
                            }
                        }

                        // Add this lease with all attributes ip/mac/expiration date/name
                        mylist.leases.Add(new Lease(client.IpAddress.ToString(), myhw, client.LeaseExpires.ToString("yyyy-MM-dd HH:mm:ss"), myname));
                    }
                }
            }

            if (bFound)
            {
                // Returning Json string from mylist omiting null values
                return(new HttpResponseMessage()
                {
                    Content = new StringContent(
                        JsonConvert.SerializeObject(mylist, new JsonSerializerSettings {
                        NullValueHandling = NullValueHandling.Ignore
                    }),
                        Encoding.UTF8,
                        "application/json"
                        )
                });
            }
            else
            {
                // Scope given in parameter was not found
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Scope not found"));
            }
        }
        public HttpResponseMessage reserve(String scope)
        {
            // Connect to DHCP Server
            var            dhcpServer = DhcpServer.Connect(dhcp_host);
            Boolean        bFound     = false;
            ScopeLeaseList mylist     = new ScopeLeaseList();

            // Browsing through scopes
            foreach (var searchscope in dhcpServer.Scopes)
            {
                if (searchscope.Address.ToString().Equals(scope))
                {
                    // Found the scope given in parameter
                    bFound = true;
                    // Browsing through reservations for this scope
                    foreach (var myresa in searchscope.Reservations)
                    {
                        // Retrieving client name
                        String myname = "";
                        if (myresa.Client.Name == null)
                        {
                            // If no name, send something anyway
                            myname = "EMPTYNAME";
                        }
                        else
                        {
                            myname = myresa.Client.Name;
                        }
                        // Retrieving client hardware address
                        String myhw = myresa.HardwareAddress.ToString();

                        // Applying Adrezo formatting
                        if (adrezo_format)
                        {
                            // Keeping only the host part in name
                            int firstpoint = myname.IndexOf('.');
                            if (firstpoint > 0)
                            {
                                myname = myname.Substring(0, firstpoint);
                            }
                            // Limit client name to 20 chars
                            if (myname.Length > 20)
                            {
                                myname = myname.Substring(0, 20);
                            }
                            // Removing : from mac address string
                            myhw = myhw.Replace(":", "");
                            // Limit mac to 12 chars
                            if (myhw.Length > 12)
                            {
                                myhw = myhw.Substring(0, 12);
                            }
                        }

                        // Reserve Mac Address doesn't have to be removed
                        // Add this reservation with no expiration date (null), just ip/mac/name
                        mylist.leases.Add(new Lease(myresa.IpAddress.ToString(), myhw, null, myname));
                    }
                }
            }

            if (bFound)
            {
                // Returning Json string from mylist omiting null values
                return(new HttpResponseMessage()
                {
                    Content = new StringContent(
                        JsonConvert.SerializeObject(mylist, new JsonSerializerSettings {
                        NullValueHandling = NullValueHandling.Ignore
                    }),
                        Encoding.UTF8,
                        "application/json"
                        )
                });
            }
            else
            {
                // Scope given in parameter was not found
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Scope not found"));
            }
        }
Exemple #22
0
        static void Main(string[] args)
        {
            DhcpServerConfigurationSection dhcpConfig = ConfigurationManager.GetSection("dhcpServer") as DhcpServerConfigurationSection;
            DhcpServer server = new DhcpServer();

            if (dhcpConfig != null)
            {
                if (dhcpConfig != null)
                {
                    if (dhcpConfig.NetworkInterface >= 0)
                    {
                        server.DhcpInterface = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[dhcpConfig.NetworkInterface];
                    }

                    server.StartAddress  = InternetAddress.Parse(dhcpConfig.StartAddress.Trim());
                    server.EndAddress    = InternetAddress.Parse(dhcpConfig.EndAddress.Trim());
                    server.Subnet        = InternetAddress.Parse(dhcpConfig.Subnet.Trim());
                    server.Gateway       = InternetAddress.Parse(dhcpConfig.Gateway.Trim());
                    server.LeaseDuration = dhcpConfig.LeaseDuration;
                    server.OfferTimeout  = dhcpConfig.OfferTimeout;
                    server.DnsSuffix     = dhcpConfig.DnsSuffix;

                    server.StartAddress = InternetAddress.Parse("2.0.4.1");
                    server.EndAddress   = InternetAddress.Parse("2.0.4.10");
                    server.Subnet       = InternetAddress.Parse("255.255.255.0");

                    foreach (InternetAddressElement dnsServer in dhcpConfig.DnsServers)
                    {
                        server.DnsServers.Add(InternetAddress.Parse(dnsServer.IPAddress.Trim()));
                    }

                    foreach (PhysicalAddressElement macAllow in dhcpConfig.MacAllowList)
                    {
                        if (macAllow.PhysicalAddress.Trim() == "*")
                        {
                            server.ClearAcls();
                            server.AllowAny = true;
                            break;
                        }
                        else
                        {
                            server.AddAcl(PhysicalAddress.Parse(macAllow.PhysicalAddress), false);
                        }
                    }

                    foreach (PhysicalAddressElement macDeny in dhcpConfig.MacDenyList)
                    {
                        if (macDeny.PhysicalAddress.Trim() == "*")
                        {
                            server.ClearAcls();
                            server.AllowAny = false;
                            break;
                        }
                        else
                        {
                            server.AddAcl(PhysicalAddress.Parse(macDeny.PhysicalAddress), true);
                        }
                    }

                    foreach (PhysicalAddressMappingElement macReservation in dhcpConfig.MacReservationList)
                    {
                        server.addReservation(macReservation.PhysicalAddress, macReservation.IPAddress);
                    }
                }

                server.Start();
                Console.WriteLine("DHCP Service Running.");
                Console.WriteLine("Hit [Enter] to Terminate.");

                Console.ReadLine();
            }
        }
Exemple #23
0
        public DhcpHost(DhcpServer server)
        {
            InitializeComponent();

            this.m_Server = server;
        }
    /// <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 name_server, bool forward_queries) :
      base(MemBlock.Reference(dhcp.BaseIP), MemBlock.Reference(dhcp.Netmask),
          name_server, forward_queries)
    {
      _node = node;
      _dns_a = new Dictionary<string, string>();
      _dns_ptr = new Dictionary<string, string>();
      _ip_addr = new Dictionary<MemBlock, Address>();
      _addr_ip = new Dictionary<Address, MemBlock>();
      _blocked_addrs = new Dictionary<Address, MemBlock>();
      mcast_addr = new List<Address>();
      _tx_counters = new Dictionary<Address, int>();
      _rx_counters = new Dictionary<Address, int>();

      _dhcp = dhcp;
      _local_ip = local_ip;
      _sync = new object();
      _udp_translators = new IProtocolTranslator<UdpPacket>[] {
        new MDnsTranslator(local_ip),
        new SipTranslator(local_ip),
        new SsdpTranslator(local_ip)
      };
      _resolver = new WriteOnce<IDnsResolver>();
    }