简体   繁体   中英

How can I get the IP address of a network printer given the port name using the Win32 API?

How can I get the IP address of a network printer given the port name, using win32 API?

I tried looking into the PRINTER_INFO_* structs , but it seems it is not present there.

您可以通过PRINTER_INFO_2获取端口名称,并从注册表获取IP,路径为:HKEY_LOCAL_MACHINE \\ SYSTEM \\ CurrentControlSet \\ Control \\ Print \\ Monitors \\ Standard TCP / IP Port \\ IP地址存储在“ HostName”中的端口

Like any other IP network device, the printer will have an IP address (denoting it's ethernet card), and will run a service on a certain port (identifying the program responding to printer messages). This is merely networking stuff and has nothing yet to do with printer specific stuff.

So given it's port only, there's no way to find it's IP address. Probably the services on all the other printers listen to the same port.

Assuming you mean you have the printer's name, you need to query the name service for your domain. This service maps network addresses to 'symbolic' names.

Using the winsock2 api, I believe it's gethostbyname you need. This will retrieve the host info of your printer by it's name.

I don't think there's a standard way to get the IP address. There are probably different incompatible implementations of network port monitors. For my network printer, the IP address is part of the port name (eg, IP_192_168.1.104 ). If it's of that form, then you might be able to parse it out, but I don't think this is universal.

Using EnumPorts you can determine if it's a network printer, but I still don't see a way to get the IP address.

只需使用高级打印机API,即可动态调用

I came looking for an answer but didn't really accept there was no way and found that there actually is. This answer is in Delphi, but it's pretty straightforward:

function PortIPAddress(Port: string): string;
var
  buf:          PWideChar;
  pd:           PRINTER_DEFAULTS;
  c,
  d,
  bs,
  hXcv:         cardinal;
begin
  Result := 'unknown';

  ZeroMemory(@pd, SizeOf(PRINTER_DEFAULTS));
  pd.DesiredAccess := SERVER_ACCESS_ADMINISTER;

  if OpenPrinter(PAnsiChar(Format(',XcvPort %s', [Port])), hXcv, @pd) then
  begin
    XcvData(hXcv, 'IPAddress', nil, 0, nil, 0, @bs, @c);

    GetMem(buf, bs);
    try
      if XcvData(hXcv, 'IPAddress', nil, 0, buf, bs, @d, @c) then
        Result := buf;
    finally
      FreeMem(buf, bs);
    end;
  end;

  ClosePrinter(hXcv);
end;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM