请问获取子网掩码的函数 ( 积分: 50 )

  • 主题发起人 主题发起人 yx127
  • 开始时间 开始时间
Y

yx127

Unregistered / Unconfirmed
GUEST, unregistred user!
请问怎样获取本机的子网掩码,这个函数怎么写或者调用什么?谢谢![:)]
 
请问怎样获取本机的子网掩码,这个函数怎么写或者调用什么?谢谢![:)]
 
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.
 
to sword_liu,
你的代码太长了。我现在已经获得ip,也可以根据ip 和子网掩码写广播地址,我现在只要一个获得子网掩码的小程序。并且,刚才那段程序,我添加了简单的控件和程序,可是看不到我要的结果,有没有简单可行的,谢谢[:)]。
 
Const
MAX_HOSTNAME_LEN = 128; { from IPTYPES.H }
MAX_DOMAIN_NAME_LEN = 128;
MAX_SCOPE_ID_LEN = 256;
MAX_ADAPTER_NAME_LENGTH = 256;
MAX_ADAPTER_DESCRIPTION_LENGTH = 128;
MAX_ADAPTER_ADDRESS_LENGTH = 8;

Type
TIPAddressString = Array[0..4*4-1] of Char;

PIPAddrString = ^TIPAddrString;
TIPAddrString = Record
Next : PIPAddrString;
IPAddress : TIPAddressString;
IPMask : TIPAddressString;
Context : Integer;
End;

PFixedInfo = ^TFixedInfo;
TFixedInfo = Record { FIXED_INFO }
HostName : Array[0..MAX_HOSTNAME_LEN+3] of Char;
DomainName : Array[0..MAX_DOMAIN_NAME_LEN+3] of Char;
CurrentDNSServer : PIPAddrString;
DNSServerList : TIPAddrString;
NodeType : Integer;
ScopeId : Array[0..MAX_SCOPE_ID_LEN+3] of Char;
EnableRouting : Integer;
EnableProxy : Integer;
EnableDNS : Integer;
End;

PIPAdapterInfo = ^TIPAdapterInfo;
TIPAdapterInfo = Record { IP_ADAPTER_INFO }
Next : PIPAdapterInfo;
ComboIndex : Integer;
AdapterName : Array[0..MAX_ADAPTER_NAME_LENGTH+3] of Char;
Description : Array[0..MAX_ADAPTER_DESCRIPTION_LENGTH+3] of Char;
AddressLength : Integer;
Address : Array[1..MAX_ADAPTER_ADDRESS_LENGTH] of Byte;
Index : Integer;
_Type : Integer;
DHCPEnabled : Integer;
CurrentIPAddress : PIPAddrString;
IPAddressList : TIPAddrString;
GatewayList : TIPAddrString;
DHCPServer : TIPAddrString;
HaveWINS : Bool;
PrimaryWINSServer : TIPAddrString;
SecondaryWINSServer : TIPAddrString;
LeaseObtained : Integer;
LeaseExpires : Integer;
End;

Function GetAdaptersInfo(AI : PIPAdapterInfo; Var BufLen : Integer) : Integer;
StdCall; External 'iphlpapi.dll' Name 'GetAdaptersInfo';

procedure GetAdapterInformation(Out sl : TStrings);
Var
AI,Work : PIPAdapterInfo;
Size : Integer;
Res : Integer;
Function GetAddrString(Addr : PIPAddrString) : String;
Begin
Result := '';
While (Addr <> nil) do Begin
Result := Result+ 'Mask: '+Addr^.IPMask+#13;
Addr := Addr^.Next;
End;
End;
begin
Size := 5120;
GetMem(AI,Size);
Res := GetAdaptersInfo(AI,Size);
If (Res <> ERROR_SUCCESS) Then Begin
SetLastError(Res);
RaiseLastWin32Error;
End;
Work := AI;
Repeat
sl.Add(GetAddrString(@Work^.IPAddressList));
Work := Work^.Next;
Until (Work = nil);
FreeMem(AI);
end;
//测试
procedure TForm1.Button1Click(Sender: TObject);
Var
sl : TStrings;
begin
sl := TStringList.Create;
GetAdapterInformation(sl);
Memo1.Lines.CommaText := sl.CommaText;
FreeAndNil(sl);
end;
 
多人接受答案了。
 

Similar threads

回复
0
查看
989
不得闲
回复
0
查看
864
不得闲
S
回复
0
查看
1K
SUNSTONE的Delphi笔记
S
后退
顶部