提一个很菜的问题:获取本地IP地址(28分)

  • 主题发起人 主题发起人 maleice
  • 开始时间 开始时间
M

maleice

Unregistered / Unconfirmed
GUEST, unregistred user!
如何获取本机IP地址或者计算机名称,
用API或者其他?
谢谢关注我这个菜鸟的问题!
 
放一个 TCPClient 到 Form 上去
然后访问 HostAdd (具体是什么属性自己查一下吧)就可以了
 
(1)命令行中打入
ipconfig /all
(2)网络连接上看
(3)Indy组件:IdIPWatch1.LocalIP
 
内含得到本机IP地址
电脑名称
子网掩码
广播地址
=====================================

unit NetFunction;

interface

uses Windows, SysUtils, Winsock;
{
使用到WinSock2。
这是一个完整的Delphi单元,将它加入到你的工程中,你可以调用:
EnumInterfaces(var s string): Boolean;
来返回所有IP地址、网络掩码、广播地址和连接状态。

此函数列举出所有的TCP/IP连接,并返回一个由回车换行(CRLF)符分隔的字符串,包含以下信息:
IP, NetMask, BroadCast-Address, Up/Down status,
Broadcast support, Loopback
如果你将这个字符串赋给TMemo(它的Memo.Lines.Text属性),你可以看到更清晰的结果。
使用此函数,你需要Win98/ME/2K, 95 OSR 2 或者NT service pack #3,
因为程序会使用到WinSock 2(WS2_32.DLL)。}

function EnumInterfaces(var IPAddress,IPSubNetMask,BroadcastAddress,Online: string): Boolean;

