通过IP地址识别连接的网络打印机

时间:2017-07-21 08:16:46

标签: c# printing dns

我想列出连接到我的网络的所有打印机(包括未安装的)

通过ping到网关上的所有地址,我可以设法将连接设备的所有IP地址都连接到我的PC。然后我通过

获得了主机名
IPHostEntry entry = Dns.GetHostEntry(ipAddress);
return entry.HostName;

我注意到打印机没有主机名 现在我需要弄清楚哪个IP属于我的IP列表或mac地址的打印机。

我该怎么做。

当我们安装网络打印机时,Windows会列出打印机的名称。我们可以使用IP或MAC获取此类名称吗?

1 个答案:

答案 0 :(得分:1)

使用

包含System.Management
using System.Management;

foreach (string printername in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
{
    string query = string.Format("SELECT * from Win32_Printer WHERE Name LIKE '%{0}'", printername);

    using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
    using (ManagementObjectCollection coll = searcher.Get())
    {
        try
        {
            foreach (ManagementObject printer in coll)
            {
                foreach (PropertyData property in printer.Properties)
                {
                    Console.WriteLine(string.Format("{0}: {1}", property.Name, property.Value));
                }
            }
        }
        catch (ManagementException ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

您将获得每台打印机的所有信息,包括名称和IP

如果您想从名称中获取打印机IP,请使用

If(printer.Properties.Caption.Contains("Printer name")
{
    return printer.Properties.PortName;
}

否则,要从名称中获取ip,请反转进程并搜索ip并返回名称。

对于网络中的打印机,请尝试以下操作:

using System.Management;

private void Form1_Load(object sender, EventArgs e)
{
    System.Management.ObjectQuery oquery = new System.Management.ObjectQuery("SELECT * FROM Win32_Printer");
    System.Management.ManagementObjectSearcher mosearcher = new
    System.Management.ManagementObjectSearcher(oquery);
    System.Management.ManagementObjectCollection moc =
    mosearcher.Get();

    foreach (ManagementObject mo in moc)
    {
        System.Management.PropertyDataCollection pdc = mo.Properties;
        foreach (System.Management.PropertyData pd in pdc)
        {
            if ((bool)mo["Network"])
            {
                MessageBox.Show(String.Format("{1}", mo[pd.Name]));
            }
        }
    }
}




// To list printers installed on computer online/offline
Code Snippet
foreach (string printer in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
{
    MessageBox.Show(printer);
}