public NetInterface(NetworkInterface adapterIn) { // set up the adapter adapter = adapterIn; stats = adapter.GetIPv4Statistics(); // set up the logging logPath = Path.Combine("logs", Path.Combine(adapter.Description, adapter.GetPhysicalAddress().ToString(), adapter.Id)); logHandler = new LogHandler(logPath); loadDataInstant(DateTime.UtcNow.Ticks); // set up the data tracking dataTransferStart = currentTicks(); bytesInSession = stats.BytesReceived; bytesOutSession = stats.BytesSent; properties = adapter.GetIPProperties(); //Console.WriteLine(adapter.Name + " " + adapter.Description + " " + adapter.OperationalStatus); Tracker = new Tracker(logHandler); }
/// <summary> /// Set the network mask via M553 /// </summary> /// <param name="index">Index of the network interface</param> /// <param name="netmask">Subnet mask</param> /// <returns>Configuration result</returns> public static async Task <string> ManageGateway(int index, IPAddress gateway, IPAddress dnsServer) { NetworkInterface iface = Get(index); if (gateway != null || dnsServer != null) { return(await DHCP.SetIPAddress(iface.Name, null, null, gateway, dnsServer)); } if (iface.OperationalStatus == OperationalStatus.Up) { gateway = (from item in iface.GetIPProperties().GatewayAddresses where item.Address.AddressFamily == AddressFamily.InterNetwork select item.Address).FirstOrDefault() ?? IPAddress.Any; dnsServer = (from item in iface.GetIPProperties().DnsAddresses where item.AddressFamily == AddressFamily.InterNetwork select item).FirstOrDefault() ?? IPAddress.Any; } else { gateway = await DHCP.GetConfiguredGateway(iface.Name); dnsServer = await DHCP.GetConfiguredDNSServer(iface.Name); } StringBuilder builder = new(); builder.AppendLine($"Gateway: {gateway}"); builder.Append($"DNS server: {dnsServer}"); return(builder.ToString()); }
/// <summary> /// Initializes a new instance of the <see cref="IfMtu"/> class. /// </summary> /// <param name="index">The index.</param> /// <param name="networkInterface">The network interface.</param> public IfMtu(int index, NetworkInterface networkInterface) : base("1.3.6.1.2.1.2.2.1.4.{0}", index) { if (networkInterface.Supports(NetworkInterfaceComponent.IPv4)) { var pv4InterfaceProperties = networkInterface.GetIPProperties().GetIPv4Properties(); _data = new Integer32(pv4InterfaceProperties == null ? -1 : pv4InterfaceProperties.Mtu); } else { _data = new Integer32(networkInterface.GetIPProperties().GetIPv6Properties().Mtu); } }
internal NetworkInterface(NetworkInterfaceInformation info) { Information = info; IPv4Index = -1; IPv6Index = -1; if (info.Supports(NetworkInterfaceComponent.IPv4)) { IPv4Index = info.GetIPProperties().GetIPv4Properties().Index; } if (info.Supports(NetworkInterfaceComponent.IPv6)) { IPv6Index = info.GetIPProperties().GetIPv6Properties().Index; } Index = Interlocked.Increment(ref NextIndex); }
internal NetworkInterface(NetworkInterfaceInformation info) { Information = info; IPv4Index = -1; IPv6Index = -1; if (info.Supports(NetworkInterfaceComponent.IPv4)) { IPv4Index = info.GetIPProperties().GetIPv4Properties().Index; } if (info.Supports(NetworkInterfaceComponent.IPv6)) { IPv6Index = info.GetIPProperties().GetIPv6Properties().Index; } Index = Interlocked.Increment(ref NextIndex); }
public static NetworkInterfaceInfo GetNetworkInterfaceInfo (NetworkInterface networkInterface) { if (networkInterface == null) { return new NetworkInterfaceInfo (IPAddress.Any, 0); } var properties = networkInterface.GetIPProperties (); var ipv4_properties = properties.GetIPv4Properties (); if (ipv4_properties == null) { throw new ArgumentException ("The specified network interface does not support IPv4.", "networkInterface"); } var host_name = Dns.GetHostName (); foreach (var address in properties.UnicastAddresses) { string addressHostname = null; try { addressHostname = Dns.GetHostEntry(address.Address).HostName; } catch(SocketException) { } if (address.Address.AddressFamily == AddressFamily.InterNetwork && addressHostname == host_name) { return new NetworkInterfaceInfo (address.Address, ipv4_properties.Index); } } throw new ArgumentException (string.Format ( "The specified network interface does not have a suitable address for the local hostname: {0}.", host_name), "networkInterface"); }
public long getSentPackets( NetworkInterface conn ) { IPInterfaceProperties properties = conn.GetIPProperties(); IPv4InterfaceStatistics ipstat = conn.GetIPv4Statistics(); return ipstat.BytesSent; }
/* * Get received traffic * returns String[] array */ public long getReceivedTraffic( NetworkInterface conn ) { IPInterfaceProperties properties = conn.GetIPProperties(); IPv4InterfaceStatistics ipstat = conn.GetIPv4Statistics(); return ipstat.BytesReceived; }
/// <summary> /// Checks local IP. /// </summary> /// <param name="ipAddr">IP Address</param> /// <returns>True if specified IP is equals to local one.</returns> private static bool CheckIpAddress(string ipAddr) { System.Net.NetworkInformation.NetworkInterface[] netInterfaces = null; try { netInterfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces(); } catch (NetworkInformationException ex) { //Logger.Log(ex.Message, EventLogEntryType.ERROR); } if (netInterfaces != null && !string.IsNullOrEmpty(ipAddr)) { for (int i = 0; i < netInterfaces.Length; i++) { System.Net.NetworkInformation.NetworkInterface netInterface = netInterfaces[i]; if (!netInterface.Supports(NetworkInterfaceComponent.IPv4)) { continue; } foreach (UnicastIPAddressInformation addr in netInterface.GetIPProperties().UnicastAddresses) { if (ipAddr == addr.Address.ToString()) { return(true); } } } } return(false); }
public static UpdateType GetUpdateType(NetworkInterface oldInterface, NetworkInterface newInterface) { if (oldInterface.Id != newInterface.Id) return UpdateType.Name; IPInterfaceProperties oldIPProps = oldInterface.GetIPProperties(); IPInterfaceProperties newIPProps = newInterface.GetIPProperties(); if (HasIPChanged(oldIPProps, newIPProps)) return UpdateType.IP; if (HasNetmaskChanged(oldIPProps, newIPProps)) return UpdateType.Netmask; if (HasGatewayChanged(oldIPProps, newIPProps)) return UpdateType.Gateway; if (HasDHCPChanged(oldIPProps, newIPProps)) return UpdateType.DHCP; if (HasDNSChanged(oldIPProps, newIPProps)) return UpdateType.DNS; if (!oldIPProps.Equals(newIPProps)) return UpdateType.Other; return UpdateType.None; }
private static void RunAsConsoleApp() { if (!ServersWatcher.CredentialsCorrect) { // In case of empty credentials - show error message and exit Console.WriteLine("Error connecting to EC cloud - invalid connect data"); } else { // Get list of running instances List <RunningInstance> instances = ServersWatcher.Instances; // Put it to console foreach (RunningInstance inst in instances) { Console.WriteLine("{0} {1}", ServersWatcher.GetInstanceName(inst), inst.PrivateIpAddress); } } #if (DEBUG) System.Net.NetworkInformation.NetworkInterface[] netInterfaces = null; try { netInterfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces(); } catch //(NetworkInformationException ex) { } if (netInterfaces != null) { for (int i = 0; i < netInterfaces.Length; i++) { System.Net.NetworkInformation.NetworkInterface netInterface = netInterfaces[i]; if (!netInterface.Supports(NetworkInterfaceComponent.IPv4)) { continue; } foreach (UnicastIPAddressInformation addr in netInterface.GetIPProperties().UnicastAddresses) { Console.WriteLine(addr.Address); } } } Console.WriteLine("\nService test starts."); Console.WriteLine("Start..."); ConsoleStartTest(); Console.WriteLine("Press any key..."); Console.ReadKey(); Console.WriteLine("Resume..."); ConsoleInstanceTest(); Console.WriteLine("Service test ended.\n"); #endif Console.WriteLine("press any key to exit"); Console.ReadKey(); }
public static IPAddress GetGatewayAddressFromNetInterface(NetworkInterface intf) { IPInterfaceProperties ipProps = intf.GetIPProperties(); if (ipProps == null) return IPAddress.Any; if (ipProps.GatewayAddresses == null || ipProps.GatewayAddresses.Count == 0) return IPAddress.Any; return ipProps.GatewayAddresses[0].Address; }
public Boolean isNetworkConnected(NetworkInterface net) { Boolean bReturn = false; if (net != null && net.OperationalStatus == OperationalStatus.Up && net.GetIPProperties() != null && net.Description != null && net.NetworkInterfaceType != NetworkInterfaceType.Loopback) { bReturn = true; } Helper.doLog("isNetworkConnected " + net.Id + " = " + bReturn, Properties.Settings.Default.DebugMode); return bReturn; }
private void SetSocketOptionsForNic(NetworkInterface nic) { nic.GetIPProperties() .UnicastAddresses .Where(unicast => unicast.Address.AddressFamily == AddressFamily.InterNetwork) .ToList() .ForEach( address => socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse(AllHostsMulticastIP), address.Address))); }
public NetworkConfigModel(NetworkInterface ni) { var ip = ni.GetIPProperties(); this.IpAddress = ip.UnicastAddresses.Count > 0 ? ip.UnicastAddresses[0].Address.ToString() : ""; this.Gateway = ip.GatewayAddresses.Count > 0 ? ip.GatewayAddresses[0].Address.ToString() : ""; this.Subnet = ip.UnicastAddresses.Count > 0 ? ip.UnicastAddresses[0].IPv4Mask.ToString() : ""; this.DNSList = ip.DnsAddresses.Count > 0 ? string.Join(";", ip.DnsAddresses.Select(dn => dn.ToString())) : ""; this.NetworkName = ni.Name; this.InterfaceName = ni.Description; this.UseDHCP = string.IsNullOrEmpty(this.IpAddress) && string.IsNullOrEmpty(this.Gateway); }
List <IPAddress> CollectAddresses(MNetworkInterface inf) { var ret = new List <IPAddress> (); foreach (UnicastIPAddressInformation addr in inf.GetIPProperties().UnicastAddresses) { ret.Add(addr.Address); } return(ret); }
private static string GetIpv4StringFromNetworkAdapter(string result, NetworkInterface adapter) { if (adapter == null) return null; foreach (UnicastIPAddressInformation ip in adapter.GetIPProperties().UnicastAddresses) { if (ip.Address.AddressFamily == AddressFamily.InterNetwork) { result = ip.Address.ToString(); } } return result; }
/// <summary> /// Returns the destination IP we'll later want to delete /// </summary> /// <param name="adapter"></param> /// <param name="hostOrIp"></param> /// <returns></returns> public static string AddRoute(NetworkInterface adapter, string hostOrIp ) { IPAddress remoteAddress = null; if (IPAddress.TryParse(hostOrIp, out remoteAddress)) { // already an IP address } else { // resolve it try { IPAddress[] addresslist = Dns.GetHostAddresses(hostOrIp); if (addresslist.Length == 0) { MessageBox.Show("Can't resolve " + hostOrIp); } else { remoteAddress = addresslist[0]; } } catch (Exception ex) { MessageBox.Show(ex.Message, "Error"); return null; } } IPInterfaceProperties properties = adapter.GetIPProperties(); try { if (remoteAddress != null) { GatewayIPAddressInformationCollection gateways = properties.GatewayAddresses; for (int j = 0; j < gateways.Count; j++) { GatewayIPAddressInformation gateway = gateways[j]; // Add the route entry to the route table to solve the Windows XP issue. AddRoute(gateway.Address.ToString(), remoteAddress.ToString()); } } } catch (Exception ex) { //DebugEx.WriteException(ex); MessageBox.Show(ex.Message, "Error"); return null; } return remoteAddress.ToString(); }
public static IPAddress GetGatewayAddress(NetworkInterface iface) { if (iface == null) return IPAddress.Parse(BadIP); IPInterfaceProperties ipProperties = iface.GetIPProperties(); foreach (GatewayIPAddressInformation ip in ipProperties.GatewayAddresses) if (ip.Address.AddressFamily == AddressFamily.InterNetwork) return ip.Address; return IPAddress.Parse(BadIP); }
public static IPAddress GetDNSAddress(NetworkInterface iface) { if (iface == null) return IPAddress.Parse(BadIP); IPInterfaceProperties ipProperties = iface.GetIPProperties(); foreach (IPAddress ip in ipProperties.DnsAddresses) if (ip.AddressFamily == AddressFamily.InterNetwork) return ip; return IPAddress.Parse(BadIP); }
/// <summary> /// Discovers network interfaces and addresses. /// </summary> /// <param name="networkInterface">The network interface to search for addresses to listen to.</param> /// <param name="bindings">The hints for the search and where to store the results.</param> /// <returns>The status of the discovery.</returns> public static string DiscoverNetwork(NetworkInterface networkInterface, Bindings bindings) { var sb = new StringBuilder("("); // this part is very .NET-specific var unicastIpc = networkInterface.GetIPProperties().UnicastAddresses; foreach (var addressInfo in unicastIpc) { if (addressInfo == null) { continue; } IPAddress inet = addressInfo.Address; // getting the broadcast address var ipv4Mask = addressInfo.IPv4Mask; // 0.0.0.0 in case of IPv6 var broadcastAddress = inet.GetBroadcastAddress(ipv4Mask); if (broadcastAddress != null && !bindings.BroadcastAddresses.Contains(broadcastAddress)) { bindings.BroadcastAddresses.Add(broadcastAddress); } if (bindings.ContainsAddress(inet)) { continue; } // ignore, if a user specifies an address and inet is not part of it if (!bindings.AnyAddresses) { if (!bindings.Addresses.Contains(inet)) { continue; } } if (inet.IsIPv4() && bindings.IsIPv4) { sb.Append(inet).Append(", "); bindings.AddFoundAddress(inet); } else if (inet.IsIPv6() && bindings.IsIPv6) { sb.Append(inet).Append(", "); bindings.AddFoundAddress(inet); } } sb.Remove(sb.Length - 1, 1); return sb.Append(")").ToString(); }
public String GetIpAddress(NetworkInterface networkInterface) { if (networkInterface.GetIPProperties() == null || networkInterface.GetIPProperties().UnicastAddresses == null) return null; UnicastIPAddressInformationCollection unicastAddresses = networkInterface.GetIPProperties().UnicastAddresses; foreach (UnicastIPAddressInformation unicastAddress in unicastAddresses) { try { if (!IsIPv6Address(unicastAddress.Address)) { String address = unicastAddress.Address.ToString(); return address; } } catch (Exception) { } } return null; }
public static IPAddress GetIP(NetworkInterface iface) { if (iface == null) return IPAddress.Parse(BadIP); IPInterfaceProperties ipProperties = iface.GetIPProperties(); foreach (UnicastIPAddressInformation ip in ipProperties.UnicastAddresses) if (ip.Address.AddressFamily == AddressFamily.InterNetwork && (ip.PrefixOrigin != PrefixOrigin.WellKnown && ip.SuffixOrigin != SuffixOrigin.LinkLayerAddress)) return ip.Address; return IPAddress.Parse(BadIP); }
public static IPAddress GetSubnetMask(NetworkInterface iface) { if (iface == null) return IPAddress.Parse(BadIP); IPInterfaceProperties ipProperties = iface.GetIPProperties(); foreach (UnicastIPAddressInformation ip in ipProperties.UnicastAddresses) if (ip.Address.AddressFamily == AddressFamily.InterNetwork && (ip.PrefixOrigin == PrefixOrigin.Manual || ip.SuffixOrigin == SuffixOrigin.Manual)) return ip.IPv4Mask; return IPAddress.Parse(BadIP); }
private static string[] GetAdapterIpAdresses(NetworkInterface adapter){ if (adapter == null) { throw new Exception("No network interfaces found"); } IPInterfaceProperties adapterProperties = adapter.GetIPProperties(); string[] s = null; IPAddressCollection dnsServers = adapterProperties.DnsAddresses; if (dnsServers != null) { s = new string[dnsServers.Count]; int i = 0; foreach (IPAddress dns in dnsServers) { s[i] = dns.ToString(); i++; } } return s; }
public static List <IAdapter> GetAdapters() { //IPAddress[] ipAdresses=Dns.Resolve(Dns.GetHostName()).AddressList; //IPAddress[] ipAdresses=Dns.GetHostEntry(Dns.GetHostName()).AddressList; NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); List <IAdapter> adapters = new List <IAdapter>(nics.Length); foreach (NetworkInterface nic in nics) { foreach (UnicastIPAddressInformation unicastIpInfo in nic.GetIPProperties().UnicastAddresses) { if (unicastIpInfo.Address != null && !unicastIpInfo.Address.IsIPv6LinkLocal) { adapters.Add(new SocketAdapter(nic, unicastIpInfo.Address)); } } //adapters.Add(new SocketAdapter(nic)); } return(adapters); }
protected void Page_Load(object sender, EventArgs e) { System.Net.NetworkInformation.NetworkInterface[] nics = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces(); System.Net.NetworkInformation.NetworkInterface adapter = nics[0]; System.Net.NetworkInformation.IPInterfaceProperties properties = adapter.GetIPProperties(); Startup_Util.UserMac = adapter.GetPhysicalAddress().ToString(); System.Net.IPHostEntry host; host = System.Net.Dns.GetHostByAddress(Request.ServerVariables["REMOTE_HOST"]); Startup_Util.UserPC = host.HostName; Startup_Util.UserIP = Request.ServerVariables["REMOTE_HOST"]; Response.Cache.SetCacheability(HttpCacheability.ServerAndNoCache); String ST = Startup_Util.DcryptionPWD(Request.QueryString[0].ToString()); string[] ARY; ARY = ST.Split('~'); string[] ARY1; ARY1 = ARY[0].Split('|'); Startup_Util.SSO_DB = ARY1[9].ToString(); //SINGLE SIGN ON CONNECTION STRING Startup_Util.SPDS_DB = ARY1[10].ToString(); //SPDS CONNECTION STRING Session["EXP_PAGE"] = ARY1[8].ToString(); Session["CompleteInformation"] = ARY1[5].ToString() + " | " + ARY1[6].ToString() + " | "; Label1.Text = Session["CompleteInformation"].ToString(); Session["LOG_CODE"] = ARY1[4].ToString(); Session["U_NAME"] = ARY1[5].ToString(); //I1.Attributes["src"] = "../MasterPage/Default2.aspx"; if (SSO_Control1.LoginStatus(Session["LOG_CODE"].ToString()) == 0) { Response.Redirect(Session["EXP_PAGE"].ToString()); } else { SSO_Control1.GearUp(ARY1[3].ToString(), ARY1[4].ToString()); } }
/// <summary> /// Set and/or report the network mask via M553 /// </summary> /// <param name="index">Index of the network interface</param> /// <param name="netmask">Subnet mask</param> /// <returns>Configuration result</returns> public static async Task <string> ManageNetmask(int index, IPAddress netmask) { NetworkInterface iface = Get(index); if (netmask != null) { return(await DHCP.SetIPAddress(iface.Name, null, netmask, null, null)); } if (iface.OperationalStatus == OperationalStatus.Up) { UnicastIPAddressInformation ipInfo = (from unicastAddress in iface.GetIPProperties().UnicastAddresses where unicastAddress.Address.AddressFamily == AddressFamily.InterNetwork select unicastAddress).FirstOrDefault(); netmask = (ipInfo != null) ? ipInfo.IPv4Mask : IPAddress.Any; } else { netmask = await DHCP.GetConfiguredNetmask(iface.Name); } return($"Net mask: {netmask}"); }
public NetworkConnectionInfo(NetworkInterface ntwkInterface) { try { ntwkInfo = new Dictionary <string, IPAddress[]>(); if (ntwkInterface == null) { return; } this.nic = new NetworkInterfaceInternal(ntwkInterface); var ipProps = ntwkInterface.GetIPProperties(); foreach (var name in PropertyNames.GetIPAddressPropertyNames()) { ntwkInfo[name] = GetAddress(name, ipProps); } foreach (var addr in ipProps.UnicastAddresses) { var pre = addr.PrefixOrigin != NetInfo.PrefixOrigin.Manual; var suf = addr.SuffixOrigin != NetInfo.SuffixOrigin.Manual; _autoAssignedAddress = pre && suf; if (_autoAssignedAddress) { break; } } _dnsSuffix = ipProps.DnsSuffix; _initializedSuccessfully = true; } catch { _initializedSuccessfully = false; } }
internal void Fill(NetworkInterface ni) { NetworkInterface = ni; IpProperties = ni.GetIPProperties(); try { Ipv4Properties = IpProperties.GetIPv4Properties(); } catch (Exception) { Ipv4Properties = null; } try { Ipv6Properties = IpProperties.GetIPv6Properties(); } catch (Exception) { Ipv6Properties = null; } LastUpdate = DateTime.Now; }
private void traceBtn_Click(object sender, EventArgs e) { EndPoint theEndPoint = null; foreach (EndPoint ep in endpoints) { if (ep.ToString().Equals(addrComboBox.Text)) { theEndPoint = ep; break; } } if (theEndPoint == null) { theEndPoint = new EndPoint(addrComboBox.Text); addrComboBox.Items.Add(theEndPoint); endpoints.Add(theEndPoint); } hostOrIp = theEndPoint.HostOrIp; // start traceroute if not already running, otherwise kill it. if (!tracertBackgroundWorker.IsBusy) { // save user input here nTraces = (int)nTraceUpDown.Value; traceInterval = (double)traceIntUpDown.Value; tStart = DateTime.Now; tEnd = DateTime.Now; networkInterface = getInterface((string)listBoxNetworkInterface.SelectedItem); if (networkInterface != null) { // set the route routeToDestination = NetworkInterfaceUtils.AddRoute(networkInterface, hostOrIp); IPInterfaceProperties properties = networkInterface.GetIPProperties(); GatewayIPAddressInformationCollection gateways = properties.GatewayAddresses; gateway = gateways[0]; // just use the first one } // clear any previously logged data dates.Clear(); pings.Clear(); // start the traceroute in a separate thread tracertBackgroundWorker.RunWorkerAsync(); // update form traceBtn.Text = "Stop"; lblTarget.Text = hostOrIp; lblStartTime.Text = tStart.ToString() + " to"; lblEndTime.Visible = true; lblEndTime.Text = tEnd.ToString(); progressBar1.Visible = true; } else if (tracertBackgroundWorker.IsBusy) { tracertBackgroundWorker.CancelAsync(); traceBtn.Text = "Stopping..."; traceBtn.Enabled = false; // Delete the route if (routeToDestination != null) { NetworkInterfaceUtils.RemoveRoute(routeToDestination); } } }
private string interfaceTooltip(NetworkInterface adapter) { StringBuilder sb = new StringBuilder(); if (!adapter.OperationalStatus.Equals(OperationalStatus.Up)) { sb.AppendLine("** Status " + adapter.OperationalStatus + " **"); } sb.AppendLine("Name\t\t: " + adapter.Name); //sb.AppendLine("Id\t\t: " + adapter.Id); sb.AppendLine("Type\t\t: " + adapter.NetworkInterfaceType); sb.AppendLine("Description\t: " + adapter.Description); UnicastIPAddressInformationCollection unicastIPC = adapter.GetIPProperties().UnicastAddresses; foreach (UnicastIPAddressInformation unicast in unicastIPC) { sb.AppendLine(unicast.Address.AddressFamily + "\t: " + unicast.Address); } return sb.ToString(); }
internal static CommsInterface FromNativeInterface(NetworkInterface nativeInterface) { var ip = nativeInterface .GetIPProperties() .UnicastAddresses .FirstOrDefault(a => a.Address.AddressFamily == AddressFamily.InterNetwork); var gateway = nativeInterface .GetIPProperties() .GatewayAddresses .Where(a => a.Address.AddressFamily == AddressFamily.InterNetwork) .Select(a => a.Address.ToString()) .FirstOrDefault(); var netmask = ip != null ? GetSubnetMask(ip) : null; // implemented natively for each .NET platform var broadcast = (ip != null && netmask != null) ? ip.Address.GetBroadcastAddress(netmask).ToString() : null; return new CommsInterface { NativeInterfaceId = nativeInterface.Id, NativeIpAddress = ip != null ? ip.Address : null, Name = nativeInterface.Name, IpAddress = ip != null ? ip.Address.ToString() : null, GatewayAddress = gateway, BroadcastAddress = broadcast, ConnectionStatus = nativeInterface.OperationalStatus.ToCommsInterfaceStatus(), NativeInterface = nativeInterface }; }
/// <summary> /// Returns a local unicast IP address for the specified network interface. /// </summary> /// <param name="iface">The network interface.</param> /// <param name="addressFamily">The address family.</param> /// <returns>The IP address.</returns> public static IPAddress GetLocalUnicastAddress(NetworkInterface iface, AddressFamily addressFamily) { // Get the IP properties. IPInterfaceProperties ipProperties = iface.GetIPProperties(); // Get the unicast IP address information. UnicastIPAddressInformation information = ipProperties.UnicastAddresses.Where(info => info.IsDnsEligible && info.Address.AddressFamily == addressFamily).FirstOrDefault(); // Return null. return information != null ? information.Address : null; }
/// <summary> /// Get the ipv4 address for a specific network adapted /// </summary> /// <param name="ipInterface">NetworkInterface class to check for ipv4 address</param> /// <returns></returns> public static string GetAdapterIPAddress(NetworkInterface ipInterface) { IPInterfaceProperties ipProperties = ipInterface.GetIPProperties(); foreach (var ip in ipProperties.UnicastAddresses) { if ((ipInterface.OperationalStatus == OperationalStatus.Up) && (ip.Address.AddressFamily == AddressFamily.InterNetwork)) { return ip.Address.ToString(); } } return ""; }
private System.Net.IPAddress getLocalSameNetworkIP(string deviceIP) { string ipString = "127.0.0.1"; System.Net.IPAddress iPAddress = System.Net.IPAddress.Parse(deviceIP); System.Net.NetworkInformation.NetworkInterface[] allNetworkInterfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces(); for (int i = 0; i < allNetworkInterfaces.Length; i++) { System.Net.NetworkInformation.NetworkInterface networkInterface = allNetworkInterfaces[i]; if (networkInterface.NetworkInterfaceType == System.Net.NetworkInformation.NetworkInterfaceType.Wireless80211 || networkInterface.NetworkInterfaceType == System.Net.NetworkInformation.NetworkInterfaceType.Ethernet) { foreach (System.Net.NetworkInformation.UnicastIPAddressInformation current in networkInterface.GetIPProperties().UnicastAddresses) { if (current.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork && current.IPv4Mask != null && (iPAddress.Address & current.IPv4Mask.Address) == (current.Address.Address & current.IPv4Mask.Address)) { return(current.Address); } } } } return(System.Net.IPAddress.Parse(ipString)); }
internal NetAdapterInfo(NetworkInterface nic, int order) { m_Name = "{0}::{1}".Args(nic.Id, nic.Name); m_Order = order; m_Description = nic.Description; m_ReceiveOnly = nic.IsReceiveOnly; m_AdapterType = nic.NetworkInterfaceType.ToString(); m_Status = nic.OperationalStatus.ToString(); m_Speed = nic.Speed; m_IPv4Support = nic.Supports( NetworkInterfaceComponent.IPv4 ); m_IPv6Support = nic.Supports( NetworkInterfaceComponent.IPv6 ); var addrs = nic.GetIPProperties().UnicastAddresses; m_Addresses = new Registry<NetAddrInfo>(); var ord = 0; foreach(var addr in addrs) { m_Addresses.Register( new NetAddrInfo(addr, ord) ); ord++; } }
Task ListenForAnnouncementsAsync(System.Net.NetworkInformation.NetworkInterface adapter, Action <AdapterInformation, string, byte[]> callback, CancellationToken cancellationToken) { return(Task.Factory.StartNew(async() => { var ipv4Address = adapter.GetIPProperties().UnicastAddresses .First(ua => ua.Address.AddressFamily == AddressFamily.InterNetwork)?.Address; if (ipv4Address == null) { return; } var ifaceIndex = adapter.GetIPProperties().GetIPv4Properties()?.Index; if (ifaceIndex == null) { return; } Debug.WriteLine($"Scanning on iface {adapter.Name}, idx {ifaceIndex}, IP: {ipv4Address}"); using (var client = new UdpClient()) { var socket = client.Client; socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, IPAddress.HostToNetworkOrder(ifaceIndex.Value)); socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); client.ExclusiveAddressUse = false; var localEp = new IPEndPoint(IPAddress.Any, 5353); socket.Bind(localEp); var multicastAddress = IPAddress.Parse("224.0.0.251"); var multOpt = new MulticastOption(multicastAddress, ifaceIndex.Value); socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, multOpt); cancellationToken.Register((() => { ((IDisposable)client).Dispose(); })); while (!cancellationToken.IsCancellationRequested) { try { var packet = await client.ReceiveAsync() .ConfigureAwait(false); try { callback(new AdapterInformation(ipv4Address.ToString(), adapter.Name), packet.RemoteEndPoint.Address.ToString(), packet.Buffer); } catch (Exception ex) { Debug.WriteLine($"Callback threw an exception: {ex}"); } } catch when(cancellationToken.IsCancellationRequested) { // eat any exceptions if we've been cancelled } } Debug.WriteLine($"Done listening for mDNS packets on {adapter.Name}, idx {ifaceIndex}, IP: {ipv4Address}."); cancellationToken.ThrowIfCancellationRequested(); } }, cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Default).Unwrap()); }
public async Task NetworkRequestAsync(byte[] requestBytes, TimeSpan scanTime, int retries, int retryDelayMilliseconds, Action <IPAddress, byte[]> onResponse, System.Net.NetworkInformation.NetworkInterface adapter, CancellationToken cancellationToken) { // http://stackoverflow.com/questions/2192548/specifying-what-network-interface-an-udp-multicast-should-go-to-in-net // Xamarin doesn't support this //if (!adapter.GetIPProperties().MulticastAddresses.Any()) // return; // most of VPN adapters will be skipped if (!adapter.SupportsMulticast) { return; // multicast is meaningless for this type of connection } if (OperationalStatus.Up != adapter.OperationalStatus) { return; // this adapter is off or not connected } if (adapter.NetworkInterfaceType == NetworkInterfaceType.Loopback) { return; // strip out loopback addresses } var p = adapter.GetIPProperties().GetIPv4Properties(); if (null == p) { return; // IPv4 is not configured on this adapter } var ipv4Address = adapter.GetIPProperties().UnicastAddresses .FirstOrDefault(ua => ua.Address.AddressFamily == AddressFamily.InterNetwork)?.Address; if (ipv4Address == null) { return; // could not find an IPv4 address for this adapter } var ifaceIndex = p.Index; Debug.WriteLine($"Scanning on iface {adapter.Name}, idx {ifaceIndex}, IP: {ipv4Address}"); using (var client = new UdpClient()) { for (var i = 0; i < retries; i++) { try { var socket = client.Client; if (socket.IsBound) { continue; } socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, IPAddress.HostToNetworkOrder(ifaceIndex)); client.ExclusiveAddressUse = false; socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, (int)scanTime.TotalMilliseconds); client.ExclusiveAddressUse = false; var localEp = new IPEndPoint(IPAddress.Any, 5353); Debug.WriteLine($"Attempting to bind to {localEp} on adapter {adapter.Name}"); socket.Bind(localEp); Debug.WriteLine($"Bound to {localEp}"); var multicastAddress = IPAddress.Parse("224.0.0.251"); var multOpt = new MulticastOption(multicastAddress, ifaceIndex); socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, multOpt); Debug.WriteLine("Bound to multicast address"); // Start a receive loop var shouldCancel = false; var recTask = Task.Run(async () => { try { while (!Volatile.Read(ref shouldCancel)) { var res = await client.ReceiveAsync() .ConfigureAwait(false); onResponse(res.RemoteEndPoint.Address, res.Buffer); } } catch when(Volatile.Read(ref shouldCancel)) { // If we're canceling, eat any exceptions that come from here } }, cancellationToken); var broadcastEp = new IPEndPoint(IPAddress.Parse("224.0.0.251"), 5353); Debug.WriteLine($"About to send on iface {adapter.Name}"); await client.SendAsync(requestBytes, requestBytes.Length, broadcastEp) .ConfigureAwait(false); Debug.WriteLine($"Sent mDNS query on iface {adapter.Name}"); // wait for responses await Task.Delay(scanTime, cancellationToken) .ConfigureAwait(false); Volatile.Write(ref shouldCancel, true); ((IDisposable)client).Dispose(); Debug.WriteLine("Done Scanning"); await recTask.ConfigureAwait(false); return; } catch (Exception e) { Debug.WriteLine($"Execption with network request, IP {ipv4Address}\n: {e}"); if (i + 1 >= retries) // last one, pass underlying out { // Ensure all inner info is captured ExceptionDispatchInfo.Capture(e).Throw(); throw; } } await Task.Delay(retryDelayMilliseconds, cancellationToken).ConfigureAwait(false); } } }
/// <summary> /// Returns a DNS server for the specified interface. /// </summary> /// <param name="iface">The interface.</param> /// <returns>The DNS server IP address.</returns> public static IPAddress GetDnsServer(NetworkInterface iface) { return iface.GetIPProperties().DnsAddresses.FirstOrDefault(); }
async Task NetworkRequestAsync(byte[] requestBytes, TimeSpan scanTime, int retries, int retryDelayMilliseconds, Action <string, byte[]> onResponse, System.Net.NetworkInformation.NetworkInterface adapter, CancellationToken cancellationToken) { // http://stackoverflow.com/questions/2192548/specifying-what-network-interface-an-udp-multicast-should-go-to-in-net #if !XAMARIN if (!adapter.GetIPProperties().MulticastAddresses.Any()) { return; // most of VPN adapters will be skipped } #endif if (!adapter.SupportsMulticast) { return; // multicast is meaningless for this type of connection } if (OperationalStatus.Up != adapter.OperationalStatus) { return; // this adapter is off or not connected } if (adapter.NetworkInterfaceType == NetworkInterfaceType.Loopback) { return; // strip out loopback addresses } var p = adapter.GetIPProperties().GetIPv4Properties(); if (null == p) { return; // IPv4 is not configured on this adapter } var ipv4Address = adapter.GetIPProperties().UnicastAddresses .FirstOrDefault(ua => ua.Address.AddressFamily == AddressFamily.InterNetwork)?.Address; if (ipv4Address == null) { return; // could not find an IPv4 address for this adapter } var ifaceIndex = p.Index; Debug.WriteLine($"Scanning on iface {adapter.Name}, idx {ifaceIndex}, IP: {ipv4Address}"); using (var client = new UdpClient()) { for (var i = 0; i < retries; i++) { #if ANDROID var mlock = wifi.CreateMulticastLock("Zeroconf lock"); #endif try { #if ANDROID mlock.Acquire(); #endif client.Client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, IPAddress.HostToNetworkOrder(ifaceIndex)); client.ExclusiveAddressUse = false; client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, scanTime.Milliseconds); client.ExclusiveAddressUse = false; var localEp = new IPEndPoint(IPAddress.Any, 5353); Debug.WriteLine($"Attempting to bind to {localEp} on adapter {adapter.Name}"); client.Client.Bind(localEp); Debug.WriteLine($"Bound to {localEp}"); var multicastAddress = IPAddress.Parse("224.0.0.251"); var multOpt = new MulticastOption(multicastAddress, ifaceIndex); client.Client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, multOpt); Debug.WriteLine("Bound to multicast address"); // Start a receive loop var shouldCancel = false; var recTask = Task.Run(async () => { try { while (!shouldCancel) { var res = await client.ReceiveAsync() .ConfigureAwait(false); onResponse(res.RemoteEndPoint.Address.ToString(), res.Buffer); } } catch (ObjectDisposedException) { } }, cancellationToken); var broadcastEp = new IPEndPoint(IPAddress.Parse("224.0.0.251"), 5353); Debug.WriteLine($"About to send on iface {adapter.Name}"); await client.SendAsync(requestBytes, requestBytes.Length, broadcastEp) .ConfigureAwait(false); Debug.WriteLine($"Sent mDNS query on iface {adapter.Name}"); // wait for responses await Task.Delay(scanTime, cancellationToken) .ConfigureAwait(false); shouldCancel = true; #if CORECLR client.Dispose(); #else client.Close(); #endif Debug.WriteLine("Done Scanning"); await recTask.ConfigureAwait(false); return; } catch (Exception e) { Debug.WriteLine($"Execption with network request, IP {ipv4Address}\n: {e}"); if (i + 1 >= retries) // last one, pass underlying out { throw; } } finally { #if ANDROID mlock.Release(); #endif } await Task.Delay(retryDelayMilliseconds, cancellationToken).ConfigureAwait(false); } } }
/// <summary> /// Returns the list of DNS server for the specified interface. /// </summary> /// <param name="iface">The interface.</param> /// <returns>The list of DNS server IP addresses.</returns> public static IPAddress[] GetDnsServers(NetworkInterface iface) { return iface.GetIPProperties().DnsAddresses.ToArray(); }
public static IPAddress GetIpAddress(NetworkInterface ni) { IPAddress retval = IPAddress.Any; foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses) { if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { retval = ip.Address; break; } } return retval; }
/// <summary> /// Report the IP address of the network interface(s) /// </summary> /// <param name="builder">String builder to write to</param> /// <param name="iface">Optional network interface</param> /// <param name="index">Index of the network interface</param> public static async ValueTask Report(StringBuilder builder, NetworkInterface iface, int index) { if (iface == null) { int i = 0; foreach (NetworkInterface item in NetworkInterface.GetAllNetworkInterfaces()) { if (item.NetworkInterfaceType != NetworkInterfaceType.Loopback && (index < 0 || index == i)) { await Report(builder, item, i ++); } } } else { if (NetworkInterface.GetAllNetworkInterfaces().Count(item => item.NetworkInterfaceType != NetworkInterfaceType.Loopback) > 1) { // Add labels if there is more than one available network interface builder.Append($"Interface {index}: "); } if (iface.Name.StartsWith('w')) { // WiFi interface if (iface.OperationalStatus != OperationalStatus.Down) { UnicastIPAddressInformation ipInfo = (from unicastAddress in iface.GetIPProperties().UnicastAddresses where unicastAddress.Address.AddressFamily == AddressFamily.InterNetwork select unicastAddress).FirstOrDefault(); if (ipInfo != null) { bool isAccessPoint = await AccessPoint.IsEnabled(); builder.AppendLine($"WiFi module is {(isAccessPoint ? "providing access point" : "connected to access point")}, IP address {ipInfo.Address}"); } else { builder.AppendLine("WiFi module is idle"); } } else { builder.AppendLine("WiFi module is disabled"); } } else { // Ethernet interface IPAddress configuredIP = await DHCP.GetConfiguredIPAddress(iface.Name); if (iface.OperationalStatus == OperationalStatus.Up) { IPAddress actualIP = (from unicastAddress in iface.GetIPProperties().UnicastAddresses where unicastAddress.Address.AddressFamily == AddressFamily.InterNetwork select unicastAddress.Address).FirstOrDefault() ?? IPAddress.Any; builder.AppendLine($"Ethernet is enabled, configured IP address: {configuredIP}, actual IP address: {actualIP}"); } else { builder.AppendLine($"Ethernet is disabled, configured IP address: {configuredIP}, actual IP address: 0.0.0.0"); } } } }