怎样获取指定域名的IP(30分)

  • 主题发起人 主题发起人 aiddy
  • 开始时间 开始时间
A

aiddy

Unregistered / Unconfirmed
GUEST, unregistred user!
请问怎样才能获取一个指定域名的IP,不要告诉我用PING来看,我要取IP到变量中
 
uses
Winsock;

function GetHostAddress(const hostname:string): string;
var
HostEnt:PHostEnt;
InAddr:TInAddr;
begin
Result:='';
HostEnt:=gethostbyname(PChar(hostname));
if HostEnt = nil then Exit;
InAddr.S_un_b.s_b1:=HostEnt^.h_addr^[0];
InAddr.S_un_b.s_b2:=HostEnt^.h_addr^[1];
InAddr.S_un_b.s_b3:=HostEnt^.h_addr^[2];
InAddr.S_un_b.s_b4:=HostEnt^.h_addr^[3];
Result:=inet_ntoa(InAddr);
end;

var
wsa:TWSAData;
initialization
WSAStartup($0101,wsa);
finalization
WSACleanup;
end.
 
我试了这段程序,比如用"www.163.com",但取不到它的IP,是怎么回事呢
 
版主,这个问题挂了几天了,怎么没人理呀,是太简单了,还是没人懂呀
 
太惭愧了!smokingroom回答的非常正确,我前天照抄着做时,没有写初始化语句,所以没成功.再次感谢smokingroom.
 
uses WinSock;

function GetIPAddress(const HostName: string): string;
var
R: Integer;
WSAData: TWSAData;
HostEnt: PHostEnt;
Host: string;
SockAddr: TSockAddrIn;
begin
Result := '';
R := WSAStartup(MakeWord(1, 1), WSAData);
if R = 0 then
try
Host := HostName;
if Host = '' then //若为空值, 则取本机的hostname,
begin
SetLength(Host, MAX_PATH);
GetHostName(PChar(Host), MAX_PATH);
end;
HostEnt := GetHostByName(PChar(Host));
if HostEnt <> nil then
begin
SockAddr.sin_addr.S_addr := Longint(PLongint(HostEnt^.h_addr_list^)^);
Result := inet_ntoa(SockAddr.sin_addr);
end;
finally
WSACleanup;
end;
end;
 
后退
顶部