var
sl: TStringList;
...
调用GetServerListFromLan(sl, nil, True);即可将局域网内的机器列表保存到sl中;
调用GetIPFromHost(hn: string); 即可返回机器名hn对应的IP地址。
procedure GetServerListFromLan(sl: TStrings; NetResContainer: PNetResource; bRoot: Boolean);
var
NetRes: Array[0..10] of TNetResource;
r,hEnum,EntryCount,NetResLen: DWORD;
strName: String;
begin
//在下面的递归程序中应该注意 WNetOpenEnum()与WNetCloseEnum()的次数是否相同。
//如果不同,肯定是在某一次循环中出差错了,可能会漏掉未释放的资源.
r := WNetOpenEnum(RESOURCE_GLOBALNET,
RESOURCETYPE_ANY,
0,
NetResContainer,
hEnum);
if r <> NO_ERROR then Exit;
while True do
begin
EntryCount := 1;
NetResLen := SizeOf(NetRes);
r := WNetEnumResource(hEnum, EntryCount, @NetRes, NetResLen);
case r of
NO_ERROR:
begin
if NetRes[0].dwDisplayType = RESOURCEDISPLAYTYPE_SERVER then
begin
strName := Trim(StrPas(NetRes[0].lpRemoteName));
if strName = '' then strName := Trim(StrPas(NetRes[0].lpProvider))
else Delete(strName, 1, 2);
sl.Add(strName);
end
else GetServerListFromLan(sl, @NetRes[0], False);
end;
ERROR_NO_MORE_ITEMS:
begin
WNetCloseEnum(hEnum);
Break;
end;
else
end;
end;
end;
//下面的函数需要包含WinSock单元
function GetIPFromHost(hn: string): string;
var
sData: TWSAData;
h: PHostEnt;
begin
Result := '0.0.0.0';
if WSAStartup($101, sData) = SOCKET_ERROR then Exit;
if hn <> '' then
begin
if hn[1] in ['0'..'9'] then
begin
if inet_addr(pchar(hn)) <> INADDR_NONE then
Result := hn;
end
else
begin
h := gethostbyname(pchar(hn));
if h <> nil then
with h^ do
Result := format('%d.%d.%d.%d', [ord(h_addr^[0]), ord(h_addr^[1]),
ord(h_addr^[2]), ord(h_addr^[3])]);
end;
end;
WSACleanup;
end;