Определить шлюз по умолчанию устройств в локальной сети - C#

Узнай цену своей работы

Формулировка задачи:

Всем доброго времени суток. Имеем большую локальную сеть с несколькими подсетями, в каждой из которых порядка 10-20 компов. вся сеть в домене. Знает ли кто-нибудь как узнать шлюз по умолчанию у каждого компьютера в сети?

Решение задачи: «Определить шлюз по умолчанию устройств в локальной сети»

textual
Листинг программы
  1. using System;
  2. using System.Drawing;
  3. using System.Collections;
  4. using System.ComponentModel;
  5. using System.Windows.Forms;
  6. using System.Data;
  7. using System.Management;
  8.  
  9. namespace WMISample
  10. {
  11.     public class MyQuerySample : System.Windows.Forms.Form
  12.     {
  13.         private System.Windows.Forms.Label userNameLabel;
  14.         private System.Windows.Forms.TextBox userNameBox;
  15.         private System.Windows.Forms.TextBox passwordBox;
  16.         private System.Windows.Forms.Label passwordLabel;
  17.         private System.Windows.Forms.Button OKButton;
  18.         private System.Windows.Forms.Button cancelButton;
  19.        
  20.         private System.ComponentModel.Container components = null;
  21.  
  22.         public MyQuerySample()
  23.         {
  24.             InitializeComponent();
  25.         }
  26.  
  27.         protected override void Dispose( bool disposing )
  28.         {
  29.             if( disposing )
  30.             {
  31.                 if (components != null)
  32.                 {
  33.                     components.Dispose();
  34.                 }
  35.             }
  36.             base.Dispose( disposing );
  37.         }
  38.  
  39.         private void InitializeComponent()
  40.         {
  41.             this.userNameLabel = new System.Windows.Forms.Label();
  42.             this.userNameBox = new System.Windows.Forms.TextBox();
  43.             this.passwordBox = new System.Windows.Forms.TextBox();
  44.             this.passwordLabel = new System.Windows.Forms.Label();
  45.             this.OKButton = new System.Windows.Forms.Button();
  46.             this.cancelButton = new System.Windows.Forms.Button();
  47.             this.SuspendLayout();
  48.             //
  49.             // userNameLabel
  50.             //
  51.             this.userNameLabel.Location = new System.Drawing.Point(16, 8);
  52.             this.userNameLabel.Name = "userNameLabel";
  53.             this.userNameLabel.Size = new System.Drawing.Size(160, 32);
  54.             this.userNameLabel.TabIndex = 0;
  55.             this.userNameLabel.Text = "Enter the user name for the remote computer:";
  56.             //
  57.             // userNameBox
  58.             //
  59.             this.userNameBox.Location = new System.Drawing.Point(160, 16);
  60.             this.userNameBox.Name = "userNameBox";
  61.             this.userNameBox.Size = new System.Drawing.Size(192, 20);
  62.             this.userNameBox.TabIndex = 1;
  63.             this.userNameBox.Text = "";
  64.             //
  65.             // passwordBox
  66.             //
  67.             this.passwordBox.Location = new System.Drawing.Point(160, 48);
  68.             this.passwordBox.Name = "passwordBox";
  69.             this.passwordBox.PasswordChar = '*';
  70.             this.passwordBox.Size = new System.Drawing.Size(192, 20);
  71.             this.passwordBox.TabIndex = 3;
  72.             this.passwordBox.Text = "";
  73.             //
  74.             // passwordLabel
  75.             //
  76.             this.passwordLabel.Location = new System.Drawing.Point(16, 48);
  77.             this.passwordLabel.Name = "passwordLabel";
  78.             this.passwordLabel.Size = new System.Drawing.Size(160, 32);
  79.             this.passwordLabel.TabIndex = 2;
  80.             this.passwordLabel.Text = "Enter the password for the remote computer:";
  81.             //
  82.             // OKButton
  83.             //
  84.             this.OKButton.Location = new System.Drawing.Point(40, 88);
  85.             this.OKButton.Name = "OKButton";
  86.             this.OKButton.Size = new System.Drawing.Size(128, 23);
  87.             this.OKButton.TabIndex = 4;
  88.             this.OKButton.Text = "OK";
  89.             this.OKButton.Click += new System.EventHandler(this.OKButton_Click);
  90.             //
  91.             // cancelButton
  92.             //
  93.             this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
  94.             this.cancelButton.Location = new System.Drawing.Point(200, 88);
  95.             this.cancelButton.Name = "cancelButton";
  96.             this.cancelButton.Size = new System.Drawing.Size(128, 23);
  97.             this.cancelButton.TabIndex = 5;
  98.             this.cancelButton.Text = "Cancel";
  99.             this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click);
  100.             //
  101.             // MyQuerySample
  102.             //
  103.             this.AcceptButton = this.OKButton;
  104.             this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
  105.             this.CancelButton = this.cancelButton;
  106.             this.ClientSize = new System.Drawing.Size(368, 130);
  107.             this.ControlBox = false;
  108.             this.Controls.Add(this.cancelButton);
  109.             this.Controls.Add(this.OKButton);
  110.             this.Controls.Add(this.passwordBox);
  111.             this.Controls.Add(this.passwordLabel);
  112.             this.Controls.Add(this.userNameBox);
  113.             this.Controls.Add(this.userNameLabel);
  114.             this.Name = "MyQuerySample";
  115.             this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
  116.             this.Text = "Remote Connection";
  117.             this.ResumeLayout(false);
  118.  
  119.         }
  120.  
  121.         [STAThread]
  122.         static void Main()
  123.         {
  124.             Application.Run(new MyQuerySample());
  125.         }
  126.  
  127.         private void OKButton_Click(object sender, System.EventArgs e)
  128.         {
  129.             try
  130.             {
  131.                 ConnectionOptions connection = new ConnectionOptions();
  132.                 connection.Username = userNameBox.Text;
  133.                 connection.Password = passwordBox.Text;
  134.                 connection.Authority = "ntlmdomain:MY_DOMAIN";
  135.  
  136.                 ManagementScope scope = new ManagementScope(
  137.                     "\\\\FullComputerName\\root\\CIMV2", connection);
  138.                 scope.Connect();
  139.  
  140.                 ObjectQuery query= new ObjectQuery(
  141.                     "SELECT * FROM Win32_NetworkAdapterConfiguration");
  142.  
  143.                 ManagementObjectSearcher searcher =
  144.                     new ManagementObjectSearcher(scope, query);
  145.  
  146.                 foreach (ManagementObject queryObj in searcher.Get())
  147.                 {
  148.                     Console.WriteLine("-----------------------------------");
  149.                     Console.WriteLine("Win32_NetworkAdapterConfiguration instance");
  150.                     Console.WriteLine("-----------------------------------");
  151.  
  152.                     if(queryObj["DefaultIPGateway"] == null)
  153.                         Console.WriteLine("DefaultIPGateway: {0}", queryObj["DefaultIPGateway"]);
  154.                     else
  155.                     {
  156.                         String[] arrDefaultIPGateway = (String[])(queryObj["DefaultIPGateway"]);
  157.                         foreach (String arrValue in arrDefaultIPGateway)
  158.                         {
  159.                             Console.WriteLine("DefaultIPGateway: {0}", arrValue);
  160.                         }
  161.                     }
  162.                 }
  163.                 Close();
  164.             }
  165.             catch(ManagementException err)
  166.             {
  167.                 MessageBox.Show("An error occurred while querying for WMI data: " + err.Message);
  168.             }
  169.             catch(System.UnauthorizedAccessException unauthorizedErr)
  170.             {
  171.                 MessageBox.Show("Connection error (user name or password might be incorrect): " + unauthorizedErr.Message);
  172.             }
  173.         }
  174.  
  175.         private void cancelButton_Click(object sender, System.EventArgs e)
  176.         {
  177.             Close();
  178.         }
  179.     }
  180. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

9   голосов , оценка 4.333 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы