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 nam开发者_运维问答e, using win32 API?
I tried looking into the PRINTER_INFO_* structs
, but it seems it is not present there.
you can get the port name by PRINTER_INFO_2,and the get the ip from the registry,the path is: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Print\Monitors\Standard TCP/IP Port\Ports the ip store in "HostName"
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 (e.g., 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.
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 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;
Simply Use Advanced Printer apis, dynamic call
精彩评论