{从Winsock 2.0导入函数WSAIOCtl -- 在Win98/ME/2K and 95 OSR2, NT srv pack #3下才有Winsock 2}
function WSAIoctl(s: TSocket; cmd: DWORD; lpInBuffer: PCHAR; dwInBufferLen: DWORD;
lpOutBuffer: PCHAR; dwOutBufferLen: DWORD;
lpdwOutBytesReturned: LPDWORD;
lpOverLapped: POINTER;
lpOverLappedRoutine: POINTER): Integer; stdcall; external 'WS2_32.DLL';

function OctToBin(i:Integer):String;
function BinToOct(k:String):Integer;
function GetComputerNameString:String;
function NetGetLocalIP:String;

{Constants taken from C header files}
const
SIO_GET_INTERFACE_LIST = $4004747F;
IFF_UP = $00000001;
IFF_BROADCAST = $00000002;
IFF_LOOPBACK = $00000004;
IFF_POINTTOPOINT = $00000008;
IFF_MULTICAST = $00000010;

type
sockaddr_gen = packed record
AddressIn: sockaddr_in;
filler: packed array[0..7] of char;
end;

type
INTERFACE_INFO = packed record
iiFlags: u_long; // Interface flags
iiAddress: sockaddr_gen; // Interface address
iiBroadcastAddress: sockaddr_gen; // Broadcast address
iiNetmask: sockaddr_gen; // Network mask
end;

implementation

{
1. 打开Winsock
2. 创建一个socket
3. 调用WSAIOCtl获取网络连接
4. 对每个连接,获取它的IP、掩码、广播地址、状态
5. 将信息填充到一个由CDLF分隔的字符串中
6. 结束}


function octtobin(i:integer):string;
var
j:integer;
s:string;
begin
j:=i;s:='';
while j>=2 do
begin
if (j mod 2)=1 then
begin
s:='1'+s;
j:=j div 2;
end
else
begin
s:='0'+s;
j:=j div 2;
end;
end;
s:=chr(ord('0')+j) + s;
if length(s)<8 then
for i:=1 to 8-length(s) do
s:='0'+s;
octtobin:=s;
end;

function BinToOct(k:string):integer;
var
i,j,t:integer;
s:char;
begin
t:=1;
j:=length(k);
j:=0+(ord(k[j])-ord('0'))*t;
for i:=length(k)-1 downto 1 do
begin
s:=k;t:=t*2;
j:=j + ((ord(s)-ord('0'))*t);
end;
bintooct:=j;
end;

function GetComputerNameString:String;
var
ComputerName: array[0..MAX_COMPUTERNAME_LENGTH+1] of char;
Size: Dword;
begin
Size := MAX_COMPUTERNAME_LENGTH+1;
if GetComputerName(ComputerName,Size) then
Result := StrPas(Computername)
end;

function NetGetLocalIP:String;
var
HostEnt: PHostEnt;
Ip: string;
addr: pchar;
Buffer: array [0..63] of char;
GInitData: TWSADATA;
begin
Result :='';
try
WSAStartup(2, GInitData);
GetHostName(Buffer, SizeOf(Buffer));
HostEnt := GetHostByName(buffer);
if HostEnt = nil then Exit;
addr := HostEnt^.h_addr_list^;
ip := Format('%d.%d.%d.%d', [byte(addr [0]),
byte (addr [1]), byte (addr [2]), byte (addr [3])]);
Result:=ip;
finally
WSACleanup;
end;
end;

function EnumInterfaces(var IPAddress,IPSubNetMask,BroadcastAddress,Online: string): Boolean;
var
s: TSocket;
wsaD: WSADATA;
NumInterfaces: Integer;
BytesReturned, SetFlags: u_long;
pAddrInet: SOCKADDR_IN;
pAddrString: PCHAR;
PtrA: pointer;
Buffer: array[0..20] of INTERFACE_INFO;
i,j: Integer;
a:string;
b:String;
c:array[0..3] of String;
d:array[0..3] of String;
e:array[0..3] of String;
begin
result := true; // Initialize
WSAStartup($0101, wsaD); // Start WinSock
s := Socket(AF_INET, SOCK_STREAM, 0); // Open a socket
if (s = INVALID_SOCKET) then exit;
try // Call WSAIoCtl
PtrA := @bytesReturned;
if (WSAIoCtl(s, SIO_GET_INTERFACE_LIST, nil, 0, @Buffer, 1024, PtrA, nil,
nil)
<> SOCKET_ERROR) then
begin // If ok, find out how
NumInterfaces := BytesReturned div SizeOf(INTERFACE_INFO);
for i:=0 to NumInterfaces-1 do
begin
pAddrInet := Buffer.iiAddress.addressIn; // IP ADDRESS
pAddrString := inet_ntoa(pAddrInet.sin_addr);
a:=pAddrString ;
if pAddrString=NetGetLocalIP then
IPAddress := pAddrString;
pAddrInet := Buffer.iiNetMask.addressIn; // SUBNET MASK
pAddrString := inet_ntoa(pAddrInet.sin_addr);
if (a =NetGetLocalIP) and (IPAddress<>'127.0.0.1') then
IPSubNetMask := pAddrString ;
pAddrInet := Buffer.iiBroadCastAddress.addressIn; // Broadcast addr
pAddrString := inet_ntoa(pAddrInet.sin_addr);
if (a =NetGetLocalIP) and (IPAddress<>'127.0.0.1') then
BroadcastAddress := '' ;
SetFlags := Buffer.iiFlags;
if (a =NetGetLocalIP) and (IPAddress<>'127.0.0.1') and ((SetFlags and IFF_UP) = IFF_UP) then
Online := 'UP'
else if (IPAddress =NetGetLocalIP) and (IPAddress<>'127.0.0.1') and ((SetFlags and IFF_UP) <> IFF_UP) then
OnLine := 'DOWN';
end;
end;
b:=IPAddress+'.';
if IPAddress<>'' then
begin
for i:=0 to 3 do
begin
c:=Copy(b,1,Pos('.',b)-1);
b:=Copy(b,Pos('.',b)+1,Length(b));
end;
end;
b:=IPSubNetMask+'.';
if IPSubNetMask<>'' then
begin
for i:=0 to 3 do
begin
d:=Copy(b,1,Pos('.',b)-1);
b:=Copy(b,Pos('.',b)+1,Length(b));
end;
end;
if (IPAddress<>'') and (IPSubNetMask<>'') then
begin
for i:=0 to 3 do
begin
c:=OctToBin(StrToInt(c));
d:=OctToBin(StrToInt(d));
e:=d;
end;
for i:=0 to 3 do
begin
b:=e;
for j:=0 to length(d) do
begin
if (d)[j]='1' then
b[j]:=(c)[j]
else
b[j]:='1';
end;
e:=Copy(b,1,8);
end;
for i:=0 to 2 do
e:=IntToStr(BinToOct(e))+'.';
e:=IntToStr(BinToOct(e[3]));
end;
for i:=0 to 3 do
BroadcastAddress:=BroadCastAddress+e;
except

end;
CloseSocket(s);
WSACleanUp;
result := True;
end;

end.
 
问一下,可不可以通过读注册表得到本机IP地址或者计算机名称呢?
还有有没有简单易行的方法呢,
呵呵
谢谢大家关注
 
ping 本机名
 
对不起,请用程序实现
 
HKEY_LOCAL_MACHINE/System/CurrentControlSet/
Services/Class/NetTrans/0000 抄的你看看有没有。有就读它就可
 
就用我的这个函数足够了~
uses winsock;

function getlocalip():string;
var
wsdata:Twsadata;
PCName : array[0..128] of char;
begin
Wsastartup($101,wsdata);
GetHostName(@PCName,128);
result := iNet_ntoa(PInAddr(GetHostByName(@PCName)^.h_addr_list^)^);
WSACleanup; {读取当前IP地址}
end;
 
放两个edit1,edit2分别显示本地计算机名和ip地址:
uses shellapi,winsock;

procedure Form1.FormCreate(Sender: TObject);
var
name:pchar;
len:Dword;//ip地址
Ip:string;
Ipstr:string;
buffer:array[1..32] of char;
i:integer;
WSData:TWSAData;
Host:PHostEnt;
begin
//获取本机计算机名
len:=30;
getmem(name,30);
Getcomputername(name,len);
edit1.text:=name;
//获取本机的ip地址
if WSAstartup(2,WSData)<>0 then //为程序使用WS2_32.DLL初始化
begin
showmessage('WS2_32.DLL初始化失败!');
halt;
end;
try
if gethostname(@buffer[1],32)<>0 then
begin
showmessage('没有得到主机名!');
halt;
end;
except
showmessage('没有成功返回主机名');
halt;
end;
Host:=gethostbyname(@buffer[1]);
if Host=nil then
begin
showmessage('IP地址为空!');
halt;
end
else
begin
for i:=1 to 4 do
begin
Ip:=inttostr(Ord(Host.h_addr^[i-1]));
// showmessage('分段Ip地址为:'+Ip);
Ipstr:=Ipstr+Ip;
if i<4 then
Ipstr:=Ipstr+'.'
else
begin
edit2.Text:=ipstr;
end;
end;
end;
end;
 
接受答案了.
 

Similar threads

S
回复
0
查看
3K
SUNSTONE的Delphi笔记
S
S
回复
0
查看
2K
SUNSTONE的Delphi笔记
S
D
回复
0
查看
2K
DelphiTeacher的专栏
D
后退
顶部