怎样由域名得到IP? ( 积分: 100 )

  • 主题发起人 主题发起人 www
  • 开始时间 开始时间
W

www

Unregistered / Unconfirmed
GUEST, unregistred user!
function GetIPByHost(const HostName: string): string;
var Host: pHostent;
ConsultResult:String;
Err:Integer;
begin
Result := '';
try
Host := GetHostByName(PChar(HostName));
except
Err:=WSAGetLastError();
exit;
end;
if host = nil then begin
exit;
end;
ConsultResult:=Copy(Host.h_addr^,0,4);
Result := Format('%d.%d.%d.%d',[ord(ConsultResult[1]), ord(ConsultResult[2]),
ord(ConsultResult[3]), ord(ConsultResult[4])]);

end;

上面这个函数在解析局域网机器时不对,比如GetIPByHost('server'),得到的是192.168.0.0,实际上应该是192.168.0.2
 
function GetIPByHost(const HostName: string): string;
var Host: pHostent;
ConsultResult:String;
Err:Integer;
begin
Result := '';
try
Host := GetHostByName(PChar(HostName));
except
Err:=WSAGetLastError();
exit;
end;
if host = nil then begin
exit;
end;
ConsultResult:=Copy(Host.h_addr^,0,4);
Result := Format('%d.%d.%d.%d',[ord(ConsultResult[1]), ord(ConsultResult[2]),
ord(ConsultResult[3]), ord(ConsultResult[4])]);

end;

上面这个函数在解析局域网机器时不对,比如GetIPByHost('server'),得到的是192.168.0.0,实际上应该是192.168.0.2
 
试试这个:
function GetIPFromName(Name: string): string;
var
WSAData: TWSAData;
HostEnt: PHostEnt;
begin
WSAStartup(2, WSAData);
HostEnt := gethostbyname(PChar(Name));
with HostEnt^ do
Result := Format('%d.%d.%d.%d', [Byte(h_addr^[0]),
Byte(h_addr^[1]), Byte(h_addr^[2]), Byte(h_addr^[3])]);
WSACleanup;
end;
 
通过机器名得到IP地址


function procedure TForm1.nametoip(name:string):string;
var
WSAData: TWSAData;
HostEnt: PHostEnt;
begin
result:='';
WSAStartup(2, WSAData);
HostEnt := gethostbyname(PChar(name));
if HostEnt <> nil then
begin
with HostEnt^ do
result:= Format('%d.%d.%d.%d', [Byte(h_addr^[0]), Byte(h_addr^[1]), Byte(h_addr^[2]), Byte(h_addr^[3])]);
end;
WSACleanup;
end;
 
通过IP地址得到机器名


function iptoname(ip:string):string;
var
WSAData:TWSAData;
p:PHostEnt;
InetAddr:dword;
begin
WSAStartup(2, WSAData);
InetAddr:= inet_addr(PChar(IP));
try
p:=GetHostByAddr(@InetAddr, Length(IP), PF_Inet);
result:=p^.h_name;
except
result:='';
end;
end;
 
多人接受答案了。
 
后退
顶部