internal void Rewrite() { var oldEntries = ScrubFile(); if (_hostnameToAddress.Count > 0 || oldEntries.Count > 0) { Logger.Info("Rewriting {0}", _hostsFilePath); // We always want our own friendly name to be self pingable var ourName = Config.Instance.GetFriendlyHostname(); _hostnameToAddress[ourName] = new HostEntry(ourName, "127.0.0.1"); var addresses = new HashSet <string>(); foreach (var value in _hostnameToAddress.Values) { addresses.Add(value.Address); } foreach (var oldEntry in oldEntries) { // Add back any old host entries which don't conflict with the latest information we got from broadcasts if (!_hostnameToAddress.ContainsKey(oldEntry.HostName) && !addresses.Contains(oldEntry.Address)) { _hostnameToAddress.Add(oldEntry.HostName, oldEntry); } } try { using (var writer = new StreamWriter(_hostsFilePath, true)) { writer.WriteLine(); writer.WriteLine(); foreach (var originalLine in _hostnameToAddress.Values) { writer.WriteLine("{0,-15} {1,-20} {2,-25} {3}", originalLine.Address, originalLine.HostName, _commentFormat, originalLine.Timestamp); } } } catch (IOException ex) { Logger.Error("Error reading/writing hosts file: " + ex); } } else { Logger.Debug("No changes required"); } }
internal void AddMapping(string hostname, string address) { lock (this) { if (HostnameToAddress.ContainsKey(hostname) && HostnameToAddress[hostname].Address == address) { // We already have this mapping return; } // Check the reverse mapping to see if we're updating an existing address HostnameToAddress = HostnameToAddress.Where(pair => pair.Value.Address != address) .ToDictionary(pair => pair.Key, pair => pair.Value); Logger.Info("Adding mapping {0} -> {1}", hostname, address); HostnameToAddress[hostname] = new HostEntry(hostname, address); // Write the hosts file once events have gone quiet _debouncer.Trigger(); } }