/// <summary> /// Returns the network card configuration of the specified NIC /// </summary> /// <param name="nicName">Name of the NIC</param> /// <param name="ipAdresses">Array of IP</param> /// <param name="subnets">Array of subnet masks</param> /// <param name="gateways">Array of gateways</param> /// <param name="dnses">Array of DNS IP</param> public static void GetIP( string nicName, out string [] ipAdresses, out string [] subnets, out string [] gateways, out string [] dnses ) { IList<Win32_NetworkAdapterConfiguration> networkCollection = null; NetworkAdapterConfiguration config = null; config = new NetworkAdapterConfiguration(); networkCollection = config.SelectAll(); ipAdresses = null; subnets = null; gateways = null; dnses = null; foreach (Win32_NetworkAdapterConfiguration netconfig in networkCollection) { // Make sure this is a IP enabled device. Not something like memory card or VM Ware if (netconfig.IPEnabled) { if( netconfig.Description == nicName ) { ipAdresses = netconfig.IPAddress; subnets = netconfig.IPSubnet; gateways = netconfig.DefaultIPGateway; dnses = netconfig.DNSServerSearchOrder; } } } }
/// <summary> /// Set's the DNS Server of the local machine /// </summary> /// <param name="nicDescription">The full description of the network interface class</param> /// <param name="dnsServers">Comma seperated list of DNS server addresses</param> /// <remarks>Requires a reference to the System.Management namespace</remarks> public static bool SetNameservers(string nicDescription, string[] dnsServers, bool restart = false) { using (ManagementClass networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration")) { using (ManagementObjectCollection networkConfigs = networkConfigMng.GetInstances()) { foreach (ManagementObject mboDNS in networkConfigs.Cast <ManagementObject>().Where(mo => (bool)mo["IPEnabled"] && (string)mo["Description"] == nicDescription)) { // NAC class was generated by opening a developer console and entering: // mgmtclassgen Win32_NetworkAdapterConfiguration -p NetworkAdapterConfiguration.cs // See: http://blog.opennetcf.com/2008/06/24/disableenable-network-connections-under-vista/ using (NetworkAdapterConfiguration config = new NetworkAdapterConfiguration(mboDNS)) { if (config.SetDNSServerSearchOrder(dnsServers) == 0) { RestartNetworkAdapter(nicDescription); } } } } } return(false); }
public IHttpActionResult AddNetworkInterface(string networkInterfaceName, string ipAddress, string subnetMask) { // Validate params if (string.IsNullOrWhiteSpace(ipAddress) || !IPAddress.TryParse(ipAddress, out IPAddress ipAddressObj)) { return(BadRequest($"Unknown format of {nameof(ipAddress)}")); } if (string.IsNullOrWhiteSpace(subnetMask) || !IPAddress.TryParse(subnetMask, out IPAddress subnetMaskObj)) { return(BadRequest($"Unknown format of {nameof(subnetMask)}")); } var ipAddressNormalized = ipAddressObj.ToString(); if (string.IsNullOrWhiteSpace(networkInterfaceName)) { return(BadRequest($"{nameof(networkInterfaceName)} is empty")); } // Load network interface var networkInterface = NetworkAdapterService.GetOne(networkInterfaceName); if (networkInterface == null) { return(new ResponseMessageResult(Request.CreateErrorResponse(HttpStatusCode.NotFound, $"Such Network Interface '{networkInterfaceName}' not found"))); } if (string.IsNullOrWhiteSpace(networkInterface.Description)) { return(new ResponseMessageResult(Request.CreateErrorResponse(HttpStatusCode.NotFound, $"Network Interface cannot be found if Description missed"))); } if (NetworkAdapterService.IsIPv4Exists(networkInterface, ipAddressNormalized)) { return(new ResponseMessageResult(Request.CreateErrorResponse(HttpStatusCode.Found, $"This IP Address '{ipAddressNormalized}' already added"))); } // Try adding IPv4 var(message, success) = new NetworkAdapterConfiguration(networkInterface).AddStaticIPv4(ipAddressObj, subnetMaskObj); if (success) { return(Ok(NetworkAdapterService.GetOneModel(networkInterface.Name))); } else { return(new ResponseMessageResult(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, message))); } }
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { var ipAddresses = new StringCollection { IPAddress.Any.ToString(), IPAddress.Loopback.ToString() }; foreach (NetworkAdapterConfiguration netConfig in NetworkAdapterConfiguration.GetInstances("IPEnabled=1")) { ipAddresses.AddRange(netConfig.IPAddress); } return(new StandardValuesCollection(ipAddresses)); }
/// <summary> /// Returns the list of Network Interfaces installed /// </summary> /// <returns>Array list of string</returns> public static ArrayList GetNICNames() { ArrayList nicNames = new ArrayList(); IList<Win32_NetworkAdapterConfiguration> networkCollection = null; NetworkAdapterConfiguration config = null; config = new NetworkAdapterConfiguration(); networkCollection = config.SelectAll(); foreach (Win32_NetworkAdapterConfiguration netconfig in networkCollection) { if (netconfig.IPEnabled) { nicNames.Add( netconfig.Description); } } return nicNames; }
static List <NetworkAdapterConfiguration> GetNetAdapterConfig() { List <NetworkAdapterConfiguration> l = new List <NetworkAdapterConfiguration>(); foreach (ManagementObject mo in new ManagementObjectSearcher("Select * from Win32_NetworkAdapterConfiguration").Get()) { if (mo["InterfaceIndex"] == null) { continue; } NetworkAdapterConfiguration nc = new NetworkAdapterConfiguration(); nc.Caption = (string)mo["Caption"]; nc.Description = (string)mo["Description"]; nc.DHCPEnabled = mo["DHCPEnabled"] == null ? true : (bool)mo["DHCPEnabled"]; nc.DHCPLeaseExpires = mo["DHCPLeaseExpires"] == null ? (DateTime?)null : ManagementDateTimeConverter.ToDateTime(Convert.ToString(mo["DHCPLeaseExpires"])); nc.DHCPLeaseObtained = mo["DHCPLeaseObtained"] == null ? (DateTime?)null : ManagementDateTimeConverter.ToDateTime(Convert.ToString(mo["DHCPLeaseObtained"])); nc.DHCPServer = (string)mo["DHCPServer"]; nc.DNSDomain = (string)mo["DNSDomain"]; nc.DefaultIPGateway = mo["DefaultIPGateway"] == null ? null : new List <string>((string[])mo["DefaultIPGateway"]); nc.DNSDomainSuffixSearchOrder = mo["DNSDomainSuffixSearchOrder"] == null ? null : new List <string>((string[])mo["DNSDomainSuffixSearchOrder"]); nc.DNSServerSearchOrder = mo["DNSServerSearchOrder"] == null ? null : new List <string>((string[])mo["DNSServerSearchOrder"]); nc.IPAddress = mo["IPAddress"] == null ? null : new List <string>((string[])mo["IPAddress"]); nc.IPSubnet = mo["IPSubnet"] == null ? null : new List <string>((string[])mo["IPSubnet"]); nc.DNSHostName = (string)mo["DNSHostName"]; nc.InterfaceIndex = (int)(uint)mo["InterfaceIndex"]; nc.IPEnabled = mo["IPEnabled"] == null ? false : (bool)mo["IPEnabled"]; nc.MACAddress = (string)mo["MACAddress"]; nc.ServiceName = (string)mo["ServiceName"]; nc.SettingsID = (string)mo["SettingID"]; nc.WINSEnableLMHostsLookup = mo["WINSEnableLMHostsLookup"] == null ? false : (bool)mo["WINSEnableLMHostsLookup"]; nc.WINSHostLookupFile = (string)mo["WINSHostLookupFile"]; nc.WINSScopeID = (string)mo["WINSScopeID"]; nc.WINSPrimaryServer = (string)mo["WINSPrimaryServer"]; nc.WINSSecondaryServer = (string)mo["WINSSecondaryServer"]; l.Add(nc); } return(l); }
public NetworkAdapter(NetworkAdapterConfiguration configuration, PlatformDependencies dependencies) { _configuration = configuration; _dependencies = dependencies; }
/// <summary> /// The start tunnel. /// </summary> /// <returns> /// The <see cref="bool"/>. /// </returns> public static bool StartTunnel() { if (!CommonLibrary.Common.IsValidIpSubnet(IpSubnet)) { return(false); } AdapterAddressRange = CommonLibrary.Common.MergeIpIntoIpSubnet( AdapterAddressRange, IpSubnet, IPAddress.Parse("10.0.0.1")); IPAddress addressGateWay = CommonLibrary.Common.MergeIpIntoIpSubnet( AdapterAddressRange, IpSubnet, IPAddress.Parse("10.0.0.2")); NetworkAdapter net = TapAdapter.InstallAnAdapter(TunnelName); if (net == null) { return(false); } if ( !Tun2Socks.StartTun2Socks( net, AdapterAddressRange, IpSubnet, addressGateWay, SocksProxyEndPoint)) { return(false); } NetworkAdapterConfiguration netconfig = net.GetNetworkConfiguration(); if (netconfig == null) { return(false); } int timeout = 30; timeout = timeout / 3; string dnsString = string.Empty; if (AutoDnsResolving && AutoDnsResolvingAddress != null) { Dns2Socks.StartDns2Socks(AutoDnsResolvingAddress, SocksProxyEndPoint); dnsString = SocksProxyEndPoint.Address.ToString(); } else if (DnsResolvingAddress != null && DnsResolvingAddress2 != null) { dnsString = DnsResolvingAddress + "," + DnsResolvingAddress2; } else if (DnsResolvingAddress != null) { dnsString = DnsResolvingAddress.ToString(); } else if (DnsResolvingAddress2 != null) { dnsString = DnsResolvingAddress2.ToString(); } while (true) { if (netconfig.SetIpAddresses(AdapterAddressRange.ToString(), IpSubnet.ToString()) && netconfig.SetDnsSearchOrder(dnsString)) { break; } if (timeout == 0) { return(false); } timeout--; Thread.Sleep(3000); } IP4RouteTable.AddChangeRouteRule( IPAddress.Parse("0.0.0.0"), addressGateWay, 2, IPAddress.Parse("0.0.0.0"), (int)net.InterfaceIndex); int lowestMetric = 1000; IP4RouteTable me = null; List <IP4RouteTable> internetRules = new List <IP4RouteTable>(); foreach (IP4RouteTable r in IP4RouteTable.GetCurrentTable().ToArray()) { if (r.Destination == "0.0.0.0") { if (r.InterfaceIndex == net.InterfaceIndex) { me = r; } else { internetRules.Add(r); if (lowestMetric > r.Metric1) { lowestMetric = r.Metric1; } } } } if (me == null) { return(false); } foreach (IP4RouteTable ip4 in IP4RouteTable.GetCurrentTable() .Where( ip4 => ExceptionIPs.Any( ip => ip4.Destination != null && ip4.NextHop != null && ip4.Mask != null && ip4.Destination == ip.ToString() && ip4.Mask == "255.255.255.255" && ip4.NextHop != "0.0.0.0"))) { ip4.RemoveRouteRule(); } int des = 0; if (me.Metric1 >= lowestMetric) { des = (me.Metric1 - lowestMetric) + 1; } foreach (IP4RouteTable r in internetRules) { if (des > 0) { r.SetMetric1(r.Metric1 + des); } if (string.IsNullOrEmpty(r.NextHop)) { continue; } foreach (IPAddress ip in ExceptionIPs) { // if (IP4RouteTable.GetBestInterfaceIndexForIP(ip) == net.InterfaceIndex) IP4RouteTable.AddChangeRouteRule(ip, IPAddress.Parse(r.NextHop), 1, null, r.InterfaceIndex); } } FlashDnsCache(); return(true); }
public RESTStatus ListNetData(SQLLib sql, object dummy, NetworkConnectionInfo ni, string id) { if (ni.HasAcl(ACLFlags.ChangeServerSettings) == false) { ni.Error = "Access denied"; ni.ErrorID = ErrorFlags.AccessDenied; return(RESTStatus.Denied); } if (string.IsNullOrWhiteSpace(id) == true) { ni.Error = "Invalid data"; ni.ErrorID = ErrorFlags.InvalidData; return(RESTStatus.NotFound); } lock (ni.sqllock) { if (Computers.MachineExists(sql, id) == false) { ni.Error = "Invalid data"; ni.ErrorID = ErrorFlags.InvalidData; return(RESTStatus.NotFound); } } LstNetData = new ListNetworkAdapterConfiguration(); LstNetData.Items = new List <NetworkAdapterConfiguration>(); LstNetData.MachineID = id; lock (ni.sqllock) { SqlDataReader dr = sql.ExecSQLReader("SELECT * FROM networkconfig WHERE MachineID=@mid", new SQLParam("@mid", id)); while (dr.Read()) { NetworkAdapterConfiguration n = new NetworkAdapterConfiguration(); sql.LoadIntoClass(dr, n); LstNetData.Items.Add(n); } dr.Close(); } foreach (NetworkAdapterConfiguration n in LstNetData.Items) { n.IPAddress = new List <string>(); n.IPSubnet = new List <string>(); n.DefaultIPGateway = new List <string>(); n.DNSDomainSuffixSearchOrder = new List <string>(); n.DNSServerSearchOrder = new List <string>(); lock (ni.sqllock) { SqlDataReader dr = sql.ExecSQLReader("select * from NetworkConfigSuppl WHERE MachineID=@mid AND InterfaceIndex=@i order by Type,[Order]", new SQLParam("@mid", id), new SQLParam("@i", n.InterfaceIndex)); while (dr.Read()) { switch (Convert.ToInt32(dr["Type"])) { case 1: n.IPAddress.Add(Convert.ToString(dr["Data"])); break; case 2: n.IPSubnet.Add(Convert.ToString(dr["Data"])); break; case 3: n.DefaultIPGateway.Add(Convert.ToString(dr["Data"])); break; case 4: n.DNSDomainSuffixSearchOrder.Add(Convert.ToString(dr["Data"])); break; case 5: n.DNSServerSearchOrder.Add(Convert.ToString(dr["Data"])); break; } } dr.Close(); } } return(RESTStatus.Success); }
private static NetworkAdapterConfiguration GetNetworkAdapter(this AdapterData adapter) { return(NetworkAdapterConfiguration.GetInstances().Cast <NetworkAdapterConfiguration>().FirstOrDefault(z => z.InterfaceIndex == adapter.networkAdapter.InterfaceIndex)); }
/// <summary> /// Enable DHCP on the NIC /// </summary> /// <param name="nicName">Name of the NIC</param> public static void SetDHCP( string nicName ) { IList<Win32_NetworkAdapterConfiguration> networkCollection = null; NetworkAdapterConfiguration config = null; config = new NetworkAdapterConfiguration(); networkCollection = config.SelectAll(); foreach (Win32_NetworkAdapterConfiguration netconfig in networkCollection) { // Make sure this is a IP enabled device. Not something like memory card or VM Ware if (netconfig.IPEnabled) { if (netconfig.Description == nicName) { netconfig.EnableDHCP(); netconfig.SetDNSServerSearchOrder(new string[]{null}); } } } }
/// <summary> /// Set IP for the specified network card name /// </summary> /// <param name="nicName">Caption of the network card</param> /// <param name="IpAddresses">Comma delimited string containing one or more IP</param> /// <param name="SubnetMask">Subnet mask</param> /// <param name="Gateway">Gateway IP</param> /// <param name="DnsSearchOrder">Comma delimited DNS IP</param> public static void SetIP( string nicName, string IpAddresses, string SubnetMask, string Gateway, string DnsSearchOrder) { IList<Win32_NetworkAdapterConfiguration> networkCollection = null; NetworkAdapterConfiguration config = null; config = new NetworkAdapterConfiguration(); networkCollection = config.SelectAll(); foreach(Win32_NetworkAdapterConfiguration netconfig in networkCollection) { // Make sure this is a IP enabled device. Not something like memory card or VM Ware if( netconfig.IPEnabled ) { if( netconfig.Description == nicName ) { netconfig.EnableStatic(new string[] { IpAddresses }, new string[] { SubnetMask }); netconfig.SetGateways(null, null); netconfig.SetDNSServerSearchOrder(null); //netconfig.SetGateways(new string[] { "192.168.2.2" }, new ushort[] { 1 }); //netconfig.SetDNSServerSearchOrder(new string[] { "205.34.23.12" }); // netconfig.EnableDHCP(); // netconfig.SetDNSServerSearchOrder(null); break; } } } }