public NetworkInterfaceHandler(ServiceBrowser serviceBrowser, NetworkInterface networkInterface) { ServiceBrowser = serviceBrowser; NetworkInterface = networkInterface; _index = NetworkInterface.Information.GetIPProperties().GetIPv4Properties().Index; _queryTimer = new Timer(OnQueryTimerElapsed); }
public CreateGameGUI(NetworkInterface nif, MainMenu m) { networkInterface = nif; networkInterface.AddMessageRecipient((INetworkMessage)this); mainMenu = m; SetUpScreen(); }
public StartGameScreen(NetworkInterface netif, bool readOnly) { SetUp(); networkInterface = netif; this.readOnly = readOnly; networkInterface.AddMessageRecipient((INetworkMessage) this); }
public MainContent(NetworkInterface nif, NetworkWindow networkWin) { lobby = new LobbyWindow(nif,networkWin); test = new TestWindow(); networkWindow = networkWin; networkInterface = nif; }
public NetworkWindow(NetworkInterface nif) { chat = new Chat(nif); chat.togglePos = new Rect(0,30,togglePos.width,25); nif.AddMessageRecipient((INetworkMessage)this); menus.Add(new MainContent(nif,this)); }
public void RegisterKillProcessOnInterfaceUp(NetworkInterface networkInterface, string processName) { _killerValues.Add(new ProcessKillerParameters() { NetworkInterface = networkInterface, ProcessName = processName }); }
public Switch(string name, int PortNum) { SwitchName = name; PortCount = PortNum; for (int i = 0; i < PortCount; i++) { Ports[i] = new NetworkInterface(SwitchName + "_interface_" + i); } }
public DotNetInterface(NetworkInterface n, UdpIPv4Address[] gw, UdpIPv4Address[] uni, UdpIPv4Address[] multi) { this.name = DotNetInterface.ParseName(n); this.linkType = DotNetInterface.ParseLinkType(n); this.physicalAddress = DotNetInterface.ParsePhysicalAddress(n); this.gatewayAddresses = gw; this.unicastAddresses = uni; this.multicastAddresses = multi; }
public void SetConnection(NetworkInterface networkInterface) { if (networkInterface == null) { throw new System.ArgumentNullException("Can't connect to null network interface", nameof(networkInterface)); } ConnectToInternal(networkInterface); networkInterface.ConnectToInternal(this); }
public DotNetInterface(NetworkInterface n, UdpIPv4Address[] gw, UdpIPv4Address[] uni, UdpIPv4Address[] multi) { name = ParseName(n); linkType = ParseLinkType(n); physicalAddress = ParsePhysicalAddress(n); gatewayAddresses = gw; unicastAddresses = uni; multicastAddresses = multi; }
public DropdownMenu( Control c, NetworkInterface nif) { control = c; endGame = new ConfirmMenu("Quit Game",(int)positionOpen.x,(int)positionOpen.y); resign = new ConfirmMenu("Resign",(int)positionOpen.x,(int)positionOpen.y+30); Console.buttonRect = new Rect(positionOpen.x,positionOpen.y+60,80,25); if(nif != null){ networkGUI = new NetworkWindow(nif); networkGUI.togglePos = new Rect(positionOpen.x,positionOpen.y+90,80,55); } }
static UdpLinkType ParseLinkType(NetworkInterface n) { switch (n.NetworkInterfaceType) { case NetworkInterfaceType.Ethernet: case NetworkInterfaceType.Ethernet3Megabit: case NetworkInterfaceType.FastEthernetFx: case NetworkInterfaceType.FastEthernetT: case NetworkInterfaceType.GigabitEthernet: return UdpLinkType.Ethernet; case NetworkInterfaceType.Wireless80211: return UdpLinkType.Wifi; default: return UdpLinkType.Unknown; } }
void Start() { Stats.StartUpRoutine(); //should be called once at the beginning of every game (include in loading script or smt) nif = (NetworkInterface)FindObjectOfType(typeof(NetworkInterface)); if(nif == null){ Instantiate(network); } sound = (Sound)FindObjectOfType(typeof(Sound)); if(sound == null) Instantiate(soundObject); mainMenuFrame = Frame.Create("Main Menu"); mainMenuFrame.AddButton(new LocalGameButton(this)); mainMenuFrame.AddButton(new NetworkedButton(this)); mainMenuFrame.AddButton(new TutorialButton(this)); mainMenuFrame.AddButton(new OptionsButton(this)); menuStack.Add(mainMenuFrame); }
public override IEnumerator SetupAsync () { netInterface = new NetworkInterface(); packetSender = new PacketSender(); packetReceiver = new PacketReceiver(netInterface); packetReceiver.AddPacketListener(OnReceivePacket); netInterface.ConnectTo(ip, port); while (netInterface.State == ConnectionState.Connecting) { yield return null; } Debug.Log("Connected!"); // var data = System.Text.Encoding.ASCII.GetBytes("hello~"); // netInterface.Send(data); netInterface.StartReceive(); }
void Start() { // Debug.Log("Screen: h = "+Screen.height+", w = "+Screen.width+", h/w = "+((double)Screen.height/(double)Screen.width)); Stats.StartUpRoutine(); //should be called once at the beginning of every game (include in loading script or smt) nif = (NetworkInterface)FindObjectOfType(typeof(NetworkInterface)); if(nif == null){ Instantiate(network); } sound = (Sound)FindObjectOfType(typeof(Sound)); if(sound == null) Instantiate(soundObject); Frame mainMenuFrame; mainMenuFrame = Frame.Create("Main Menu"); mainMenuFrame.AddButton(new LocalGameButton(this)); mainMenuFrame.AddButton(new NetworkedButton(this)); mainMenuFrame.AddButton(new TutorialButton(this)); mainMenuFrame.AddButton(new OptionsButton(this)); menuStack.Add(mainMenuFrame); }
private static int Compare(NetworkInterface ni1, NetworkInterface ni2) { int index1 = GetIndex(ni1); int index2 = GetIndex(ni2); return index1.CompareTo(index2); }
public bool Run() { Debug.IndentLevel = 1; List<NetworkInterface> adapters = new List<NetworkInterface>(); // Get list of connected adapters Debug.WriteLine("Getting connected adapter list", EventLogEntryType.Information); adapters = NetworkInterface.GetAllNetworkInterfaces() .Where( x => x.NetworkInterfaceType != NetworkInterfaceType.Loopback && x.OperationalStatus == OperationalStatus.Up ) .ToList(); if (0 == adapters.Count) { Debug.WriteLine("No adapters found.", EventLogEntryType.Information); // No available adapters return true; } // Open network devices for sending raw packets OpenDevices(); // Get list of users List<string> users = GetUsers(); if (users.Count == 0) { Debug.WriteLine("NoUsers", EventLogEntryType.Error); } // Wait to open devices System.Threading.Thread.Sleep(Convert.ToInt32(TimeSpan.FromSeconds(1).TotalMilliseconds)); // Get information which doesn't change often or doesn't need to be 100% accurate in realtime when iterating through adapters PacketInfo pinfo = new PacketInfo(); pinfo.OperatingSystem = FriendlyName().Trim(); pinfo.OperatingSystemVersion = ""; pinfo.Username = String.Join(",", users).Trim().TrimEnd(','); pinfo.Uptime = GetUptime(); foreach (NetworkInterface adapter in adapters) { Debug.WriteLine(String.Format("Adapter {0}:", adapter.Name), EventLogEntryType.Information); try { Debug.WriteLine("Generating packet", EventLogEntryType.Information); Packet packet = CreateLLDPPacket(adapter, pinfo); Debug.IndentLevel = 1; Debug.WriteLine("Sending packet", EventLogEntryType.Information); sendRawPacket(adapter, packet); Debug.IndentLevel = 1; } catch (Exception e) { Debug.WriteLine(String.Format("Error sending packet:{0}{1}", Environment.NewLine, e.ToString()), EventLogEntryType.Error); } Debug.WriteLine("", EventLogEntryType.Information); Debug.WriteLine(new String('-', 40), EventLogEntryType.Information); Debug.IndentLevel = 1; } return true; }
private void CheckNetworkInterfaceStatuses(Dictionary<int, NetworkInterfaceHandler> interfaceHandlers) { lock (interfaceHandlers) { if (interfaceHandlers != _interfaceHandlers) { return; } HashSet<NetworkInterfaceHandler> handlers = new HashSet<NetworkInterfaceHandler>(_interfaceHandlers.Values); NetworkInterfaceInformation[] interfaceInfos = NetworkInterfaceInformation.GetAllNetworkInterfaces(); foreach (NetworkInterfaceInformation interfaceInfo in interfaceInfos) { if (interfaceInfo.NetworkInterfaceType == NetworkInterfaceType.Loopback) { continue; } if (interfaceInfo.NetworkInterfaceType == NetworkInterfaceType.Tunnel) { continue; } int index = interfaceInfo.GetIPProperties().GetIPv4Properties().Index; NetworkInterfaceHandler interfaceHandler; _interfaceHandlers.TryGetValue(index, out interfaceHandler); if (interfaceHandler == null) { var networkInterface = new NetworkInterface(interfaceInfo); index = interfaceInfo.GetIPProperties().GetIPv4Properties().Index; interfaceHandler = new NetworkInterfaceHandler(this, networkInterface); _interfaceHandlers.Add(index, interfaceHandler); OnNetworkInterfaceAdded(networkInterface); interfaceHandler.StartBrowse(_serviceTypes.Select(st => new Name(st.ToLower() + ".local."))); } if (interfaceInfo.OperationalStatus == OperationalStatus.Up) { interfaceHandler.Enable(); } else { interfaceHandler.Disable(); } handlers.Remove(interfaceHandler); } foreach (NetworkInterfaceHandler handler in handlers) { _interfaceHandlers.Remove(handler.Index); handler.Disable(); OnNetworkInterfaceRemoved(handler.NetworkInterface); } } }
static string ParseName(NetworkInterface n) { try { return n.Description; } catch { return "UNKNOWN"; } }
//愉快な関数たち ------------------------------------------------------------------- public bool CanConectNetWork() { return(NetworkInterface.GetIsNetworkAvailable()); }
public static void LoggingAdapters(string id) { var adapter = NetworkInterface.GetAllNetworkInterfaces().First(adapter => adapter.Id == id); Logging.Warning($"检索此网卡信息出错: {adapter.Name} {adapter.Id} {adapter.Description}"); }
public Winsock(DEV9_State parDev9, string parDevice) : base(parDev9) { //Add allways on connections byte[] dns1 = null; byte[] dns2 = null; Dictionary <string, byte[]> hosts = new Dictionary <string, byte[]>(); NetworkInterface adapter = null; if (parDevice != "Auto") { adapter = GetAdapterFromGuid(parDevice); if (adapter == null) { //System.Windows.Forms.MessageBox.Show("Failed to GetAdapter"); throw new NullReferenceException("Failed to GetAdapter"); } adapterIP = (from ip in adapter.GetIPProperties().UnicastAddresses where ip.Address.AddressFamily == AddressFamily.InterNetwork select ip.Address).SingleOrDefault(); } else { adapter = UDP_DHCPSession.AutoAdapter(); adapterIP = IPAddress.Any; } if (adapter == null) { throw new NullReferenceException("Auto Selection Failed, Check You Connection or Manually Specify Adapter"); } if (!DEV9Header.config.SocketConnectionSettings.AutoDNS1) { dns1 = IPAddress.Parse(DEV9Header.config.SocketConnectionSettings.DNS1).GetAddressBytes(); } if (!DEV9Header.config.SocketConnectionSettings.AutoDNS2) { dns2 = IPAddress.Parse(DEV9Header.config.SocketConnectionSettings.DNS2).GetAddressBytes(); } foreach (Config.ConfigHost host in DEV9Header.config.Hosts) { if (host.Enabled) { hosts.Add(host.URL, IPAddress.Parse(host.IP).GetAddressBytes()); } } //DHCP emulated server ConnectionKey dhcpKey = new ConnectionKey { Protocol = (byte)IPType.UDP, SRVPort = 67 }; dhcpServer = new UDP_DHCPSession(dhcpKey, adapter, dns1, dns2, DEV9Header.config.SocketConnectionSettings.LANMode); dhcpServer.ConnectionClosedEvent += HandleConnectionClosed; dhcpServer.SourceIP = new byte[] { 255, 255, 255, 255 }; dhcpServer.DestIP = DefaultDHCPConfig.DHCP_IP; if (!connections.TryAdd(dhcpServer.Key, dhcpServer)) { throw new Exception("Connection Add Failed"); } //DNS emulated server ConnectionKey dnsKey = new ConnectionKey { Protocol = (byte)IPType.UDP, SRVPort = 53 }; IPAddress localhost = (from ip in adapter.GetIPProperties().UnicastAddresses where ip.Address.AddressFamily == AddressFamily.InterNetwork select ip.Address).SingleOrDefault(); dnsServer = new UDP_DNSSession(dnsKey, hosts, localhost.GetAddressBytes()); dnsServer.ConnectionClosedEvent += HandleConnectionClosed; dnsServer.SourceIP = dhcpServer.PS2IP; dnsServer.DestIP = DefaultDHCPConfig.DHCP_IP; if (!connections.TryAdd(dnsServer.Key, dnsServer)) { throw new Exception("Connection Add Failed"); } // foreach (Config.ConfigIncomingPort port in DEV9Header.config.SocketConnectionSettings.IncomingPorts) { if (!port.Enabled) { continue; } ConnectionKey Key = new ConnectionKey { Protocol = (byte)port.Protocol, PS2Port = port.Port, SRVPort = port.Port }; Session s = null; if (port.Protocol == IPType.UDP) { //avoid duplicates if (fixedUDPPorts.ContainsKey(port.Port)) { continue; } ConnectionKey fKey = new ConnectionKey { Protocol = (byte)IPType.UDP, PS2Port = port.Port, SRVPort = 0 }; UDPFixedPort fPort = new UDPFixedPort(fKey, adapterIP, port.Port); fPort.ConnectionClosedEvent += HandleFixedPortClosed; fPort.DestIP = new byte[] { 0, 0, 0, 0 }; fPort.SourceIP = dhcpServer.PS2IP; if (!connections.TryAdd(fPort.Key, fPort) | !fixedUDPPorts.TryAdd(port.Port, fPort)) { fPort.Dispose(); throw new Exception("Connection Add Failed"); } s = fPort.NewListenSession(Key); } s.ConnectionClosedEvent += HandleConnectionClosed; s.SourceIP = dhcpServer.PS2IP; s.DestIP = dhcpServer.Broadcast; if (!connections.TryAdd(s.Key, s)) { s.Dispose(); throw new Exception("Connection Add Failed"); } } SetMAC(null); SetMAC(adapter.GetPhysicalAddress().GetAddressBytes()); }
/// <summary> /// Initializes UPnP NAT info. /// </summary> private void Init() { /* First try to get default LAN adapter gateway and check if it's UPnP nat. * If this fails try UPnP search. */ try{ UPnP_Client client = new UPnP_Client(); UPnP_Device[] devices = null; // Try to get gateway UPnP info, if it supports it. try{ IPAddress gwIP = null; foreach (NetworkInterface adapter in NetworkInterface.GetAllNetworkInterfaces()) { if (adapter.OperationalStatus == OperationalStatus.Up) { foreach (GatewayIPAddressInformation gwInformation in adapter.GetIPProperties().GatewayAddresses) { gwIP = gwInformation.Address; break; } break; } } devices = client.Search(gwIP, "urn:schemas-upnp-org:device:InternetGatewayDevice:1", 1200); } catch { // We dont care about errors here. } // Gateway no UPnP device, search for UPnP router. if (devices.Length == 0) { devices = client.Search("urn:schemas-upnp-org:device:InternetGatewayDevice:1", 1200); } if (devices.Length > 0) { XmlDocument xml = new XmlDocument(); xml.LoadXml(devices[0].DeviceXml); // Loop XML tree by nodes. List <XmlNode> queue = new List <XmlNode>(); queue.Add(xml); while (queue.Count > 0) { XmlNode currentNode = queue[0]; queue.RemoveAt(0); if (string.Equals("urn:schemas-upnp-org:service:WANPPPConnection:1", currentNode.InnerText, StringComparison.InvariantCultureIgnoreCase)) { foreach (XmlNode node in currentNode.ParentNode.ChildNodes) { if (string.Equals("controlURL", node.Name, StringComparison.InvariantCultureIgnoreCase)) { m_BaseUrl = devices[0].BaseUrl; m_ServiceType = "urn:schemas-upnp-org:service:WANPPPConnection:1"; m_ControlUrl = node.InnerText; return; } } } else if (string.Equals("urn:schemas-upnp-org:service:WANIPConnection:1", currentNode.InnerText, StringComparison.InvariantCultureIgnoreCase)) { foreach (XmlNode node in currentNode.ParentNode.ChildNodes) { if (string.Equals("controlURL", node.Name, StringComparison.InvariantCultureIgnoreCase)) { m_BaseUrl = devices[0].BaseUrl; m_ServiceType = "urn:schemas-upnp-org:service:WANIPConnection:1"; m_ControlUrl = node.InnerText; return; } } } else if (currentNode.ChildNodes.Count > 0) { for (int i = 0; i < currentNode.ChildNodes.Count; i++) { queue.Insert(i, currentNode.ChildNodes[i]); } } } } } catch { } }
/// <summary> /// Get all local ip addresses (non alloc version) /// </summary> /// <param name="targetList">result list</param> /// <param name="addrType">type of address (IPv4, IPv6 or both)</param> public static void GetLocalIpList(List <string> targetList, LocalAddrType addrType) { bool ipv4 = (addrType & LocalAddrType.IPv4) == LocalAddrType.IPv4; bool ipv6 = (addrType & LocalAddrType.IPv6) == LocalAddrType.IPv6; #if WINRT && !UNITY_EDITOR foreach (HostName localHostName in NetworkInformation.GetHostNames()) { if (localHostName.IPInformation != null && ((ipv4 && localHostName.Type == HostNameType.Ipv4) || (ipv6 && localHostName.Type == HostNameType.Ipv6))) { targetList.Add(localHostName.ToString()); } } #else try { foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces()) { //Skip loopback and disabled network interfaces if (ni.NetworkInterfaceType == NetworkInterfaceType.Loopback || ni.OperationalStatus != OperationalStatus.Up) { continue; } var ipProps = ni.GetIPProperties(); //Skip address without gateway if (ipProps.GatewayAddresses.Count == 0) { continue; } foreach (UnicastIPAddressInformation ip in ipProps.UnicastAddresses) { var address = ip.Address; if ((ipv4 && address.AddressFamily == AddressFamily.InterNetwork) || (ipv6 && address.AddressFamily == AddressFamily.InterNetworkV6)) { targetList.Add(address.ToString()); } } } } catch { //ignored } //Fallback mode (unity android) if (targetList.Count == 0) { #if NETCORE var hostTask = Dns.GetHostEntryAsync(Dns.GetHostName()); hostTask.Wait(); var host = hostTask.Result; #else var host = Dns.GetHostEntry(Dns.GetHostName()); #endif foreach (IPAddress ip in host.AddressList) { if ((ipv4 && ip.AddressFamily == AddressFamily.InterNetwork) || (ipv6 && ip.AddressFamily == AddressFamily.InterNetworkV6)) { targetList.Add(ip.ToString()); } } } #endif if (targetList.Count == 0) { if (ipv4) { targetList.Add("127.0.0.1"); } if (ipv6) { targetList.Add("::1"); } } }
// A.23 - Turn on IPv6 public NetworkInterface TurnOnIPv6(out string newServiceAddr, out string oldServiceAddr, out bool restoreEnabled) { newServiceAddr = null; oldServiceAddr = null; restoreEnabled = false; bool IPv6Feature = Features.Contains(Feature.IPv6); if (!IPv6Feature) { Test.Assert(IPv6Feature, "IPv6 not supported", "Check if IPv6 is supported"); } // backup interfaces NetworkInterface[] interfaces = BackupInterfaces(); NetworkInterface selectedInterface = null; // select current network interface to search for IPv6 address in it string intToken = null; foreach (var item in interfaces) { if (BackupIPv6) { if (item.IPv6.Config.DHCP == IPv6DHCPConfiguration.Off) { // search in Manual tag if (item.Enabled && item.IPv6 != null && item.IPv6.Config != null && item.IPv6.Config.Manual != null && item.IPv6.Config.Manual.Length != 0 && !string.IsNullOrEmpty(item.IPv6.Config.Manual[0].Address)) { string ipAddress = null; ExtractIPfromServiceAddress(AddressBackup, out ipAddress); if (item.IPv6.Config.Manual[0].Address == ipAddress) { intToken = item.token; selectedInterface = item; break; } } // search in LinkLocal tag else if (item.Enabled && item.IPv6 != null && item.IPv6.Config != null && item.IPv6.Config.LinkLocal != null && item.IPv6.Config.LinkLocal.Length != 0 && !string.IsNullOrEmpty(item.IPv6.Config.LinkLocal[0].Address)) { string ipAddress = null; ExtractIPfromServiceAddress(AddressBackup, out ipAddress); if (item.IPv6.Config.LinkLocal[0].Address == ipAddress) { intToken = item.token; selectedInterface = item; break; } } } else { // search in FromDHCP tag if (item.Enabled && item.IPv6 != null && item.IPv6.Config != null && item.IPv6.Config.FromDHCP != null && item.IPv6.Config.FromDHCP.Length != 0 && !string.IsNullOrEmpty(item.IPv6.Config.FromDHCP[0].Address)) { string ipAddress = null; ExtractIPfromServiceAddress(AddressBackup, out ipAddress); if (item.IPv6.Config.FromDHCP[0].Address == ipAddress) { intToken = item.token; selectedInterface = item; break; } } // search in LinkLocal tag else if (item.Enabled && item.IPv6 != null && item.IPv6.Config != null && item.IPv6.Config.LinkLocal != null && item.IPv6.Config.LinkLocal.Length != 0 && !string.IsNullOrEmpty(item.IPv6.Config.LinkLocal[0].Address)) { string ipAddress = null; ExtractIPfromServiceAddress(AddressBackup, out ipAddress); if (item.IPv6.Config.LinkLocal[0].Address == ipAddress) { intToken = item.token; selectedInterface = item; break; } } } } else { if (!item.IPv4.Config.DHCP) { // search in Manual tag if (item.Enabled && item.IPv4 != null && item.IPv4.Config != null && item.IPv4.Config.Manual != null && item.IPv4.Config.Manual.Length != 0 && !string.IsNullOrEmpty(item.IPv4.Config.Manual[0].Address)) { string ipAddress = null; ExtractIPfromServiceAddress(AddressBackup, out ipAddress); if (item.IPv4.Config.Manual[0].Address == ipAddress) { intToken = item.token; selectedInterface = item; break; } } // search in LinkLocal tag else if (item.Enabled && item.IPv4 != null && item.IPv4.Config != null && item.IPv4.Config.LinkLocal != null && !string.IsNullOrEmpty(item.IPv4.Config.LinkLocal.Address)) { string ipAddress = null; ExtractIPfromServiceAddress(AddressBackup, out ipAddress); if (item.IPv4.Config.LinkLocal.Address == ipAddress) { intToken = item.token; selectedInterface = item; break; } } } else { // search in FromDHCP tag if (item.Enabled && item.IPv4 != null && item.IPv4.Config != null && item.IPv4.Config.FromDHCP != null && !string.IsNullOrEmpty(item.IPv4.Config.FromDHCP.Address)) { string ipAddress = null; ExtractIPfromServiceAddress(AddressBackup, out ipAddress); if (item.IPv4.Config.FromDHCP.Address == ipAddress) { intToken = item.token; selectedInterface = item; break; } } // search in LinkLocal tag else if (item.Enabled && item.IPv4 != null && item.IPv4.Config != null && item.IPv4.Config.LinkLocal != null && !string.IsNullOrEmpty(item.IPv4.Config.LinkLocal.Address)) { string ipAddress = null; ExtractIPfromServiceAddress(AddressBackup, out ipAddress); if (item.IPv4.Config.LinkLocal.Address == ipAddress) { intToken = item.token; selectedInterface = item; break; } } } } } Test.Assert(!string.IsNullOrEmpty(intToken), "Current network interface not found", "Search for current network interface"); // select IPv6 if (BackupIPv6) { // do nothing, use current IPv6 and current network interface // nothing needed to be restored return(selectedInterface); } else if (!BackupIPv6) { if (selectedInterface.IPv6 != null) { if (selectedInterface.IPv6.Enabled) { if (selectedInterface.IPv6.Config.DHCP == IPv6DHCPConfiguration.Off) { // Manual tag exists if (selectedInterface.IPv6.Config.Manual != null && selectedInterface.IPv6.Config.Manual.Length != 0 && !string.IsNullOrEmpty(selectedInterface.IPv6.Config.Manual[0].Address)) { string IPv6 = selectedInterface.IPv6.Config.Manual[0].Address; SelectIPv6(ref oldServiceAddr, ref newServiceAddr, IPv6); } // LinkLocal tag exists else if (selectedInterface.IPv6.Config.LinkLocal != null && selectedInterface.IPv6.Config.LinkLocal.Length != 0 && !string.IsNullOrEmpty(selectedInterface.IPv6.Config.LinkLocal[0].Address)) { string IPv6 = selectedInterface.IPv6.Config.LinkLocal[0].Address; SelectIPv6(ref oldServiceAddr, ref newServiceAddr, IPv6); } else { Test.Assert(false, "Manual or LinkLocal IPv6 addresses were not found", "Searching for Manual or LinkLocal IPv6 address"); } } else { // FromDHCP tag exists if (selectedInterface.IPv6.Config.FromDHCP != null && selectedInterface.IPv6.Config.FromDHCP.Length != 0 && !string.IsNullOrEmpty(selectedInterface.IPv6.Config.FromDHCP[0].Address)) { string IPv6 = selectedInterface.IPv6.Config.FromDHCP[0].Address; SelectIPv6(ref oldServiceAddr, ref newServiceAddr, IPv6); } // LinkLocal tag exists else if (selectedInterface.IPv6.Config.LinkLocal != null && selectedInterface.IPv6.Config.LinkLocal.Length != 0 && !string.IsNullOrEmpty(selectedInterface.IPv6.Config.LinkLocal[0].Address)) { string IPv6 = selectedInterface.IPv6.Config.LinkLocal[0].Address; SelectIPv6(ref oldServiceAddr, ref newServiceAddr, IPv6); } else { Test.Assert(false, "FromDHCP or LinkLocal IPv6 addresses were not found", "Searching for Manual or LinkLocal IPv6 address"); } } } else { // setup IPv6 interface as enabled EnableIPv6(intToken, ref oldServiceAddr, ref newServiceAddr, out restoreEnabled /*, ref restoreDHCP, out dhcp*/); } } else { // setup IPv6 interface as enabled EnableIPv6(intToken, ref oldServiceAddr, ref newServiceAddr, out restoreEnabled /*, ref restoreDHCP, out dhcp*/); } } return(selectedInterface); }
private static bool IsValid(NetworkInterface ni) { return GetIndex(ni) != -1; }
private void CheckNetworkInterfaceStatuses(object sender, EventArgs e) { lock (_interfaceHandlers) { HashSet<NetworkInterfaceHandler> handlers = new HashSet<NetworkInterfaceHandler>(_interfaceHandlers.Values); NetworkInterfaceInformation[] interfaceInfos = NetworkInterfaceInformation.GetAllNetworkInterfaces(); foreach (NetworkInterfaceInformation interfaceInfo in interfaceInfos) { if (interfaceInfo.NetworkInterfaceType == NetworkInterfaceType.Loopback) { continue; } if (interfaceInfo.NetworkInterfaceType == NetworkInterfaceType.Tunnel) { continue; } int index = interfaceInfo.GetIPProperties().GetIPv4Properties().Index; NetworkInterfaceHandler interfaceHandler; _interfaceHandlers.TryGetValue(index, out interfaceHandler); if (interfaceHandler == null) { var networkInterface = new NetworkInterface(interfaceInfo); index = interfaceInfo.GetIPProperties().GetIPv4Properties().Index; interfaceHandler = new NetworkInterfaceHandler(this, networkInterface); _interfaceHandlers.Add(index, interfaceHandler); } if (interfaceInfo.OperationalStatus == OperationalStatus.Up) { interfaceHandler.Enable(); } else { interfaceHandler.Disable(); } handlers.Remove(interfaceHandler); } foreach (NetworkInterfaceHandler handler in handlers) { handler.Disable(); } } }
public void Execute() { int c = 0; Boolean repeat = true; while (repeat) { repeat = false; c++; try { //initialize UdpClient udpClient = new UdpClient(); //set end point to multicast 239.168.100.2:64537 IPEndPoint endPointUDP = new IPEndPoint(Utilities.multicastEndPoint.Address, Utilities.multicastEndPoint.Port); while (closeClientUDP == false) { //create payload: 4 byte lenght payload 4 byte port n byte name byte[] nameBytes = Encoding.UTF8.GetBytes(Name); int nameSize = nameBytes.Length; int payloadSize = nameSize + 8; byte[] payload = new byte[payloadSize]; Buffer.BlockCopy(BitConverter.GetBytes(payloadSize), 0, payload, 0, 4); //big/little endian Buffer.BlockCopy(BitConverter.GetBytes(PortTCP), 0, payload, 4, 4); Buffer.BlockCopy(nameBytes, 0, payload, 8, nameSize); if (NetworkInterface.GetIsNetworkAvailable()) { //send messagge udpClient.Send(payload, payloadSize, endPointUDP); } //sleep for 2 seconds Thread.Sleep(2000); } //close udpclient udpClient.Close(); //say to form that you finished if (!finalClose) { form.BeginInvoke(form.CloseThreadDelegate, new object[] { Thread.CurrentThread, Utilities.CientUDP }); } } catch (SocketException e) { //Console.WriteLine(e.ErrorCode); Console.WriteLine(e.ToString()); if (c < 2) { if (udpClient != null && udpClient.Client != null) { udpClient.Close(); } repeat = true; } else { //say to form that you finished if (!finalClose) { form.BeginInvoke(form.CloseThreadDelegate, new object[] { Thread.CurrentThread, Utilities.CientUDP }); } if (udpClient != null && udpClient.Client != null) { udpClient.Close(); } } } } }
/// <summary> /// Generate LLDP packet for adapter /// </summary> /// <param name="adapter"></param> private Packet CreateLLDPPacket(NetworkInterface adapter, PacketInfo pinfo) { Debug.IndentLevel = 2; PhysicalAddress MACAddress = adapter.GetPhysicalAddress(); IPInterfaceProperties ipProperties = adapter.GetIPProperties(); IPv4InterfaceProperties ipv4Properties = null; // Ipv4 IPv6InterfaceProperties ipv6Properties = null;// Ipv6 // IPv6 if (adapter.Supports(NetworkInterfaceComponent.IPv6)) { try { ipv6Properties = ipProperties.GetIPv6Properties(); } catch (NetworkInformationException e) { // Adapter doesn't probably have IPv6 enabled Debug.WriteLine(e.Message, EventLogEntryType.Warning); } } // IPv4 if (adapter.Supports(NetworkInterfaceComponent.IPv4)) { try { ipv4Properties = ipProperties.GetIPv4Properties(); } catch (NetworkInformationException e) { // Adapter doesn't probably have IPv4 enabled Debug.WriteLine(e.Message, EventLogEntryType.Warning); } } // System description Dictionary<string, string> systemDescription = new Dictionary<string, string>(); systemDescription.Add("OS", pinfo.OperatingSystem); //systemDescription.Add("Ver", pinfo.OperatingSystemVersion); //systemDescription.Add("Usr", pinfo.Username); systemDescription.Add("Up", pinfo.Uptime); // Port description Dictionary<string, string> portDescription = new Dictionary<string, string>(); // adapter.Description is for example "Intel(R) 82579V Gigabit Network Connection" // Registry: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkCards\<number>\Description value //jt //portDescription.Add("Vendor", adapter.Description); //portDescription.Add("Vendor", ""); /* adapter.Id is GUID and can be found in several places: In this example it is "{87423023-7191-4C03-A049-B8E7DBB36DA4}" Registry: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion - \NetworkCards\<number>\ServiceName value (in same tree as adapter.Description!) - \NetworkList\Nla\Cache\Intranet\<adapter.Id> key - \NetworkList\Nla\Cache\Intranet\<domain>\<adapter.Id> key Registry: HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows NT\CurrentVersion - \NetworkCards\<number>\ServiceName value Registry: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318}\0007 {4D36E972-E325-11CE-BFC1-08002BE10318} == Network and Sharing Center -> viewing adapter's "Properties" and selecting "Device class GUID" from dropdown menu {4D36E972-E325-11CE-BFC1-08002BE10318}\0007 == Network and Sharing Center -> viewing adapter's "Properties" and selecting "Driver key" from dropdown menu - \NetCfgInstanceId value - \Linkage\Export value (part of) - \Linkage\FilterList value (part of) - \Linkage\RootDevice value Registry: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\DeviceClasses\{ad498944-762f-11d0-8dcb-00c04fc3358c}\##?#PCI#VEN_8086&DEV_1503&SUBSYS_849C1043&REV_06#3&11583659&0&C8#{ad498944-762f-11d0-8dcb-00c04fc3358c}\#{87423023-7191-4C03-A049-B8E7DBB36DA4}\SymbolicLink value (part of) Registry: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Network\{ 4D36E972 - E325 - 11CE - BFC1 - 08002BE10318}\{ 87423023 - 7191 - 4C03 - A049 - B8E7DBB36DA4} Registry: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Network\{4D36E972-E325-11CE-BFC1-08002BE10318}\{ACB3F7A0-2E45-4435-854A-A4E120477E1D}\Connection\Name value (part of) Registry: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\{ 87423023 - 7191 - 4C03 - A049 - B8E7DBB36DA4} Registry: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\iphlpsvc\Parameters\Isatap\{ ACB3F7A0 - 2E45 - 4435 - 854A - A4E120477E1D}\InterfaceName value (part of) Registry: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\<various names>\Linkage - \Bind value (part of) - \Export value (part of) - \Route value (part of) Registry: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\NetBT\Parameters\Interfaces\Tcpip_{87423023-7191-4C03-A049-B8E7DBB36DA4} Registry: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\Psched\Parameters\NdisAdapters\{87423023-7191-4C03-A049-B8E7DBB36DA4} Registry: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\RemoteAccess\Interfaces\<number>\InterfaceName value Registry: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Adapters\{87423023-7191-4C03-A049-B8E7DBB36DA4}\IpConfig value (part of) IPv4 information: Registry: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Interfaces\{87423023-7191-4C03-A049-B8E7DBB36DA4} IPv6 information: Registry: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\TCPIP6\Parameters\Interfaces\{87423023-7191-4c03-a049-b8e7dbb36da4} Registry: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\WfpLwf\Parameters\NdisAdapters\{87423023-7191-4C03-A049-B8E7DBB36DA4} */ // jt //portDescription.Add("ID", adapter.Id); //portDescription.Add("ID", ""); // Gateway if (ipProperties.GatewayAddresses.Count > 0) { portDescription.Add("GW", String.Join(", ", ipProperties.GatewayAddresses.Select(i => i.Address.ToString()).ToArray())); } else { portDescription.Add("GW", "-"); } // CIDR if (ipProperties.UnicastAddresses.Count > 0) { int[] mask = ipProperties.UnicastAddresses .Where( w => w.IPv4Mask.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork ) .Select(x => getCIDRFromIPMaskAddress(x.IPv4Mask)) .Where( m => m!= 0) .ToArray() ; portDescription.Add("NM", String.Join(", ", mask)); } else { portDescription.Add("NM", "-"); } /* // DNS server(s) if (ipProperties.DnsAddresses.Count > 0) { portDescription.Add("DNS", String.Join(", ", ipProperties.DnsAddresses.Select(i => i.ToString()).ToArray())); } else { portDescription.Add("DNS", "-"); } */ // DHCP server if (ipProperties.DhcpServerAddresses.Count > 0) { portDescription.Add("DHCP", String.Join(", ", ipProperties.DhcpServerAddresses.Select(i => i.ToString()).ToArray())); } else { portDescription.Add("DHCP", "-"); } /* // WINS server(s) if (ipProperties.WinsServersAddresses.Count > 0) { portDescription.Add("WINS", String.Join(", ", ipProperties.WinsServersAddresses.Select(i => i.ToString()).ToArray())); } */ // Link speed portDescription.Add("Spd", ReadableSize(adapter.Speed) + "ps"); // Capabilities enabled List<CapabilityOptions> capabilitiesEnabled = new List<CapabilityOptions>(); capabilitiesEnabled.Add(CapabilityOptions.StationOnly); if (ipv4Properties.IsForwardingEnabled) { capabilitiesEnabled.Add(CapabilityOptions.Router); } ushort expectedSystemCapabilitiesCapability = GetCapabilityOptionsBits(GetCapabilityOptions()); ushort expectedSystemCapabilitiesEnabled = GetCapabilityOptionsBits(capabilitiesEnabled); // Constuct LLDP packet LLDPPacket lldpPacket = new LLDPPacket(); lldpPacket.TlvCollection.Add(new ChassisID(ChassisSubTypes.MACAddress, MACAddress)); lldpPacket.TlvCollection.Add(new PortID(PortSubTypes.LocallyAssigned, System.Text.Encoding.UTF8.GetBytes(adapter.Name))); lldpPacket.TlvCollection.Add(new TimeToLive(120)); lldpPacket.TlvCollection.Add(new PortDescription(CreateTlvString(portDescription))); lldpPacket.TlvCollection.Add(new SystemName(GetFQDN())); lldpPacket.TlvCollection.Add(new SystemDescription(CreateTlvString(systemDescription))); lldpPacket.TlvCollection.Add(new SystemCapabilities(expectedSystemCapabilitiesCapability, expectedSystemCapabilitiesEnabled)); // Management var managementAddressObjectIdentifier = "Management"; // Add management IPv4 address(es) if (null != ipv4Properties) { foreach (UnicastIPAddressInformation ip in ipProperties.UnicastAddresses) { if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { lldpPacket.TlvCollection.Add(new ManagementAddress(new NetworkAddress(ip.Address), InterfaceNumbering.SystemPortNumber, Convert.ToUInt32(ipv4Properties.Index), managementAddressObjectIdentifier)); } } } // Add management IPv6 address(es) if (null != ipv6Properties) { foreach (UnicastIPAddressInformation ip in ipProperties.UnicastAddresses) { if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) { lldpPacket.TlvCollection.Add(new ManagementAddress(new NetworkAddress(ip.Address), InterfaceNumbering.SystemPortNumber, Convert.ToUInt32(ipv6Properties.Index), managementAddressObjectIdentifier)); } } } // == Organization specific TLVs // Ethernet lldpPacket.TlvCollection.Add(new OrganizationSpecific(new byte[] { 0x0, 0x12, 0x0f }, 5, new byte[] { 0x5 })); var expectedOrganizationUniqueIdentifier = new byte[3] { 0, 0, 0 }; var expectedOrganizationSpecificBytes = new byte[] { 0, 0, 0, 0 }; //int orgSubType = 0; // IPv4 Information: //if (null != ipv4Properties) //{ // lldpPacket.TlvCollection.Add((new StringTLV(TLVTypes.OrganizationSpecific, String.Format("IPv4 DHCP: {0}", ipv4Properties.IsDhcpEnabled.ToString())))); //lldpPacket.TlvCollection.Add(new OrganizationSpecific(expectedOrganizationSpecificBytes, new StringTLV(), System.Text.Encoding.UTF8.GetBytes(String.Format("IPv4 DHCP: {0}", ipv4Properties.IsDhcpEnabled.ToString())))); //} // End of LLDP packet lldpPacket.TlvCollection.Add(new EndOfLLDPDU()); if (0 == lldpPacket.TlvCollection.Count) { throw new Exception("Couldn't construct LLDP TLVs."); } if (lldpPacket.TlvCollection.Last().GetType() != typeof(EndOfLLDPDU)) { throw new Exception("Last TLV must be type of 'EndOfLLDPDU'!"); } foreach (TLV tlv in lldpPacket.TlvCollection) { Debug.WriteLine(tlv.ToString(), EventLogEntryType.Information); } // Generate packet Packet packet = new EthernetPacket(MACAddress, destinationHW, EthernetPacketType.LLDP); packet.PayloadData = lldpPacket.Bytes; return packet; }
getInterfaceIndex(string iface, AddressFamily family) { if (iface.Length == 0) { return(-1); } // // The iface parameter must either be an IP address, an // index or the name of an interface. If it's an index we // just return it. If it's an IP addess we search for an // interface which has this IP address. If it's a name we // search an interface with this name. // try { return(int.Parse(iface, CultureInfo.InvariantCulture)); } catch (FormatException) { } NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); try { IPAddress addr = IPAddress.Parse(iface); foreach (NetworkInterface ni in nics) { IPInterfaceProperties ipProps = ni.GetIPProperties(); foreach (UnicastIPAddressInformation uni in ipProps.UnicastAddresses) { if (uni.Address.Equals(addr)) { if (addr.AddressFamily == AddressFamily.InterNetwork) { IPv4InterfaceProperties ipv4Props = ipProps.GetIPv4Properties(); if (ipv4Props != null) { return(ipv4Props.Index); } } else { IPv6InterfaceProperties ipv6Props = ipProps.GetIPv6Properties(); if (ipv6Props != null) { return(ipv6Props.Index); } } } } } } catch (FormatException) { } foreach (NetworkInterface ni in nics) { if (ni.Name == iface) { IPInterfaceProperties ipProps = ni.GetIPProperties(); if (family == AddressFamily.InterNetwork) { IPv4InterfaceProperties ipv4Props = ipProps.GetIPv4Properties(); if (ipv4Props != null) { return(ipv4Props.Index); } } else { IPv6InterfaceProperties ipv6Props = ipProps.GetIPv6Properties(); if (ipv6Props != null) { return(ipv6Props.Index); } } } } throw new ArgumentException("couldn't find interface `" + iface + "'"); }
//***************************************************************** //-------------searchButton click event handling ------------------ //***************************************************************** private void searchButton_Click(object sender, EventArgs e) { pictureBox1.Visible = true; //------------Geting the text from search box-------------- if (string.IsNullOrWhiteSpace(searchBox.Text)) { MessageBox.Show("Search Box is empty! Please write your Query to search"); return; //searchBox.Text = "Write your query here ...."; //continue; } else { searchOb.searchQuery = searchBox.Text.ToString().Trim(); } //-------------getting the selected radio button--------------- if (mostRelevent.Checked) { searchOb.sortBy = mostRelevent.Text; } else if (mostRecent.Checked) { searchOb.sortBy = mostRecent.Text; } else if (priceAscending.Checked) { searchOb.sortBy = priceAscending.Text; } else if (priceDescending.Checked) { searchOb.sortBy = priceDescending.Text; } //--------------- Getting the price Range ---------------- if (string.IsNullOrWhiteSpace(lowerPriceRange.Text) && string.IsNullOrWhiteSpace(upperPriceRange.Text)) { searchOb.lowerPriceRange = 0; searchOb.upperPriceRange = 0; } else { try { searchOb.lowerPriceRange = int.Parse(lowerPriceRange.Text.ToString()); searchOb.upperPriceRange = int.Parse(upperPriceRange.Text.ToString()); } catch (FormatException fe) { MessageBox.Show("Please enter valid number for price range"); return; } } //---------getting the selected location------------- if (allBangladeshCheck.Checked) { searchOb.selectedLocation.Add(allBangladeshCheck.Text.ToString()); } else { if (dhakaCheck.Checked) { searchOb.selectedLocation.Add(dhakaCheck.Text.ToString()); } if (chittagongChecke.Checked) { searchOb.selectedLocation.Add(chittagongChecke.Text.ToString()); } if (sylhetCheck.Checked) { searchOb.selectedLocation.Add(sylhetCheck.Text.ToString()); } if (khulnaChecked.Checked) { searchOb.selectedLocation.Add(khulnaChecked.Text.ToString()); } } if (!searchOb.selectedLocation.Any()) { allBangladeshCheck.Checked = true; searchOb.selectedLocation.Add(allBangladeshCheck.Text.ToString()); } if (!NetworkInterface.GetIsNetworkAvailable()) { MessageBox.Show("No Internet Connection!"); return; } sc = new SearchControl(searchOb); Task tsk = Task.Factory.StartNew(sc.startSearch); Task.WaitAll(tsk); showSearchResult showResult = new showSearchResult(sc); showResult.Show(); showResult.ClearGrid(); showResult.showResult(); pictureBox1.Visible = false; }
private string getMacAddress() { return(NetworkInterface.GetAllNetworkInterfaces()[0].GetPhysicalAddress().ToString()); }
void EnableIPv6(string intToken, ref string oldServiceAddr, ref string newServiceAddr, out bool restoreEnabled) { NetworkInterfaceSetConfiguration configuration = new NetworkInterfaceSetConfiguration(); configuration.IPv6 = new IPv6NetworkInterfaceSetConfiguration(); configuration.IPv6.Enabled = true; configuration.IPv6.EnabledSpecified = true; SetIPConfiguration(intToken, configuration); // verify if IPv6 settings were applied NetworkInterface[] currentSettings = GetNetworkInterfaces(); NetworkInterface modified = currentSettings.Where(NI => NI.token == intToken).FirstOrDefault(); Test.Assert(modified.IPv6 != null && modified.IPv6.Enabled, "IPv6 settings were not applied", "Verifying appliance of IPv6 settings"); restoreEnabled = true; if (modified.IPv6.Config.DHCP == IPv6DHCPConfiguration.Off) { // Manual tag exists if (modified.IPv6.Config.Manual != null && modified.IPv6.Config.Manual.Length != 0 && !string.IsNullOrEmpty(modified.IPv6.Config.Manual[0].Address)) { string IPv6 = modified.IPv6.Config.Manual[0].Address; SelectIPv6(ref oldServiceAddr, ref newServiceAddr, IPv6); } // LinkLocal tag exists else if (modified.IPv6.Config.LinkLocal != null && modified.IPv6.Config.LinkLocal.Length != 0 && !string.IsNullOrEmpty(modified.IPv6.Config.LinkLocal[0].Address)) { string IPv6 = modified.IPv6.Config.LinkLocal[0].Address; SelectIPv6(ref oldServiceAddr, ref newServiceAddr, IPv6); } else { Test.Assert(false, "Manual or LinkLocal IPv6 addresses were not found", "Searching for Manual or LinkLocal IPv6 address"); } } else { // FromDHCP tag exists if (modified.IPv6.Config.FromDHCP != null && modified.IPv6.Config.FromDHCP.Length != 0 && !string.IsNullOrEmpty(modified.IPv6.Config.FromDHCP[0].Address)) { string IPv6 = modified.IPv6.Config.FromDHCP[0].Address; SelectIPv6(ref oldServiceAddr, ref newServiceAddr, IPv6); } // LinkLocal tag exists else if (modified.IPv6.Config.LinkLocal != null && modified.IPv6.Config.LinkLocal.Length != 0 && !string.IsNullOrEmpty(modified.IPv6.Config.LinkLocal[0].Address)) { string IPv6 = modified.IPv6.Config.LinkLocal[0].Address; SelectIPv6(ref oldServiceAddr, ref newServiceAddr, IPv6); } else { Test.Assert(false, "FromDHCP or LinkLocal IPv6 addresses were not found", "Searching for Manual or LinkLocal IPv6 address"); } } }
/// <summary> /// Return an Id for this device, namely, the first non-empty MAC address it can find across all network interfaces (if any). /// </summary> public static string GetDeviceId() => NetworkInterface.GetAllNetworkInterfaces()? .Select(n => n?.GetPhysicalAddress()?.ToString()) .Where(address => address != null && !string.IsNullOrWhiteSpace(address) && !address.StartsWith("000000")) .FirstOrDefault();
//Save the image private async void button_iconSave_Tap(object sender, RoutedEventArgs e) { try { if (vBitmapImage != null && vBitmapImage.PixelHeight > 0) { //Get the url path string UrlPath = string.Empty; try { UrlPath = vBitmapImage.UriSource.AbsolutePath; } catch { } if (string.IsNullOrWhiteSpace(UrlPath)) { UrlPath = vBitmapImage.UriSource.ToString(); } //Get the file name string FileName = "Unknown"; try { FileName = Path.GetFileNameWithoutExtension(UrlPath); } catch { } if (string.IsNullOrWhiteSpace(FileName)) { FileName = "Unknown"; } //Check if network is available bool IsNetworkAvailable = NetworkInterface.GetIsNetworkAvailable(); //Get the file extension string FileExtensionFile = ".jpg"; string FileExtensionDisplay = "JPG"; if (IsNetworkAvailable) { try { FileExtensionFile = Path.GetExtension(UrlPath).ToLower(); } catch { } if (string.IsNullOrWhiteSpace(FileExtensionFile)) { FileExtensionFile = ".jpg"; } FileExtensionDisplay = FileExtensionFile.ToUpper().Replace(".", string.Empty); } else { int MessageResult = await new MessagePopup().Popup("Offline saving", "Saving images while in offline mode may save the image in a lower quality and animations will be saved as a static image.", "Save image", "", "", "", "", true); if (MessageResult == 0) { return; } } FileSavePicker FileSavePicker = new FileSavePicker(); FileSavePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; FileSavePicker.FileTypeChoices.Add(FileExtensionDisplay, new List <string>() { FileExtensionFile }); FileSavePicker.SuggestedFileName = FileName; StorageFile NewFile = await FileSavePicker.PickSaveFileAsync(); if (NewFile != null) { //Download the bitmapimage source uri if (IsNetworkAvailable) { System.Diagnostics.Debug.WriteLine("Saving online image..."); byte[] ImageBuffer = await AVDownloader.DownloadByteAsync(10000, "News Scroll", null, vBitmapImage.UriSource); if (ImageBuffer != null) { await FileIO.WriteBytesAsync(NewFile, ImageBuffer); } else { await new MessagePopup().Popup("Failed to save", "Failed to save the image, please check your internet connection and try again.", "Ok", "", "", "", "", false); System.Diagnostics.Debug.WriteLine("Failed to download the image."); } } //Capture the image displayed in xaml else { System.Diagnostics.Debug.WriteLine("Saving offline image..."); ////Set the image size temporarily to bitmap size //Double PreviousWidth = image_ImageViewer.ActualWidth; //Double PreviousHeight = image_ImageViewer.ActualHeight; //image_ImageViewer.Width = vBitmapImage.PixelWidth; //image_ImageViewer.Height = vBitmapImage.PixelHeight; //Fix RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap(); await renderTargetBitmap.RenderAsync(image_source); IBuffer PixelBuffer = await renderTargetBitmap.GetPixelsAsync(); using (IRandomAccessStream fileStream = await NewFile.OpenAsync(FileAccessMode.ReadWrite)) { BitmapEncoder bitmapEncoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, fileStream); bitmapEncoder.SetPixelData( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)renderTargetBitmap.PixelWidth, (uint)renderTargetBitmap.PixelHeight, DisplayInformation.GetForCurrentView().LogicalDpi, DisplayInformation.GetForCurrentView().LogicalDpi, PixelBuffer.ToArray()); await bitmapEncoder.FlushAsync(); } //System.Diagnostics.Debug.WriteLine("From: " + image_ImageViewer.Width + " setting back: " + PreviousWidth); //image_ImageViewer.Width = PreviousWidth; //image_ImageViewer.Height = PreviousHeight; } } } } catch { await new MessagePopup().Popup("Failed to save", "Failed to save the image, please check your internet connection and try again.", "Ok", "", "", "", "", false); System.Diagnostics.Debug.WriteLine("Failed to save the image."); } }
public bool isInternetConnected() { bool conn = NetworkInterface.GetIsNetworkAvailable(); return(conn); }
private async Task <int> BindingContent(bool requireUpdate = false, string updateStatus = "đang cập nhật...") { try { int updated = 0; this.SetProgressIndicator(true, updateStatus); if (_pageNumber == 0) { _pageNumber = 1; } var feedId = _currentPublisher.FeedIds[_currentIndex]; if (requireUpdate && !NetworkInterface.GetIsNetworkAvailable()) { Messenger.ShowToast("không có mạng..."); requireUpdate = false; } updated = await _viewModel.RefreshLatestData(feedId, _currentPublisher.Id, requireUpdate); _feedManager.SetLastId <Guid>(feedId.ToString()); if (_viewModel.AllItemViewModels.Count == 0) { //this.SetProgressIndicator(false); //Messenger.ShowToast("chưa có tin nào...", completedAction: () => this.BackToPreviousPage()); return(updated); } if (updated > 0) { _viewModel.PagedItemViewModels.Clear(); _pageNumber = 1; } _viewModel.LoadPage(_pageNumber, AppConfig.ShowUnreadItemOnly); UpdateItemReadCount(); UpdateViewTitle(); this.llsItemList.ItemsSource = _viewModel.PagedItemViewModels; CreateAppBar(); if (updated > 0) { llsItemList.ScrollToTop(); } else { llsItemList.ScrollTo <string>(_lastItemId); } this.SetProgressIndicator(false); return(updated); } catch (Exception ex) { throw ex; } }
// Device items private static void handleDeviceItem(NodeHandler handler, DeviceItem item) { NodeHandler child_handler = handler.Enter(item, item.Name); if (child_handler != null) { SoftwareContainer sw_cont = item.GetService <SoftwareContainer>(); if (sw_cont != null) { PlcSoftware controller = sw_cont.Software as PlcSoftware; if (controller != null) { NodeHandler block_handler = child_handler.Enter(controller.BlockGroup, "Blocks"); if (block_handler != null) { iterDataBlock(block_handler, controller.BlockGroup.Blocks); iterBlockFolder(block_handler, controller.BlockGroup.Groups); } child_handler.Exit(controller.BlockGroup); NodeHandler type_handler = child_handler.Enter(controller.TypeGroup, "Types"); if (type_handler != null) { iterType(type_handler, controller.TypeGroup.Types); iterTypeFolder(block_handler, controller.TypeGroup.Groups); } child_handler.Exit(controller.TypeGroup); } HmiTarget hmi_target = sw_cont.Software as HmiTarget; if (hmi_target != null) { //Console.WriteLine("HMI target"); NodeHandler screen_handler = child_handler.Enter(hmi_target.ScreenFolder, "Screens"); if (screen_handler != null) { //Console.WriteLine("Iterating screens"); iterScreen(screen_handler, hmi_target.ScreenFolder.Screens); iterScreenFolder(screen_handler, hmi_target.ScreenFolder.Folders); } child_handler.Exit(hmi_target.ScreenFolder); NodeHandler template_handler = child_handler.Enter(hmi_target.ScreenTemplateFolder, "Templates"); if (template_handler != null) { //Console.WriteLine("Iterating templates"); iterScreenTemplate(template_handler, hmi_target.ScreenTemplateFolder.ScreenTemplates); iterScreenTemplateFolder(template_handler, hmi_target.ScreenTemplateFolder.Folders); } child_handler.Exit(hmi_target.ScreenTemplateFolder); NodeHandler popup_handler = child_handler.Enter(hmi_target.ScreenPopupFolder, "Popups"); if (popup_handler != null) { //Console.WriteLine("Iterating popups"); iterScreenPopup(template_handler, hmi_target.ScreenPopupFolder.ScreenPopups); iterScreenPopupFolder(template_handler, hmi_target.ScreenPopupFolder.Folders); } child_handler.Exit(hmi_target.ScreenPopupFolder); NodeHandler connection_handler = child_handler.Enter(hmi_target.Connections, "Connections"); if (connection_handler != null) { foreach (Connection connection in hmi_target.Connections) { connection_handler.Enter(connection, connection.Name); connection_handler.Exit(connection); } } child_handler.Exit(hmi_target.Connections); } } NetworkInterface netif = item.GetService <NetworkInterface>(); if (netif != null) { NodeHandler netif_handler = child_handler.Enter(netif, "Nodes"); if (netif_handler != null) { IterNetNodes(netif_handler, netif.Nodes); } child_handler.Exit(netif); } } handler.Exit(item); }
public void _closeNetwork(NetworkInterface networkInterface) { networkInterface.close(); }
public static void Connect() { form.Log("connecting...", Color.DarkGray); string serverIP = form.textBoxServerIP.Text; int serverPort = (int)form.numericUpDownPort.Value; try { tcpToServer = new TcpClient() { NoDelay = true }; tcpToServer.Connect(serverIP, serverPort); udpToServer = new UdpClient(tcpToServer.Client.LocalEndPoint as IPEndPoint); udpToServer.Connect(serverIP, serverPort); } catch (SocketException) {//connection refused Close(); form.Log("failed\n", Color.Red); form.EnableButtons(); return; } form.Log("connected\n", Color.Green); Stream stream = tcpToServer.GetStream(); swriter = new BinaryWriter(stream); sreader = new BinaryReader(stream); form.Log("checking version...", Color.DarkGray); swriter.Write(Database.bridgeVersion); if (!sreader.ReadBoolean()) { form.Log("mismatch\n", Color.Red); form.buttonDisconnect.Invoke(new Action(form.buttonDisconnect.PerformClick)); return; } form.Log("match\n", Color.Green); form.Log("logging in...", Color.DarkGray); swriter.Write(form.textBoxUsername.Text); swriter.Write(form.textBoxPassword.Text); swriter.Write(NetworkInterface.GetAllNetworkInterfaces().Where(nic => nic.OperationalStatus == OperationalStatus.Up).Select(nic => nic.GetPhysicalAddress().ToString()).FirstOrDefault()); switch ((AuthResponse)sreader.ReadByte()) { case AuthResponse.success: if (sreader.ReadBoolean()) //if banned { MessageBox.Show(sreader.ReadString()); //ban message form.Log("you are banned\n", Color.Red); goto default; } break; case AuthResponse.unknownUser: form.Log("unknown username\n", Color.Red); goto default; case AuthResponse.wrongPassword: form.Log("wrong password\n", Color.Red); goto default; default: form.buttonDisconnect.Invoke(new Action(form.buttonDisconnect.PerformClick)); return; } form.Log("success\n", Color.Green); connected = true; swriter.Write((byte)0);//request query new Thread(new ThreadStart(ListenFromServerTCP)).Start(); new Thread(new ThreadStart(ListenFromServerUDP)).Start(); ListenFromClientTCP(); }
private static int GetIndex(NetworkInterface ni) { IPInterfaceProperties ipprops = ni.GetIPProperties(); IPv4InterfaceProperties ipv4props = GetIPv4Properties(ipprops); if (ipv4props != null) { return ipv4props.Index; } else if (Java_java_net_InetAddressImplFactory.isIPv6Supported()) { IPv6InterfaceProperties ipv6props = GetIPv6Properties(ipprops); if (ipv6props != null) { return ipv6props.Index; } } return -1; }
/// <summary> /// 返回描述本地计算机上的网络接口的对象(网络接口也称为网络适配器)。 /// </summary> /// <returns></returns> public static NetworkInterface[] NetCardInfo() { return(NetworkInterface.GetAllNetworkInterfaces()); }
public Chat(NetworkInterface netIf) { networkIf = netIf; }
/// <summary> /// ストリーミングAPIへ接続します。<para /> /// 接続に失敗した場合、規定アルゴリズムに沿って自動で再接続を試みます。<para /> /// それでも失敗する場合はfalseを返します。この場合、再接続を試みてはいけません。 /// </summary> /// <param name="track">トラック対象キーワード</param> private void ConnectCore(AccountInfo info, string track) { try { int failureWaitSec = 0; while (true) { // 接続 try { using (var n = NotifyStorage.NotifyManually("@" + info.ScreenName + ": インターネットへの接続を確認しています...")) { while (!NetworkInterface.GetIsNetworkAvailable()) { info.ConnectionState = ConnectionState.WaitNetwork; ConnectionManager.OnConnectionStateChanged(EventArgs.Empty); // ネットワークが利用可能になるまでポーリング Thread.Sleep(10000); } } using (var n = NotifyStorage.NotifyManually("@" + info.ScreenName + ": 接続しています...")) { info.ConnectionState = ConnectionState.TryConnection; ConnectionManager.OnConnectionStateChanged(EventArgs.Empty); System.Diagnostics.Debug.WriteLine(info.ScreenName + " - User Streams Connection with Track: " + track); connection = streamingCore.ConnectNew( info, StreamingDescription.ForUserStreams(TwitterDefine.UserStreamsTimeout, track: track, repliesAll: info.AccountProperty.UserStreamsRepliesAll)); } } catch (WebException we) { if ((int)we.Status == 420) { // 多重接続されている throw new WebException("@" + info.ScreenName + ": 多重接続されています。接続できません。"); } if (we.Status == WebExceptionStatus.Timeout) // タイムアウト例外なら再試行する { NotifyStorage.Notify("@" + info.ScreenName + ": User Streams接続がタイムアウトしました。再試行します..."); } else { string descText = we.Status.ToString(); if (we.Status == WebExceptionStatus.UnknownError) { descText = we.Message; } if (we.Status == WebExceptionStatus.ProtocolError) { var hwr = we.Response as HttpWebResponse; if (hwr != null) { descText += " - " + hwr.StatusCode + " : " + hwr.StatusDescription; } } throw new WebException("接続に失敗しました。(" + descText + ")"); } } catch { throw; } if (connection != null) { // Connection successful info.ConnectionState = ConnectionState.Connected; ConnectionManager.OnConnectionStateChanged(EventArgs.Empty); return; } if (failureWaitSec > 0) { if (failureWaitSec > Setting.Instance.ConnectionProperty.UserStreamsConnectionFailedMaxWaitSec) { throw new WebException("User Streamsへの接続に失敗しました。"); } else { NotifyStorage.Notify("@" + info.ScreenName + ": User Streamsへの接続に失敗。再試行まで" + failureWaitSec.ToString() + "秒待機...", failureWaitSec / 1000); // ウェイトカウント Thread.Sleep(failureWaitSec * 1000); NotifyStorage.Notify("@" + info.ScreenName + ": User Streamsへの接続を再試行します..."); } } else { NotifyStorage.Notify("@" + info.ScreenName + ": User Streamsへの接続に失敗しました。再試行します..."); } // 最初に失敗したらすぐに再接続 // 2回目以降はその倍に増やしていく // 300を超えたら接続失敗で戻る if (failureWaitSec == 0) { failureWaitSec = Setting.Instance.ConnectionProperty.UserStreamsConnectionFailedInitialWaitSec; } else { failureWaitSec *= 2; } } } catch (ThreadAbortException) { throw; } catch (Exception e) { this.AccountInfo.ConnectionState = ConnectionState.Disconnected; ConnectionManager.OnConnectionStateChanged(EventArgs.Empty); throw new WebException("User Streamsへの接続に失敗しました。", e); } }
public AnnouncementIdentifier(NetworkInterface inter, Announcement announcement) { _interface = inter.Index; _address = announcement.Source; _hash = announcement.Hash; }
/// <summary> /// Initializes a new instance of the <see cref="IfOutNUcastPkts"/> class. /// </summary> /// <param name="index">The index.</param> /// <param name="networkInterface">The network interface.</param> public IfOutNUcastPkts(int index, NetworkInterface networkInterface) : base("1.3.6.1.2.1.2.2.1.18.{0}", index) { _networkInterface = networkInterface; }
// private AI ai = new AI(); //for debug void Awake() { sound = (Sound)FindObjectOfType(typeof(Sound)); graphicalEffectFactory = (GraphicalEffectFactory)FindObjectOfType(typeof(GraphicalEffectFactory)); networkInterface = (NetworkInterface)FindObjectOfType(typeof(NetworkInterface)); if (sound == null){ Debug.LogError("sound-object not found"); } if (graphicalEffectFactory == null){ Debug.LogError("graphicalEffectFactory-object not found"); } Console.Init(this); }
#pragma warning restore 618 #if !UNITY_WEBPLAYER static bool IsValidInterface(NetworkInterface nic, IPInterfaceProperties p) { foreach (var addr in p.GatewayAddresses) { byte[] bytes = addr.Address.GetAddressBytes(); if (bytes.Length == 4 && bytes[0] != 0 && bytes[1] != 0 && bytes[2] != 0 && bytes[3] != 0) { return true; } } return false; }
internal async Task Bind(NetworkInterface targetNetworkInterface, TargetTreeView targetTreeView) { try { this.IsBinding = true; _TargetTreeView = targetTreeView; _TargetNetworkInterface = targetNetworkInterface; await publicIpSelectionControl1.Bind(targetTreeView); await networkSelectionControl1.Bind(targetTreeView); if (_TargetNetworkInterface.TargetNetworkInterfaceIpConfigurations.Count > 0) { networkSelectionControl1.VirtualNetworkTarget = _TargetNetworkInterface.TargetNetworkInterfaceIpConfigurations[0]; if (_TargetNetworkInterface.TargetNetworkInterfaceIpConfigurations[0].TargetPublicIp == null) { rbPublicIpDisabled.Checked = true; } else { rbPublicIpEnabled.Checked = true; } publicIpSelectionControl1.PublicIp = _TargetNetworkInterface.TargetNetworkInterfaceIpConfigurations[0].TargetPublicIp; } lblSourceName.Text = _TargetNetworkInterface.SourceName; txtTargetName.Text = _TargetNetworkInterface.TargetName; if (_TargetNetworkInterface.EnableIPForwarding) { rbIPForwardingEnabled.Checked = true; } else { rbIPForwardingDisabled.Checked = true; } if (_TargetNetworkInterface.EnableAcceleratedNetworking) { rbAcceleratedNetworkingEnabled.Checked = true; } else { rbAcceleratedNetworkingDisabled.Checked = true; } if (_TargetNetworkInterface.SourceNetworkInterface != null) { if (_TargetNetworkInterface.SourceNetworkInterface.GetType() == typeof(Azure.Asm.NetworkInterface)) { Azure.Asm.NetworkInterface asmNetworkInterface = (Azure.Asm.NetworkInterface)_TargetNetworkInterface.SourceNetworkInterface; lblVirtualNetworkName.Text = asmNetworkInterface.NetworkInterfaceIpConfigurations[0].VirtualNetworkName; lblSubnetName.Text = asmNetworkInterface.NetworkInterfaceIpConfigurations[0].SubnetName; lblStaticIpAddress.Text = asmNetworkInterface.NetworkInterfaceIpConfigurations[0].PrivateIpAddress; } else if (_TargetNetworkInterface.SourceNetworkInterface.GetType() == typeof(Azure.Arm.NetworkInterface)) { Azure.Arm.NetworkInterface armNetworkInterface = (Azure.Arm.NetworkInterface)_TargetNetworkInterface.SourceNetworkInterface; lblVirtualNetworkName.Text = armNetworkInterface.NetworkInterfaceIpConfigurations[0].VirtualNetworkName; lblSubnetName.Text = armNetworkInterface.NetworkInterfaceIpConfigurations[0].SubnetName; lblStaticIpAddress.Text = armNetworkInterface.NetworkInterfaceIpConfigurations[0].PrivateIpAddress; } } virtualMachineSummary.Bind(_TargetNetworkInterface.ParentVirtualMachine, _TargetTreeView); networkSecurityGroup.Bind(_TargetNetworkInterface.NetworkSecurityGroup, _TargetTreeView); await this.publicIpSelectionControl1.Bind(_TargetTreeView); this.UpdatePropertyEnablement(); } finally { this.IsBinding = false; } }
public NetworkInformation() { NIC = NetworkInterface.GetAllNetworkInterfaces(); }
static byte[] ParsePhysicalAddress(NetworkInterface n) { try { return n.GetPhysicalAddress().GetAddressBytes(); } catch { return new byte[0]; } }
/// <summary> /// Pings a host and reports back the number of successful pings. On error returns -1. /// </summary> /// <param name="Hostname">The name of the host to ping.</param> /// <param name="Count">The number of times to ping.</param> /// <returns></returns> public float PingIt(string Hostname, int Count) { this.ErrorMsg = string.Empty; //Holds the amount of successful pings. float success = 0; //Holds the specific ping options, 64 is the TTL. True doesn't fragment the packet. PingOptions options = new PingOptions(64, true); //A 32 byte variable that contains the data to ping with. byte[] buffer = new byte[32]; //The object that conducts network commands. Ping attempt = new Ping(); //A list to contain the resolved IP address's. IPAddress[] host = null; //Holds the result of the ping. PingReply reply = null; //Checks to see if the network is available. if (NetworkInterface.GetIsNetworkAvailable()) { //Resolves the hostname to a list of IP's try { host = Dns.GetHostAddresses(Hostname); } catch (Exception err) { this.ErrorMsg = string.Format("Could not resolve the host {0}: {1}", Hostname, err.Message); return(-1); } //Loop to cycle for the desired number of pings. for (int i = 1; i <= Count; i++) { //Ping machine try { //Sends a ping message at a host, with a time out of 1000, data buffer, and options of options. reply = attempt.Send(host[0], 1000, buffer, options); //Checks the reply for success if (reply.Status == IPStatus.Success) { //If success, increment success success++; } } catch (Exception err) { this.ErrorMsg = string.Format("Error pinging host {0} with IP {1}: {2}", Hostname, host[0].ToString(), err.Message); return(-1); } } return(success); } this.ErrorMsg = string.Format("No network connection"); return(-1); }
void OnNetworkInterfaceRemoved(NetworkInterface networkInterface) { SynchronizationContextPost(o => { if (NetworkInterfaceRemoved != null) { NetworkInterfaceRemoved(this, new NetworkInterfaceEventArgs(networkInterface)); } }); }
private static NetworkInterface GetInternalNetworkSwitchInterface() { return(NetworkInterface.GetAllNetworkInterfaces().Where(i => i.Name.Contains("Windows Phone Emulator")).FirstOrDefault()); }
/// <summary> /// Gets the local broadcast address /// </summary> public static IPAddress GetBroadcastAddress() { #if __ANDROID__ try{ Android.Net.Wifi.WifiManager wifi = (Android.Net.Wifi.WifiManager)Android.App.Application.Context.GetSystemService(Android.App.Activity.WifiService); if (wifi.IsWifiEnabled) { var dhcp = wifi.DhcpInfo; int broadcast = (dhcp.IpAddress & dhcp.Netmask) | ~dhcp.Netmask; byte[] quads = new byte[4]; for (int k = 0; k < 4; k++) { quads[k] = (byte)((broadcast >> k * 8) & 0xFF); } return(new IPAddress(quads)); } } catch // Catch Access Denied Errors { return(IPAddress.Broadcast); } #endif #if IS_FULL_NET_AVAILABLE try { NetworkInterface ni = GetNetworkInterface(); if (ni == null) { return(null); } IPInterfaceProperties properties = ni.GetIPProperties(); foreach (UnicastIPAddressInformation unicastAddress in properties.UnicastAddresses) { if (unicastAddress != null && unicastAddress.Address != null && unicastAddress.Address.AddressFamily == AddressFamily.InterNetwork) { var mask = unicastAddress.IPv4Mask; byte[] ipAdressBytes = unicastAddress.Address.GetAddressBytes(); byte[] subnetMaskBytes = mask.GetAddressBytes(); if (ipAdressBytes.Length != subnetMaskBytes.Length) { throw new ArgumentException("Lengths of IP address and subnet mask do not match."); } byte[] broadcastAddress = new byte[ipAdressBytes.Length]; for (int i = 0; i < broadcastAddress.Length; i++) { broadcastAddress[i] = (byte)(ipAdressBytes[i] | (subnetMaskBytes[i] ^ 255)); } return(new IPAddress(broadcastAddress)); } } } catch // Catch any errors { return(IPAddress.Broadcast); } #endif return(IPAddress.Broadcast); }
private static string GetName(NetworkInterface networkInterface) { return(networkInterface.Name); }
DotNetInterface ParseInterface(NetworkInterface n) { HashSet<UdpIPv4Address> gateway = new HashSet<UdpIPv4Address>(UdpIPv4Address.Comparer.Instance); HashSet<UdpIPv4Address> unicast = new HashSet<UdpIPv4Address>(UdpIPv4Address.Comparer.Instance); HashSet<UdpIPv4Address> multicast = new HashSet<UdpIPv4Address>(UdpIPv4Address.Comparer.Instance); IPInterfaceProperties p = null; try { p = n.GetIPProperties(); } catch { return null; } if (p != null) { try { foreach (var gw in p.GatewayAddresses) { try { if (gw.Address.AddressFamily == AddressFamily.InterNetwork) { gateway.Add(ConvertAddress(gw.Address)); } } catch { } } } catch { } try { foreach (var addr in p.DnsAddresses) { try { if (addr.AddressFamily == AddressFamily.InterNetwork) { gateway.Add(ConvertAddress(addr)); } } catch { } } } catch { } try { foreach (var uni in p.UnicastAddresses) { try { if (uni.Address.AddressFamily == AddressFamily.InterNetwork) { UdpIPv4Address ipv4 = ConvertAddress(uni.Address); unicast.Add(ipv4); gateway.Add(new UdpIPv4Address(ipv4.Byte3, ipv4.Byte2, ipv4.Byte1, 1)); } } catch { } } } catch { } try { foreach (var multi in p.MulticastAddresses) { try { if (multi.Address.AddressFamily == AddressFamily.InterNetwork) { multicast.Add(ConvertAddress(multi.Address)); } } catch { } } } catch { } if (unicast.Count == 0 || gateway.Count == 0) { return null; } } return new DotNetInterface(n, gateway.ToArray(), unicast.ToArray(), multicast.ToArray()); }
/// <summary> /// The Put NetworkInterface operation creates/updates a /// networkInterface /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.INetworkInterfaceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// Required. The name of the network interface. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the create/update NetworkInterface /// operation /// </param> /// <returns> /// Response for PutNetworkInterface Api servive call /// </returns> public static NetworkInterfacePutResponse BeginCreateOrUpdating(this INetworkInterfaceOperations operations, string resourceGroupName, string networkInterfaceName, NetworkInterface parameters) { return(Task.Factory.StartNew((object s) => { return ((INetworkInterfaceOperations)s).BeginCreateOrUpdatingAsync(resourceGroupName, networkInterfaceName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult()); }
public ConnectGUI(NetworkInterface netIf) { networkIf = netIf; }
/// <summary> /// The Put NetworkInterface operation creates/updates a /// networkInterface /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.INetworkInterfaceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// Required. The name of the network interface. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the create/update NetworkInterface /// operation /// </param> /// <returns> /// Response for PutNetworkInterface Api servive call /// </returns> public static Task <NetworkInterfacePutResponse> BeginCreateOrUpdatingAsync(this INetworkInterfaceOperations operations, string resourceGroupName, string networkInterfaceName, NetworkInterface parameters) { return(operations.BeginCreateOrUpdatingAsync(resourceGroupName, networkInterfaceName, parameters, CancellationToken.None)); }