〓〓〓〓 如何获取ip地址 〓〓〓〓(实在是没分了!!!)(10分)

  • 主题发起人 主题发起人 imlujian
  • 开始时间 开始时间
I

imlujian

Unregistered / Unconfirmed
GUEST, unregistred user!
拨号上网和通过局域网上网这两种上网类型的机器,delphi中如何能获得在internet上使用的ip!
 
function LocalIP : string;
type
TaPInAddr = array [0..10] of PInAddr;
PaPInAddr = ^TaPInAddr;
var
phe : PHostEnt;
pptr : PaPInAddr;
Buffer : array [0..63] of char;
I : Integer;
GInitData : TWSADATA;
begin
WSAStartup($101, GInitData);
Result := '';
GetHostName(Buffer, SizeOf(Buffer));
phe :=GetHostByName(buffer);
if phe = nil then Exit;
pptr := PaPInAddr(Phe^.h_addr_list);
I := 0;
while pptr^ <> nil do begin
if i=0
then result:=StrPas(inet_ntoa(pptr^^))
else result:=result+','+StrPas(inet_ntoa(pptr^^));
Inc(I);
end;
WSACleanup;
end;
 
To YB_unique:
你的代码编译时出错。
1 需要加入IdWinsock单元。
2 WSAStartup($101, GInitData)处报错“Access violation at address 00000000”
 
function Tform1.LookupIP: String;
type PPInAddr= ^PInAddr;
var
wsaData: TWSAData;
HostInfo: PHostEnt;
HostName: Array[0..255] of Char;
Addr: PPInAddr;
begin
Result:='';
if WSAStartup($0101, wsaData)<>0 then exit;
try
if gethostname(HostName, SizeOf(HostName)) <> 0 then exit;
HostInfo:= gethostbyname(HostName);
if HostInfo=nil then Exit;
Addr:=Pointer(HostInfo^.h_addr_list);
if (Addr=nil) or (Addr^=nil) then exit;
Result:=StrPas(inet_ntoa(Addr^^));
inc(Addr);
while Addr^<>nil do begin
Result:=Result+^M^J+StrPas(inet_ntoa(Addr^^));
inc(Addr);
end;
finally
WSACleanup;
end;
end;

使用时 label1.Caption := LookupIP; 就行了.
 
听说有控件!
 
我这个肯定能用:我用过
function LocalIP : string;
type
TaPInAddr = array [0..10] of PInAddr;
PaPInAddr = ^TaPInAddr;
var
phe : PHostEnt;
pptr : PaPInAddr;
Buffer : array [0..63] of char;
I : Integer;
GInitData : TWSADATA;

begin
WSAStartup($101, GInitData);
Result := '';
GetHostName(Buffer, SizeOf(Buffer));
phe :=GetHostByName(buffer);
if phe = nil then Exit;
pptr := PaPInAddr(Phe^.h_addr_list);
I := 0;
while pptr^ <> nil do begin
result:=StrPas(inet_ntoa(pptr^^));
Inc(I);
end;
WSACleanup;
end;
 
//支持多网卡
use ...,winsock;
...
function getIPs: TStrings;
type
TaPInAddr = Array[0..10] of PInAddr;
PaPInAddr = ^TaPInAddr;
var
phe: PHostEnt;
pptr: PaPInAddr;
Buffer: Array[0..63] of Char;
I: Integer;
GInitData: TWSAData;
begin
WSAStartup($101, GInitData);
Result:=TStringList.Create;
Result.Clear;
GetHostName(Buffer, SizeOf(Buffer));
phe := GetHostByName(buffer);
if phe = nil then Exit;
pPtr := PaPInAddr(phe^.h_addr_list);
I := 0;
while pPtr^ <> nil do
begin
Result.Add(inet_ntoa(pptr^^));
Inc(I);
end;
WSACleanup;
end;

 
后退
顶部