/// <summary> /// Checks whether this host has the same MAC Address as 'h'. /// </summary> /// <param name="h">Other host.</param> /// <returns></returns> public bool Equals(WOL2Host h) { // If the host has a mac address compare those if (h.GetMacAddress() != null && h.GetMacAddress().Length > 0 && GetMacAddress() != null && GetMacAddress().Length > 0 && h.GetMacAddress().ToLower() == GetMacAddress().ToLower()) { return(true); } // if it has an ip v6 address and this one is equal else if (h.GetIpV6Address() != null && h.GetIpV6Address().Length > 0 && GetIpV6Address() != null && GetIpV6Address().Length > 0 && h.GetIpV6Address() == GetIpV6Address()) { return(true); } // if it uses DHCP and the hostname is equal else if (IsDynamicHost() && GetName() != null && GetName().Length > 0 && GetName() == h.GetName()) { return(true); } // if it does not use DHCP and the IPv4 Address is equal else if (!IsDynamicHost() && GetIpAddress() != null && GetIpAddress().Length > 0 && GetIpAddress() == h.GetIpAddress()) { return(true); } else { return(false); } }
/// <summary> /// Executes this tool on the given Host. /// </summary> /// <param name="h">the host to call this tool for</param> /// <returns></returns> public bool Execute(WOL2Host h) { bool bRet = false; string param = GetCmdLine(); if (h != null) { param = h.ExpandVariables(param); } // Expand environment variables param = Environment.ExpandEnvironmentVariables(param); string cmd = Environment.ExpandEnvironmentVariables(m_sCmd); try { System.Diagnostics.Process.Start(cmd, param); } catch (Exception ex) { MessageBox.Show(ex.Message + "\n\n" + cmd + "\n" + param, "WOL2", MessageBoxButtons.OK, MessageBoxIcon.Error); } return(bRet); }
/// <summary> /// This function gets asynchronously called by the job processor. /// It will process all pending scan jobs. /// </summary> private void JobProcessorFunc() { while (m_Jobs.Count != 0) { Monitor.Enter(m_Jobs); WOL2Host h = m_Jobs[0]; Monitor.Exit(m_Jobs); // Wait for a free scan slot while (m_lScansRunning > 255) { Thread.Sleep(10); } // Kick up a new scanner thread m_lScansRunning++; MOE.Logger.DoLog("JobProcessor: Spawning new scan process for: " + h.GetIpAddress(), MOE.Logger.LogLevel.lvlDebug); HostScanner hs = new HostScanner(ScanHost); hs.BeginInvoke(h, new AsyncCallback(HostScanFinished), 0); Monitor.Enter(m_Jobs); m_Jobs.Remove(h); Monitor.Exit(m_Jobs); } // Done :-) MOE.Logger.DoLog("JobProcessor: All jobs done.", MOE.Logger.LogLevel.lvlDebug); // m_finishedCallback.Invoke( null ); m_JobProcessor = null; }
/// <summary> /// Scans an IPv4 range /// </summary> /// <param name="from">Starting address</param> /// <param name="to">end address</param> /// <param name="Subnet">Subnet Mask for the network</param> public void ScanIPv4Range(IPAddress from, IPAddress to, IPAddress Subnet) { MOE.Logger.DoLog("ScanIPv4Range: Scanning range from " + from + " to " + to, MOE.Logger.LogLevel.lvlInfo); // Initialize the scan m_lFinishedScans = 0; // Calculate the number of hosts to scan /* IPAddress r = new IPAddress(to.Address - from.Address ); * string [] s = r.ToString().Split('.'); * if (s.Length == 4) * { * m_lMaxScans = Int16.Parse(s[3]); * m_lMaxScans *= 1 + Int16.Parse(s[2]); * m_lMaxScans *= 1 + Int16.Parse(s[1]); * m_lMaxScans *= 1 + Int16.Parse(s[0]); * } */ // scan while the end of the range is not reached while (true) { from.Address += 0x01000000; // Advance to next IP // Contruct a temporary host element WOL2Host h = new WOL2Host(); h.SetIpAddress(from.ToString()); h.SetSubnetMask(Subnet.ToString()); // Add the job MOE.Logger.DoLog("ScanIPv4Range(): Added scan job: " + h.GetIpAddress(), MOE.Logger.LogLevel.lvlDebug); Monitor.Enter(m_Jobs); m_Jobs.Add(h); m_lMaxScans++; Monitor.Exit(m_Jobs); // Stop if the end IP is reached... if (from.ToString() == to.ToString()) { break; } // Increment the second octett if the first is full if ((from.Address & 0x00000000ff000000) == 0x00000000ff000000) { from.Address += 0x0000000000010000; } } // Start the async job processor ProcessJobs(); }
public DlgEditHost(WOL2Host h) { // The InitializeComponent() call is required for Windows Forms designer support. InitializeComponent(); // Assign the host to this instance m_Host = h; // Check if the host is a new one /* if( !m_Host.IsValid() ) * { * // Create a new host * } * else * {*/ // Edit an existing host txtComment.Text = m_Host.GetDescription(); txtIp.Text = m_Host.GetIpAddress(); txtIPv6.Text = m_Host.GetIpV6Address(); txtMac.Text = m_Host.GetMacAddress(); txtSnMask.Text = m_Host.GetSubnetMask(); txtName.Text = m_Host.GetName(); txtGroups.Text = m_Host.GetGroups(); chkDHCP.Checked = m_Host.IsDynamicHost(); chkNotify.Checked = m_Host.IsStateChangedNoftificationEnabled(); txtSecureOn.Text = m_Host.GetSecureOnPassword(); WOLPacketTransferMode f = m_Host.PacketTransferMode; if ((f & WOLPacketTransferMode.modeBCast) == WOLPacketTransferMode.modeBCast) { cboWolMode.SelectedIndex = 1; } else if ((f & WOLPacketTransferMode.modeNetCast) == WOLPacketTransferMode.modeNetCast) { cboWolMode.SelectedIndex = 2; } else if ((f & WOLPacketTransferMode.modeSendToHost) == WOLPacketTransferMode.modeSendToHost) { cboWolMode.SelectedIndex = 3; } else { cboWolMode.SelectedIndex = 0; } // } }
void BtnOkClick(object s, EventArgs x) { int iCount = 0; bool bChanged = false; foreach (WOL2Host h in lbHosts.CheckedItems) { // Check if this host already exists WOL2Host foundHost = null; if (!m_HostList.Exists(delegate(WOL2Host theHost) { foundHost = theHost; return(h.Equals(theHost)); })) { //if (h != null) //{ MOE.Logger.DoLog("DlgNetworkScanner: Adding new Host " + h, MOE.Logger.LogLevel.lvlInfo); m_HostList.Add(h); iCount++; bChanged = true; //} } else { // Check if a host was found, that is equal to the current one if (foundHost != null) { MOE.Logger.DoLog("DlgNetworkScanner: Updating host " + foundHost + "...", MOE.Logger.LogLevel.lvlInfo); // If so, update it. foundHost.SetIpAddress(h.GetIpAddress()); foundHost.SetIpV6Address(h.GetIpV6Address()); foundHost.SetSubnetMask(h.GetSubnetMask()); foundHost.SetMacAddress(h.GetMacAddress()); foundHost.SetName(h.GetName()); bChanged = true; MOE.Logger.DoLog("DlgNetworkScanner: Updated host " + foundHost, MOE.Logger.LogLevel.lvlInfo); } } } ChangedHostList = bChanged; }
public DlgEditHost( WOL2Host h ) { // The InitializeComponent() call is required for Windows Forms designer support. InitializeComponent(); // Assign the host to this instance m_Host = h; // Check if the host is a new one /* if( !m_Host.IsValid() ) { // Create a new host } else {*/ // Edit an existing host txtComment.Text = m_Host.GetDescription(); txtIp.Text = m_Host.GetIpAddress(); txtIPv6.Text = m_Host.GetIpV6Address(); txtMac.Text = m_Host.GetMacAddress(); txtSnMask.Text = m_Host.GetSubnetMask(); txtName.Text = m_Host.GetName(); txtGroups.Text = m_Host.GetGroups(); chkDHCP.Checked = m_Host.IsDynamicHost(); chkNotify.Checked = m_Host.IsStateChangedNoftificationEnabled(); txtSecureOn.Text = m_Host.GetSecureOnPassword(); WOLPacketTransferMode f = m_Host.PacketTransferMode; if ((f & WOLPacketTransferMode.modeBCast) == WOLPacketTransferMode.modeBCast) cboWolMode.SelectedIndex = 1; else if ((f & WOLPacketTransferMode.modeNetCast) == WOLPacketTransferMode.modeNetCast) cboWolMode.SelectedIndex = 2; else if ((f & WOLPacketTransferMode.modeSendToHost) == WOLPacketTransferMode.modeSendToHost) cboWolMode.SelectedIndex = 3; else cboWolMode.SelectedIndex = 0; // } }
/// <summary> /// Sends a magic packet to the destination host. /// </summary> /// <param name="h">The WOLHost to wake.</param> public void SendWOLPacket( WOL2Host h ) { if( h == null ) return; MOE.Logger.DoLog( "Waking host " + h, MOE.Logger.LogLevel.lvlInfo ); byte[] targetMAC = new byte[6]; string[] mac = h.GetMacAddress().Split( ':' ); // target mac must be 6-bytes! if( mac.Length != 6 ) { mac = h.GetMacAddress().Split( '-' ); } // target mac must be 6-bytes! if( mac.Length != 6 ) return; // Convert String Array to byte Array for( int i = 0; i < 6; i++ ) targetMAC[i] = Convert.ToByte( mac[i], 16 ); // check password byte[] password = null; string[] pwd = null; if( m_bAskForSecureOnPwd ) { MOE.InputBoxDialog ib = new MOE.InputBoxDialog(); ib.FormPrompt = MOE.Utility.GetStringFromRes( "strSecureOnPrompt" ); ib.FormCaption = "SecureOn"; ib.ShowDialog( this ); string sn = ib.InputResponse; if( sn.Length == 12 ) { pwd = new String[6]; for( int i = 0; i < 6; i++ ) pwd[i] = sn.Substring((i)*2, 2 ); } else if( sn.Length == 12+5 ) { pwd = sn.Split( ':' ); if( pwd == null ) pwd = sn.Split( '-' ); } } else { if( h.GetSecureOnPassword() != null ) { pwd = h.GetSecureOnPassword().Split( ':' ); if( pwd == null ) pwd = h.GetSecureOnPassword().Split( '-' ); } } if( pwd != null ) { if( (pwd.Length == 4) || (pwd.Length == 6) ) { password = new Byte[ pwd.Length ]; // Convert String Array to byte Array for( int i = 0; i < pwd.Length; i++ ) password[i] = Convert.ToByte( pwd[i], 16 ); } } int packetLength = 6 + (20 * 6); if( password != null ) { packetLength += password.Length; } byte[] magicPacket = new byte[packetLength]; // has a 6-byte header of 0xFF byte[] header = new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; Buffer.BlockCopy(header, 0, magicPacket, 0, header.Length); // repeat the destination MAC 16 times int offset = 6; for(int i = 0 ; i < 16 ; i++) { Buffer.BlockCopy(targetMAC, 0, magicPacket, offset, targetMAC.Length); offset += 6; } if( password != null ) { Buffer.BlockCopy(password, 0, magicPacket, offset, password.Length); } try { IPEndPoint ep = null; WOLPacketTransferMode transfer = h.PacketTransferMode == WOLPacketTransferMode.modeNone ? m_PacketTransferOptions : h.PacketTransferMode; if ((transfer & WOLPacketTransferMode.modeSendToHost) == WOLPacketTransferMode.modeSendToHost) { string dest = null; if (h.IsDynamicHost()) { // Send WOL package to all known DHCP addresses dest = h.GetName(); try { foreach (IPAddress ip in Dns.GetHostEntry(dest).AddressList) { ep = new IPEndPoint(ip, m_iWakePort); MOE.Logger.DoLog("Sending DHCP WOL package to " + ep.ToString(), MOE.Logger.LogLevel.lvlInfo); try { UdpClient c = new UdpClient(); c.Send(magicPacket, magicPacket.Length, ep); } catch { } } } catch { } return; } else { dest = h.GetIpV6Address(); if (dest == null || dest.Length == 0 || !m_bUseIpV6) dest = h.GetIpAddress(); if (dest != null && dest.Length > 0) ep = new IPEndPoint(IPAddress.Parse(dest), m_iWakePort); } } else if ((transfer & WOLPacketTransferMode.modeNetCast) == WOLPacketTransferMode.modeNetCast) { // Resolve the hostname to an IP address if (h.IsDynamicHost()) { try { foreach (IPAddress ip in Dns.GetHostEntry(h.GetName()).AddressList) { try { if (ip.AddressFamily == AddressFamily.InterNetwork) { IPAddress nm = IPAddress.Parse(WOL2DNSHelper.ResolveSubnetMask(ip)); IPAddress snbcast = WOL2DNSHelper.GetBroadcastAddress(ip, nm); ep = new IPEndPoint(snbcast, m_iWakePort); } else // IPv6 link local bcast http://www.iana.org/assignments/ipv6-multicast-addresses/ipv6-multicast-addresses.xml ep = new IPEndPoint(IPAddress.Parse("FF02:0:0:0:0:0:0:1" ), m_iWakePort ); /* MOE.Logger.DoLog("Sending DHCP WOL package to " + ep.ToString(), MOE.Logger.LogLevel.lvlInfo); UdpClient c = new UdpClient(); c.Send(magicPacket, magicPacket.Length, ep); */ } catch { } } } catch (Exception ex) { MOE.Logger.DoLog("Cannoot wake host " + h.ToString() +"! Reason: " + ex.Message, MOE.Logger.LogLevel.lvlWarning); } //return; } if( ep == null || !h.IsDynamicHost() ) { string sip = null; sip = h.GetIpV6Address(); if (sip == null || sip.Length == 0 || !m_bUseIpV6) sip = h.GetIpAddress(); if (sip != null) { IPAddress ip = IPAddress.Parse(sip); if (ip.AddressFamily == AddressFamily.InterNetwork) { try { // Generate a broadcast address IPAddress nm = IPAddress.Parse(h.GetSubnetMask()); IPAddress snbcast = WOL2DNSHelper.GetBroadcastAddress(ip, nm); if (snbcast != null) ep = new IPEndPoint(snbcast, m_iWakePort); } catch { } } else if (ip.AddressFamily == AddressFamily.InterNetworkV6) { // IPv6 link local bcast http://www.iana.org/assignments/ipv6-multicast-addresses/ipv6-multicast-addresses.xml ep = new IPEndPoint(IPAddress.Parse("FF02:0:0:0:0:0:0:1"), m_iWakePort); } } } } else { ep = new IPEndPoint(IPAddress.Broadcast, m_iWakePort); } if (ep == null) { MOE.Logger.DoLog("Could not identify an endpoint for " + h.ToString(), MOE.Logger.LogLevel.lvlWarning); return; } MOE.Logger.DoLog( "Will send WOL package to " + ep.ToString(), MOE.Logger.LogLevel.lvlInfo ); // Use the global transfer mode to get the type (tcp/udp) // if( ( m_PacketTransferOptions & WOLPacketTransferMode.modeUDP ) == WOLPacketTransferMode.modeUDP ) // use udp, tested and works // { UdpClient udpClient = new UdpClient(); udpClient.Send(magicPacket, magicPacket.Length, ep); MOE.Logger.DoLog("Local Endpoint used: " + udpClient.Client.LocalEndPoint.ToString(), MOE.Logger.LogLevel.lvlInfo); udpClient.Close(); // } //else if( ( m_PacketTransferOptions & WOLPacketTransferMode.modeTCP ) == WOLPacketTransferMode.modeTCP ) // use tcp, not tested yet // { // No other protocol implemented yet // } } catch (ArgumentNullException e) { MOE.Logger.DoLog( e.ToString(), Logger.LogLevel.lvlError ); } catch( SocketException e ) { MOE.Logger.DoLog( e.ToString(), Logger.LogLevel.lvlError ); } }
/// <summary> /// Executes this tool on the given Host. /// </summary> /// <param name="h">the host to call this tool for</param> /// <returns></returns> public bool Execute(WOL2Host h) { bool bRet = false; string param = GetCmdLine(); if (h != null) { param = h.ExpandVariables(param); } // Expand environment variables param = Environment.ExpandEnvironmentVariables(param); string cmd = Environment.ExpandEnvironmentVariables(m_sCmd); try { System.Diagnostics.Process.Start(cmd, param); } catch (Exception ex ) { MessageBox.Show(ex.Message +"\n\n" + cmd + "\n" + param, "WOL2", MessageBoxButtons.OK, MessageBoxIcon.Error); } return bRet; }
/// <summary> /// This function scans a single host /// </summary> /// <param name="h">A WOL2Host containing the information /// required to scan a host.</param> /// <returns>True, if the host was successfully scanned.</returns> private bool ScanHost(WOL2Host h) { bool bRet = false; IPAddress ip = IPAddress.Parse(h.GetIpAddress()); byte[] buffer = new byte[32]; Ping myPing = new Ping(); PingOptions pingOptions = new PingOptions(); PingReply reply = myPing.Send(ip, m_iPingTimeout, buffer, pingOptions); // send the ping if (reply.Status == IPStatus.Success) { // Found a host // WOL2Host h = new WOL2Host(); try { h.SetIpAddress(ip.ToString()); h.SetMacAddress(WOL2DNSHelper.GetMACAddress(h.GetIpAddress())); h.SetName(Dns.GetHostEntry(h.GetIpAddress()).HostName); // ipv6 lookup string lookup = h.GetName(); string ipv6 = WOL2DNSHelper.ResolveToIPv6Local(lookup); if (ipv6 == null) { lookup = h.GetIpAddress(); ipv6 = WOL2DNSHelper.ResolveToIPv6Local(lookup); } if (ipv6 != null) { h.SetIpV6Address(ipv6); } // check if the hostname was found bool bAdd = true; if (m_bAddIfHostnameResolved) { bAdd = (h.GetIpAddress() != h.GetName()); } if (m_bAddIfMacResolved) { bAdd = (h.GetMacAddress().Length != 0); } if (bAdd) { Monitor.Enter(Hosts); Hosts.Add(h); Monitor.Exit(Hosts); } MOE.Logger.DoLog("ScanHost(): Found host: " + h + ". " + (bAdd ? "Adding it." : "Not adding it."), MOE.Logger.LogLevel.lvlInfo); bRet = bAdd; } catch (System.Net.Sockets.SocketException se) { MOE.Logger.DoLog(se.ToString(), MOE.Logger.LogLevel.lvlWarning); } catch (Exception ex) { MOE.Logger.DoLog(ex.ToString(), MOE.Logger.LogLevel.lvlWarning); } } MOE.Logger.DoLog("ScanHost(): finished job " + h.GetIpAddress(), MOE.Logger.LogLevel.lvlDebug); return(bRet); }
public void AssignHostToListItem( WOL2Host h, ListViewItem i ) { // Remove old values in case of an update i.SubItems.Clear(); // Update / Add the item i.Text = h.GetName(); switch (h.GetState()) { default: case WOL2HostState.wolHostOffline: i.ImageIndex = 0; break; case WOL2HostState.wolHostOnline: i.ImageIndex = 1; break; case WOL2HostState.wolHostStarting: i.ImageIndex = 2; break; } // Add the sub items i.UseItemStyleForSubItems = false; i.SubItems.Add( h.GetIpAddress() ); i.SubItems.Add( h.GetMacAddress() ); i.SubItems.Add( h.GetDescription() ); System.Windows.Forms.ListViewItem.ListViewSubItem itm = i.SubItems.Add( h.StateAsString() ); if( m_bColorizeListView ) { if( h.GetState() == WOL2HostState.wolHostOnline ) itm.BackColor = Color.Green; else itm.BackColor = Color.Red; } string sManufacturer = ""; if( h.GetMacAddress() != null && h.GetMacAddress().Length > 4 ) sManufacturer = m_macResolver.GetManufacturerFromMac(h.GetMacAddress()); i.SubItems.Add(sManufacturer ); // Add the IP v 6 address i.SubItems.Add(h.GetIpV6Address()); // Wire the two objects together i.Tag = h; h.SetListViewItem( i ); }
/// <summary> /// Scans an IPv4 range /// </summary> /// <param name="from">Starting address</param> /// <param name="to">end address</param> /// <param name="Subnet">Subnet Mask for the network</param> public void ScanIPv4Range(IPAddress from, IPAddress to, IPAddress Subnet ) { MOE.Logger.DoLog( "ScanIPv4Range: Scanning range from " + from + " to " + to, MOE.Logger.LogLevel.lvlInfo ); // Initialize the scan m_lFinishedScans = 0; // Calculate the number of hosts to scan /* IPAddress r = new IPAddress(to.Address - from.Address ); string [] s = r.ToString().Split('.'); if (s.Length == 4) { m_lMaxScans = Int16.Parse(s[3]); m_lMaxScans *= 1 + Int16.Parse(s[2]); m_lMaxScans *= 1 + Int16.Parse(s[1]); m_lMaxScans *= 1 + Int16.Parse(s[0]); } */ // scan while the end of the range is not reached while (true) { from.Address += 0x01000000; // Advance to next IP // Contruct a temporary host element WOL2Host h = new WOL2Host(); h.SetIpAddress( from.ToString() ); h.SetSubnetMask( Subnet.ToString() ); // Add the job MOE.Logger.DoLog("ScanIPv4Range(): Added scan job: " + h.GetIpAddress(), MOE.Logger.LogLevel.lvlDebug); Monitor.Enter(m_Jobs); m_Jobs.Add(h); m_lMaxScans++; Monitor.Exit(m_Jobs); // Stop if the end IP is reached... if (from.ToString() == to.ToString()) break; // Increment the second octett if the first is full if ((from.Address & 0x00000000ff000000) == 0x00000000ff000000) { from.Address += 0x0000000000010000; } } // Start the async job processor ProcessJobs(); }
/// <summary> /// Updates the given host in the list view (if visible) /// </summary> private void RefreshHost(WOL2Host h) { if (this.InvokeRequired) { try { // We are, so marshall this call this.Invoke(new UpdateHost(RefreshHost), h); } catch { // Do nothing. Its most likely that the app is closing. } } else { // Find the list item foreach (ListViewItem itm in listView.Items) { if (itm.Tag == h) { AssignHostToListItem(h, itm); return; } } } }
/** * Inserts the host to the current list */ private void _AddHost(WOL2Host h) { Monitor.Enter(m_LockHosts); m_Hosts.Add(h); RefreshHostList(); Monitor.Exit(m_LockHosts); ChangedHostsFile(); }
/// <summary> /// Wakes a single host. /// </summary> /// <param name="idx">Index of the host to wake in the list view.</param> public bool WakeHost( WOL2Host h, bool bNoConfirm ) { if (!bNoConfirm) { string sAction = "Wake host " + h.GetName(); if (ConfirmAction(sAction) == false) return false; } bool bRet = false; if( h != null ) { SendWOLPacket( h ); bRet = true; lblStatus.Text = String.Format( MOE.Utility.GetStringFromRes("strSendWolPackageToHost"),h.GetName()); } return bRet; }
private void fromCSVToolStripMenuItem_Click(object sender, EventArgs e) { openFileDialog1.Filter = "CSV|*.csv"; if (openFileDialog1.ShowDialog(this) == DialogResult.OK) { FileStream fs = null; try { fs = File.OpenRead(openFileDialog1.FileName); } catch (Exception ex) { MessageBox.Show(this, ex.Message, "WOL2", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } StreamReader sr = new StreamReader(fs); int idx = 0; int cnt = 0; while (!sr.EndOfStream) { string line = sr.ReadLine(); // Idle while the import is running (each 10 items) if (cnt % 10 == 0) { statusStrip1.Text = "Import: " + cnt; statusStrip1.Update(); Application.DoEvents(); } if (idx++ > 0) // skip the header { string[] items = line.Split(';'); if( items.Length != 9 ) { string msg = MOE.Utility.GetStringFromRes("strCSVLineNotValid"); if (MessageBox.Show(this, msg + "\nLine: " + (idx) + "\n'" + line + "'", "WOL2", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == System.Windows.Forms.DialogResult.No) break; else continue; } try { WOL2Host h = new WOL2Host(items[0], //name items[1], //comment items[2], //ip items[3], //mac items[4], //sn mask WOL2HostState.wolHostOffline, WOL2ConnectionType.wolConnectionLan, items[5], //groups "", items[6], //secure on pw items[7] == "1", // dhcp flag false, false, items[8], // IPv6 Address m_PacketTransferOptions); if (h.IsValid()) { _AddHost(h); cnt++; } } catch (Exception ex ) { string msg = MOE.Utility.GetStringFromRes("strCSVLineNotValid"); if (MessageBox.Show(this, msg + "\nLine: " + (idx) + "\n'" + ex.Message, "WOL2", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == System.Windows.Forms.DialogResult.No) break; } } } // Close the file sr.Close(); fs.Close(); MessageBox.Show(this, "Added " + cnt + " hosts.", "WOL2",MessageBoxButtons.OK, MessageBoxIcon.Information); } }
public void ShutdownHost( WOL2Host h, bool bNoConfirm ) { if (!bNoConfirm) { string sAction = "Shutdown host " + h.GetName(); if (ConfirmAction(sAction) == false) return; } if( MOE.Utility.IsRunningOnMono() ) { String sMsg = "Hi fellower Mac or gnu/linux user!\n\nActually shutting down remote hosts is not implemented yet.\nIf you know a commandline call to do that, do not hesitate to contat me.\nI'll be happy to include it ;-)"; MessageBox.Show( sMsg, "Not implemented yet :-(", MessageBoxButtons.OK, MessageBoxIcon.Error ); } else // We're running on .NET this is most likely to happen on a windows machine { string sDelimiter = "-"; System.OperatingSystem osInfo = System.Environment.OSVersion; if (osInfo.Version.Major >= 6) sDelimiter = "/"; string sArgs = sDelimiter + "s"; if( m_iShutdownTimeout > 0 ) sArgs += " " + sDelimiter + "t " + m_iShutdownTimeout.ToString(); if( m_sShutdownComment != null && m_sShutdownComment.Length > 0 ) sArgs += " " + sDelimiter + "c \"" + m_sShutdownComment + "\""; if( h.IsDynamicHost() ) sArgs += " " + sDelimiter + "m \\\\" + h.GetName(); else sArgs += " " + sDelimiter + "m " + h.GetIpAddress(); if( m_bForceShutdown ) sArgs += " " + sDelimiter + "f"; try { string sDomain = h.GetName(); if (m_sShutdownDomain != null && m_sShutdownDomain.Length > 0 ) sDomain = m_sShutdownDomain; if( m_sShutdownUser != null && m_sShutdownUser.Length > 0 && m_sShutdownPaswd != null && m_sShutdownPaswd.Length > 0 ) System.Diagnostics.Process.Start( "shutdown.exe" , sArgs, m_sShutdownUser, m_sShutdownPaswd, sDomain ); else System.Diagnostics.Process.Start("shutdown.exe" , sArgs ); } catch( Exception e ) { MOE.Logger.DoLog( e.ToString(), Logger.LogLevel.lvlError ); } } }
/// <summary> /// Checks whether this host has the same MAC Address as 'h'. /// </summary> /// <param name="h">Other host.</param> /// <returns></returns> public bool Equals( WOL2Host h ) { // If the host has a mac address compare those if( h.GetMacAddress() != null && h.GetMacAddress().Length >0 && GetMacAddress() != null && GetMacAddress().Length>0 && h.GetMacAddress().ToLower() == GetMacAddress().ToLower() ) return true; // if it has an ip v6 address and this one is equal else if( h.GetIpV6Address() != null && h.GetIpV6Address().Length>0 && GetIpV6Address() != null && GetIpV6Address().Length>0 && h.GetIpV6Address() == GetIpV6Address() ) return true; // if it uses DHCP and the hostname is equal else if (IsDynamicHost() && GetName() != null && GetName().Length > 0 && GetName() == h.GetName()) return true; // if it does not use DHCP and the IPv4 Address is equal else if (!IsDynamicHost() && GetIpAddress() != null && GetIpAddress().Length > 0 && GetIpAddress() == h.GetIpAddress()) return true; else return false; }
/// <summary> /// Opens a host file /// </summary> /// <param name="sFile">The file to open.</param> public bool OpenHostList( string sFile ) { bool bRet = false; if( sFile == null ) { // Ask for a xml file OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.FileName = m_sHostFileName; openFileDialog1.Filter = "XML File (*.xml)|*.xml|All Files (*.*)|*.*" ; openFileDialog1.FilterIndex = 1; openFileDialog1.RestoreDirectory = true ; // Read and filter the raw data if(openFileDialog1.ShowDialog() == DialogResult.OK) { sFile = openFileDialog1.FileName; } } if( sFile != null ) { int iCount = 0; // Create the XML document XmlDocument xml = new XmlDocument(); try { // Try to load the file xml.Load( sFile ); // Clean the old host list Monitor.Enter( m_LockHosts ); m_Hosts.Clear(); m_Groups.Clear(); Monitor.Exit( m_LockHosts ); m_CurrentGroup = null; // Try to get the host nodes XmlNodeList xmlHosts = xml.SelectNodes( "/WakeOnLan/Hosts/Host" ); // Insert all hosts Monitor.Enter( m_LockHosts ); foreach( XmlNode hostNode in xmlHosts ) { // Insert the host WOL2Host h = new WOL2Host( ); XmlNode n = hostNode.FirstChild; if( h.DeserializeXML( n ) ) { m_Hosts.Add( h ); h.SetState( WOL2HostState.wolHostOffline ); iCount++; } } Monitor.Exit( m_LockHosts ); // Try to get the group nodes XmlNodeList xmlGroups = xml.SelectNodes( "/WakeOnLan/Groups/Group" ); // Insert all groups Monitor.Enter( m_Groups ); foreach( XmlNode groupNode in xmlGroups ) { XmlNode n = groupNode.FirstChild; WOL2Group g = new WOL2Group(); g.DeserializeXML( n ); if( g.IsValid() ) { m_Groups.Add( g.GetName(), g ); } } Monitor.Exit( m_Groups ); RefreshGroupList(); // Get the HostFile Note XmlNode tmp = xml.SelectSingleNode("/WakeOnLan/Comment"); if (tmp != null) { m_sHostFileNote = tmp.InnerText; tbtnNote.ToolTipText = m_sHostFileNote; } // File loaded... m_sHostFileName = sFile; bRet = true; RefreshHostList(); lblStatus.Text = String.Format( MOE.Utility.GetStringFromRes("strFileOpened"), iCount ); MOE.Logger.DoLog( "Opened host file " + sFile + " with " + iCount + " hosts.", Logger.LogLevel.lvlInfo ); // Add the file to the MRU list if not present yet if (m_MruList.IndexOf(sFile) == -1) { m_MruList.Insert(0, sFile); BuildMruList(); } } catch { // Some Error } } // new file m_bChangedFile = false; return bRet; }
/// <summary> /// Inserts a new host /// </summary> public void InsertNewHost(WOL2Host h) { if( h == null ) h = new WOL2Host(); DlgEditHost dlg = new DlgEditHost( h ); DialogResult dr = dlg.ShowDialog( this ); if (dr == System.Windows.Forms.DialogResult.OK) { if (h.IsValid()) { _AddHost(h); } else { // Re open the edit window InsertNewHost(h); } } }
/// <summary> /// This function scans a single host /// </summary> /// <param name="h">A WOL2Host containing the information /// required to scan a host.</param> /// <returns>True, if the host was successfully scanned.</returns> private bool ScanHost( WOL2Host h ) { bool bRet = false; IPAddress ip = IPAddress.Parse( h.GetIpAddress() ); byte[] buffer = new byte[32]; Ping myPing = new Ping(); PingOptions pingOptions = new PingOptions(); PingReply reply = myPing.Send(ip, m_iPingTimeout, buffer, pingOptions); // send the ping if( reply.Status == IPStatus.Success ) { // Found a host // WOL2Host h = new WOL2Host(); try { h.SetIpAddress( ip.ToString() ); h.SetMacAddress(WOL2DNSHelper.GetMACAddress(h.GetIpAddress())); h.SetName( Dns.GetHostEntry( h.GetIpAddress() ).HostName ); // ipv6 lookup string lookup = h.GetName(); string ipv6 = WOL2DNSHelper.ResolveToIPv6Local(lookup); if (ipv6 == null) { lookup = h.GetIpAddress(); ipv6 = WOL2DNSHelper.ResolveToIPv6Local(lookup); } if( ipv6 != null ) h.SetIpV6Address(ipv6); // check if the hostname was found bool bAdd = true; if( m_bAddIfHostnameResolved ) bAdd = ( h.GetIpAddress() != h.GetName() ); if( m_bAddIfMacResolved ) bAdd = ( h.GetMacAddress().Length != 0 ); if( bAdd ) { Monitor.Enter( Hosts ); Hosts.Add( h ); Monitor.Exit( Hosts ); } MOE.Logger.DoLog("ScanHost(): Found host: " + h + ". " + (bAdd ? "Adding it." : "Not adding it."), MOE.Logger.LogLevel.lvlInfo); bRet = bAdd; } catch(System.Net.Sockets.SocketException se ) { MOE.Logger.DoLog( se.ToString(), MOE.Logger.LogLevel.lvlWarning ); } catch( Exception ex ) { MOE.Logger.DoLog( ex.ToString(), MOE.Logger.LogLevel.lvlWarning ); } } MOE.Logger.DoLog("ScanHost(): finished job " + h.GetIpAddress(), MOE.Logger.LogLevel.lvlDebug ); return bRet; }