LAN info - Windows only

Share your advanced PureBasic knowledge/code with the community.
User avatar
doctorized
Addict
Addict
Posts: 856
Joined: Fri Mar 27, 2009 9:41 am
Location: Athens, Greece

Re: LAN info - Windows only

Post by doctorized »

I corrected the code. I did some additional corrections and improvements. Only isatap adapters are not detected but GetAdaptersInfo_() is not returning them.

Code: Select all

#MIB_IF_TYPE_OTHER = 1
#MIB_IF_TYPE_ETHERNET = 6
#MIB_IF_TYPE_TOKENRING = 9
#MIB_IF_TYPE_FDDI = 15
#MIB_IF_TYPE_PPP = 23
#MIB_IF_TYPE_LOOPBACK = 24
#MIB_IF_TYPE_SLIP = 28
#MIB_IF_TYPE_80211 = 71

#MIB_IF_OPER_STATUS_NON_OPERATIONAL = 0
#MIB_IF_OPER_STATUS_UNREACHABLE = 1
#MIB_IF_OPER_STATUS_DISCONNECTED = 2
#MIB_IF_OPER_STATUS_CONNECTING = 3
#MIB_IF_OPER_STATUS_CONNECTED = 4
#MIB_IF_OPER_STATUS_OPERATIONAL = 5

#BROADCAST_NODETYPE = 1
#PEER_TO_PEER_NODETYPE = 2
#MIXED_NODETYPE = 4
#HYBRID_NODETYPE = 8

Structure IP_ADDR_STRING1
    *NextAdapter.IP_ADDR_STRING1
    ;NextAdapter.i
    IpAddress.a[16];IP_ADDRESS_STRING
    IpMask.a[16];IP_ADDRESS_STRING
    Context.i
 EndStructure
 
 Structure FIXED_INFO1
    HostName.a[132]            ;MAX_HOSTNAME_LEN + 4
    DomainName.a[132]         ;MAX_DOMAIN_NAME_LEN + 4
    CurrentDnsServer.i
    DnsServerList.IP_ADDR_STRING1
    NodeType.l
    ScopeId.a[260]             ;MAX_SCOPE_ID_LEN + 4
    EnableRouting.l
    EnableProxy.l
    EnableDns.l
 EndStructure
 
Structure IP_ADAPTER_INFO1
    NextAdapter.i
    ComboIndex.l
    AdapterName.a[260] ;MAX_ADAPTER_NAME_LENGTH + 4
    Description.a[132] ;MAX_ADAPTER_DESCRIPTION_LENGTH + 4
    AddressLength.l
    Address.a[8] ;MAX_ADAPTER_ADDRESS_LENGTH
    index.l
    Type.l
    DhcpEnabled.i
    CurrentIpAddress.i
    IpAddressList.IP_ADDR_STRING1
    GatewayList.IP_ADDR_STRING1
    DhcpServer.IP_ADDR_STRING1
    HaveWINS.i
    PrimaryWinsServer.IP_ADDR_STRING1
    SecondaryWinsServer.IP_ADDR_STRING1
    LeaseObtained.i
    LeaseExpires.i
 EndStructure
 
 Structure MIB_IFROW2
  StructureUnion
    Value.q
    Value2.q
  EndStructureUnion
  InterfaceIndex.l
  InterfaceGuid.a[16]
  Alias.w[257]
  Description.w[257]
  PhysicalAddressLength.l
  PhysicalAddress.a[32]
  PermanentPhysicalAddress.a[32]
  Mtu.l
  Type.l
  TunnelType.l;
  MediaType.l
  PhysicalMediumType.l
  AccessType.l
  DirectionType.l
  InterfaceAndOperStatusFlags.l
  OperStatus.l
  AdminStatus.l
  MediaConnectState.l
  NetworkGuid.a[16]
  ConnectionType.q
  TransmitLinkSpeed.q
  ReceiveLinkSpeed.q
  InOctets.q
  InUcastPkts.q
  InNUcastPkts.q
  InDiscards.q
  InErrors.q
  InUnknownProtos.q
  InUcastOctets.q
  InMulticastOctets.q
  InBroadcastOctets.q
  OutOctets.q
  OutUcastPkts.q
  OutNUcastPkts.q
  OutDiscards.q
  OutErrors.q
  OutUcastOctets.q
  OutMulticastOctets.q
  OutBroadcastOctets.q
  OutQLen.q
EndStructure 

Structure MIB_IFROW
    wszName.a[512]
    dwIndex.l
    dwType.l
    dwMtu.l
    dwSpeed.l
    dwPhysAddrLen.l
    bPhysAddr.a[8]
    dwAdminStatus.l
    dwOperStatus.l
    dwLastChange.l
    dwInOctets.l
    dwInUcastPkts.l
    dwInNUcastPkts.l
    dwInDiscards.l
    dwInErrors.l
    dwInUnknownProtos.l
    dwOutOctets.l
    dwOutUcastPkts.l
    dwOutNUcastPkts.l
    dwOutDiscards.l
    dwOutErrors.l
    dwOutQLen.l
    dwDescrLen.l
    bDescr.a[256]
 EndStructure

Structure MIB_IFTABLE1
    dwNumEntries.l
    table.MIB_IFROW[256]
 EndStructure
 
Structure NetWorkInfo
index.l
HostName.s
DomainName.s
DNSIPAdd.s[11]
nod.s
ScopeID.s
DNSE.s
ProxyE.s
RoutE.s
Conx.s
AdapterName.s[11]
Type.s[11]
Speed.s[11]
sMTU.s[11]
packsS.s[11]
bytesS.s[11]
packsR.s[11]
bytesR.s[11]
status.s[11]
Array IPAddr.s(11,256)
Array SubMask.s(11,256)
Addr.s[11]
Indx.s[11]
DHCPE.s[11]
DHCPIPAddr.s[11]
DHCPIPMask.s[11]
DHCPLObt.s[11]
DHCPLExp.s[11]
GateIPAddress.s[11]
GateIPMask.s[11]
HaveWINS.s[11]
PWINSIPAddress.s[11]
PWINSIPMask.s[11]
SWINSIPAddress.s[11]
SWINSIPMask.s[11]
HWInterface.s[11]
FilterInterface.s[11]
HasConntectorPresent.s[11]
PortAuthenticated.s[11]
MediaConnected.s[11]
Paused.s[11]
LowPower.s[11]
EndPoint.s[11]
EndStructure

Global MIB_IFTABLE.MIB_IFTABLE1
 Global NewList NICs.s()
 Global GroupDemicals.s = ","
 Global GroupThousands.s = "."
 Global LANInfo.NetWorkInfo
 
 Procedure.d int32_uint32(lValue.l)
int32uint32.l
    If lValue < 0
        int32uint32 = lValue + $100000000
    Else
        int32uint32 = lValue
    EndIf
    ProcedureReturn int32uint32
 EndProcedure
 
 Procedure.s c2str(num.d, demical.l=0)
ProcedureReturn ReplaceString(StrD(num,demical), ".", GroupDemicals)
EndProcedure

Procedure.s FormatByteSize(n.q)
  Protected s.s=Str(n)
  Protected len=Len(s)
  Protected ret.s
 
  For i=0 To len-1
    If i And Not i%3 : ret="." + ret : EndIf; "." is the greek symbol for separating thousands. Use your own.
    ret= Mid(s,len-i,1) +ret
  Next
 
  ProcedureReturn ret
EndProcedure

Procedure.s SpaceDivider(space.q)
tm.s:mt.d=space
If mt>1000: mt / 1024:tm = " KB":EndIf
If mt>1000: mt / 1024:tm = " MB":EndIf
If mt>1000: mt / 1024:tm = " GB":EndIf
If mt>1000: mt / 1024:tm = " TB":EndIf
ProcedureReturn ReplaceString(StrD(mt,3), ".", GroupDemicals) + tm
EndProcedure

Procedure.s GetRegString(hKey.l, strPath.s, strValue.s, RegType.l=2)
KeyHand.l:datatype.l:lResult.l
Dim strBuf.a(1):lDataBufSize.l
intZeroPos.l:tempV.l:mm.l
RegOpenKeyEx_(hKey, strPath, 0, 1, @KeyHand)
lResult = RegQueryValueEx_(KeyHand, strValue, 0, @lValueType, 0, @lDataBufSize)
If lDataBufSize > 0
	*Buffer = AllocateMemory(lDataBufSize)
Else 
	ProcedureReturn
EndIf
lResult = RegQueryValueEx_(KeyHand, @strValue, 0, @RegType, *Buffer, @lDataBufSize)
If lResult = #ERROR_SUCCESS
	ProcedureReturn PeekS(*Buffer,-1,#PB_Unicode)
EndIf
EndProcedure

Procedure LAN()
lErrors = GetAdaptersInfo_(0, @lBufferLength)
CardsFound.i = lBufferLength/SizeOf(IP_ADAPTER_INFO1)
Dim IP_ADAPTER_INFO.IP_ADAPTER_INFO1(CardsFound)
lErrors = GetAdaptersInfo_(@IP_ADAPTER_INFO(0), @lBufferLength)
If lErrors <> #ERROR_SUCCESS: MessageRequester("Error","GetAdaptersInfo_() error."): ProcedureReturn: EndIf
lBufferPos.l
tmp.s
tmp2.d
lErrors = GetIfTable_(@MIB_IFTABLE, @lSize, 0)
lSize = SizeOf(MIB_IFTABLE1)
lErrors = GetIfTable_(@MIB_IFTABLE, @lSize, 0)
If MIB_IFTABLE\dwNumEntries <> 0
	GetIfTables.i = MIB_IFTABLE\dwNumEntries; we need to know how many are the tables to retrieve them.
EndIf

Dim If_entry.MIB_IFROW2(GetIfTables - 1)

If OSVersion() >= #PB_OS_Windows_Vista
	If_entry2.MIB_IFROW2
	Lib_iphlpapi = OpenLibrary(#PB_Any,"iphlpapi.dll")
	If Lib_iphlpapi<> 0
		GetIfEntry=GetFunction(Lib_iphlpapi,"GetIfEntry2")
	EndIf
	CloseLibrary(Lib_iphlpapi)
	For ii=1 To GetIfTables
		If_entry2\InterfaceIndex = ii
		CallFunctionFast(GetIfEntry, @If_entry2)
		CopyMemory(@If_entry2, @If_entry(ii-1),SizeOf(MIB_IFROW2))
		ClearStructure(@If_entry2, MIB_IFROW2)
	Next
Else
	If_entry1.MIB_IFROW
	For ii=1 To GetIfTables
		IF_entry1\dwIndex = ii
		GetIfEntry_(@If_entry1)
		CopyMemory(@If_entry1\bDescr, @If_entry(ii-1)\Description, 256)
		CopyMemory(@If_entry1\bPhysAddr, @If_entry(ii-1)\PhysicalAddress, 8)
		If_entry(ii-1)\AdminStatus = If_entry1\dwAdminStatus
		If_entry(ii-1)\InterfaceIndex = If_entry1\dwIndex
		If_entry(ii-1)\InDiscards = If_entry1\dwInDiscards
		If_entry(ii-1)\InNUcastPkts = If_entry1\dwInNUcastPkts
		If_entry(ii-1)\InOctets = If_entry1\dwInOctets
		If_entry(ii-1)\InUcastPkts = If_entry1\dwInUcastPkts
		If_entry(ii-1)\Mtu = If_entry1\dwMtu
		If_entry(ii-1)\OperStatus = If_entry1\dwOperStatus
		If_entry(ii-1)\OutNUcastPkts = If_entry1\dwOutNUcastPkts
		If_entry(ii-1)\OutOctets = If_entry1\dwOutOctets
		If_entry(ii-1)\OutUcastPkts = If_entry1\dwOutUcastPkts
		If_entry(ii-1)\TransmitLinkSpeed = If_entry1\dwSpeed
	Next
EndIf

	xx = 0
	Dim FIXED_INFO.FIXED_INFO1(9)
	lBufferLength = SizeOf(FIXED_INFO1)*9
	lErrors = GetNetworkParams_(@FIXED_INFO(), @lBufferLength)
	For i=0 To 9
		With FIXED_INFO(i)
			If \HostName = 0:Break:EndIf
		IP_ADDR_STRING.IP_ADDR_STRING1
		LANInfo\HostName = PeekS(@\Hostname,-1,#PB_Ascii)
		LANInfo\DomainName = PeekS(@\DomainName,-1,#PB_Ascii)
		If \EnableDns = 1:  LANInfo\DNSE = "Yes": Else: LANInfo\DNSE = "No": EndIf
		LANInfo\DNSIPAdd[xx] = PeekS(@\DnsServerList\IpAddress,-1,#PB_Ascii)
		lNext.l = \DnsServerList\NextAdapter
		While aa.l=0
			If lNext <> 0 
				If IsBadReadPtr_(lNext, SizeOf(IP_ADDR_STRING1)) = #False
					MoveMemory(@lNext, @IP_ADDR_STRING, SizeOf(IP_ADDR_STRING1))
				EndIf
				If lNext <> IP_ADDR_STRING\NextAdapter 
					lNext = IP_ADDR_STRING\NextAdapter
					xx = xx + 1
					LANInfo\DNSIPAdd[xx] = PeekS(@IP_ADDR_STRING\IpAddress[0],-1,#PB_Ascii)
				Else
					aa=1
				EndIf
			Else
				aa=1
			EndIf
		Wend
		Select \NodeType
			Case #BROADCAST_NODETYPE: LANInfo\nod = "Broadcast"
			Case #PEER_TO_PEER_NODETYPE: LANInfo\nod = "Peer To Peer"
			Case #MIXED_NODETYPE: LANInfo\nod = "Mixed"
			Case #HYBRID_NODETYPE: LANInfo\nod = "Hybrid"
			Default: LANInfo\nod = "Unknown " + Str(\NodeType)
		EndSelect
		LANInfo\ScopeID = ReplaceString(PeekS(@\ScopeId[0],-1,#PB_Ascii), Chr(0), "")
		If \EnableProxy = 1: LANInfo\ProxyE = "Yes": Else: LANInfo\ProxyE = "No": EndIf
		If \EnableRouting = 1:  LANInfo\RoutE = "Yes": Else: LANInfo\RoutE = "No": EndIf
	EndWith
	Next
	Dim tmpMACs.s(GetIfTables)
	For ii =0 To GetIfTables-1
			tmpMAC.s =""
			For iMAC=0 To If_entry(ii)\PhysicalAddressLength -1
				tmpMAC + RSet(Hex(PeekA(@if_entry(ii)\PhysicalAddress[iMAC])),2,"0") + ":"
			Next
			tmpMACs(ii) = Left(tmpMAC,Len(tmpMAC)-1)
		Next
		For ii = 0 To CardsFound-1
			tmpMAC.s =""
			For iMAC=0 To IP_ADAPTER_INFO(ii)\AddressLength-1
				tmpMAC + RSet(Hex(PeekA(@IP_ADAPTER_INFO(ii)\Address[iMAC])),2,"0") + ":"
			Next
			LANInfo\Addr[ii] = Left(tmpMAC,Len(tmpMAC)-1)
		Next
For i = 0 To CardsFound-1
	With IP_ADAPTER_INFO(i)		
		Select \Type
			Case #MIB_IF_TYPE_OTHER: LANInfo\Type[i] = "Other"
			Case #MIB_IF_TYPE_ETHERNET: LANInfo\Type[i] = "Ethernet"
			Case #MIB_IF_TYPE_TOKENRING: LANInfo\Type[i] = "Tokenring"
			Case #MIB_IF_TYPE_FDDI: LANInfo\Type[i] = "FDDI"
			Case #MIB_IF_TYPE_PPP: LANInfo\Type[i] = "PPP"
			Case #MIB_IF_TYPE_LOOPBACK: LANInfo\Type[i] = "Loopback"
			Case #MIB_IF_TYPE_SLIP: LANInfo\Type[i] = "Slip"
			Case #MIB_IF_TYPE_80211: LANInfo\Type[i] = "802.11 wireless network"
			Default: LANInfo\Type[i] = "Unknown " + Str(\Type)
		EndSelect
		
		For ii = 0 To GetIfTables-1
			;If PeekS(@If_entry(ii)\Description,-1,#PB_Unicode) = LANInfo\AdapterName[i]
			If tmpMACs(ii) = LANInfo\Addr[i] And If_entry(ii)\InterfaceIndex = IP_ADAPTER_INFO(i)\index
				LANInfo\AdapterName[i] = PeekS(@\Description,-1,#PB_Ascii)
				If LANInfo\AdapterName[i] = ""
					LANInfo\AdapterName[i] = PeekS(@If_entry(ii)\Description,-1,#PB_Unicode)
					If LANInfo\AdapterName[i] = ""
						aaa.s = PeekS(@IP_ADAPTER_INFO(i)\AdapterName,-1,#PB_Ascii)
						For ii=0 To 100
							If GetRegString(#HKEY_LOCAL_MACHINE, "SOFTWARE\Microsoft\Windows NT\CurrentVErsion\NetworkCards\" + Str(ii), "ServiceName") = aaa
								LANInfo\AdapterName[i] = GetRegString(#HKEY_LOCAL_MACHINE, "SOFTWARE\Microsoft\Windows NT\CurrentVErsion\NetworkCards\" + Str(ii), "Description")
							EndIf
						Next
					EndIf
				EndIf
		
				tmp2 = int32_uint32(If_entry(ii)\TransmitLinkSpeed): tmp = " bit"
				If tmp2 >= 1000:  tmp2 = tmp2 / 1000: tmp = " Kbit": EndIf
				If tmp2 >= 1000:  tmp2 = tmp2 / 1000: tmp = " Mbit": EndIf
				If tmp2 >= 1000:  tmp2 = tmp2 / 1000: tmp = " Gbit": EndIf
				LANInfo\Speed[i] = c2str(tmp2,2) + tmp
				LANInfo\sMTU[i] = Str(If_entry(ii)\Mtu) + " bytes"
				LANInfo\packsS[i] = FormatByteSize(If_entry(ii)\OutNUcastPkts + If_entry(ii)\OutUcastPkts)
				
				tmp = FormatByteSize(If_entry(ii)\OutOctets)
				If tmp = "":  tmp = "0": EndIf
				If If_entry(ii)\OutOctets > 1024
					tmp + "  ( " + SpaceDivider(If_entry(ii)\OutOctets) + " )"
					If Right(tmp,6) = GroupDemicals + "000 )":tmp=Left(tmp,Len(tmp)-6) + " )": EndIf
				EndIf
				LANInfo\bytesS[i] = tmp
				LANInfo\packsR[i] = FormatByteSize(If_entry(ii)\InNUcastPkts + If_entry(ii)\InUcastPkts)
				
				tmp = FormatByteSize(If_entry(ii)\InOctets)
				If tmp = "":  tmp = "0": EndIf
				If (If_entry(ii)\InOctets) > 1024
					tmp + "  ( " + SpaceDivider(If_entry(ii)\InOctets) + " )"
					If Right(tmp,6) = GroupDemicals + "000 )":tmp=Left(tmp,Len(tmp)-6) + " )": EndIf
				EndIf
				LANInfo\bytesR[i] = tmp
				
				If OSVersion() >= #PB_OS_Windows_Vista; data came from GetIfTable2_()
					Select If_entry(ii)\OperStatus
						Case 1: LANInfo\status[i] = "Operational"
						Case 2: LANInfo\status[i] = "Disconnected"
						Case 3: LANInfo\status[i] = "Testing"
						Case 4: LANInfo\status[i] = "Unknown"
						Case 5: LANInfo\status[i] = "Waiting to become operational"
						Case 6: LANInfo\status[i] = "Disconnected - Some component is not present"
						Case 7: LANInfo\status[i] = "Disconnected - one or more of lower-layer interfaces are down"
						Default: LANInfo\status[i] = "Unknown " + c2str(int32_uint32(If_entry(ii)\OperStatus),0)
					EndSelect
				Else; data came from GetIfTable_()
					Select If_entry(ii)\OperStatus
						Case #MIB_IF_OPER_STATUS_NON_OPERATIONAL: LANInfo\status[i] = "Non operational"
						Case #MIB_IF_OPER_STATUS_UNREACHABLE: LANInfo\status[i] = "Unreachable"
						Case #MIB_IF_OPER_STATUS_DISCONNECTED: LANInfo\status[i] = "Disconnected"
						Case #MIB_IF_OPER_STATUS_CONNECTING: LANInfo\status[i] = "Connecting"
						Case #MIB_IF_OPER_STATUS_CONNECTED: LANInfo\status[i] = "Connected"
						Case #MIB_IF_OPER_STATUS_OPERATIONAL: LANInfo\status[i] = "Operational"
						Default: LANInfo\status[i] = "Unknown " + c2str(int32_uint32(If_entry(ii)\OperStatus),0)
					EndSelect 	
				EndIf
				If OSVersion() >= #PB_OS_Windows_Vista; data came from GetIfTable2_()
					If If_entry(ii)\InterfaceAndOperStatusFlags & 1 = 1
						LANInfo\HWInterface[i] = "Yes"
					Else
						LANInfo\HWInterface[i] = "No"
					EndIf
					
					If (If_entry(ii)\InterfaceAndOperStatusFlags >> 1) & 1 = 1 
						LANInfo\FilterInterface[i] = "Yes"
					Else
						LANInfo\FilterInterface[i] = "No"
					EndIf
					;Debug (If_entry(ii)\InterfaceAndOperStatusFlags >> 2) & 1
					If (If_entry(ii)\InterfaceAndOperStatusFlags >> 2) & 1 = 1
						LANInfo\HasConntectorPresent[i] = "Yes"
					Else
						LANInfo\HasConntectorPresent[i] = "No"
					EndIf
					
					If (If_entry(ii)\InterfaceAndOperStatusFlags >> 3) & 1 = 1
						LANInfo\PortAuthenticated[i] = "No"
					Else
						LANInfo\PortAuthenticated[i] = "Yes"
					EndIf
					
					If (If_entry(ii)\InterfaceAndOperStatusFlags >> 4) & 1 = 1
						LANInfo\MediaConnected[i] = "No"
					Else
						LANInfo\MediaConnected[i] = "Yes"
						If If_entry(ii)\MediaConnectState = 1
							LANInfo\MediaConnected[i] + " (connector is plugged in)"
						ElseIf If_entry(ii)\MediaConnectState = 2
							LANInfo\MediaConnected[i] + " (connector is not plugged in)"
						EndIf
					EndIf
					
					If (If_entry(ii)\InterfaceAndOperStatusFlags >> 5) & 1 = 1
						LANInfo\Paused[i] = "Yes"
					Else
						LANInfo\Paused[i] = "No"
					EndIf
					
					If (If_entry(ii)\InterfaceAndOperStatusFlags >> 6) & 1 = 1
						LANInfo\LowPower[i] = "Yes"
					Else
						LANInfo\LowPower[i] = "No"
					EndIf
					
					If (If_entry(ii)\InterfaceAndOperStatusFlags >> 7) & 1 = 1
						LANInfo\EndPoint[i] = "Yes"
					Else
						LANInfo\EndPoint[i] = "No"
					EndIf
				EndIf
				Break
			EndIf
		Next	
		LANInfo\IPAddr(i,1) = PeekS(@\IpAddressList\IpAddress,-1,#PB_Ascii)
		LANInfo\SubMask(i,1) = PeekS(@\IpAddressList\IpMask,-1,#PB_Ascii)
		;ShowMemoryViewer(@\IpAddressList,SizeOf(IP_ADDR_STRING1))
		;If PeekI(@\IpAddressList\NextAdapter) <> 0
		aam.i = \IpAddressList\NextAdapter
		If \IpAddressList\NextAdapter >20000;<> 0
			*dum.IP_ADDR_STRING1 = \IpAddressList\NextAdapter
			For iia = 2 To 256
				;*dum.IP_ADDR_STRING1 = \IpAddressList\NextAdapter
		;		ShowMemoryViewer(*dum,SizeOf(IP_ADDR_STRING1))
				LANInfo\IPAddr(i,iia) = PeekS(@*dum\IpAddress,-1,#PB_Ascii)
				LANInfo\SubMask(i,iia) = PeekS(@*dum\IpMask,-1,#PB_Ascii)
				If *dum\NextAdapter <> 0
					Debug *dum\NextAdapter
					*dum = *dum\NextAdapter
				Else
					Break
				EndIf
			Next
		EndIf
		;tmp = ""
		;If Len(PeekS(@\AdapterName,-1,#PB_Ascii)) >= \AddressLength
		;	For lIncrement.l = 0 To \AddressLength-1
		;		tmp = tmp + RSet(Hex(\Address[lIncrement] & $FF),2,"0")
		;	Next lIncrement
		;	tmp = RSet(tmp,12,"0")
		;	tmp = Left(tmp, 2) + ":" + Mid(tmp, 3, 2) + ":" + Mid(tmp, 5, 2) + ":" + Mid(tmp, 7, 2) + ":" + Mid(tmp, 9, 2) + ":" + Mid(tmp, 11, 2)
		;	LANInfo\Addr[i] = tmp
		;EndIf
		LANInfo\Indx[i] = (c2str(int32_uint32(\Index),0))
		
		If \DhcpEnabled = 1:  LANInfo\DHCPE[i] = "Yes": Else: LANInfo\DHCPE[i] = "No": EndIf
		LANInfo\DHCPIPAddr[i] = PeekS(@\DhcpServer\IpAddress,-1,#PB_Ascii)
		LANInfo\DHCPIPMask[i] = PeekS(@\DhcpServer\IpMask,-1,#PB_Ascii)
		
		TZResult = GetTimeZoneInformation_(@TZinfo.TIME_ZONE_INFORMATION)
		Select TZResult
			Case 0, 1 ;Use standard time UTC offset
				TZResult = TZinfo\Bias
			Case 2 ;Use daylight savings time UTC offset
				TZResult = TZinfo\Bias - 60
		EndSelect
		If \LeaseObtained > 10000 
			tmp = FormatDate("%dd/%mm/%yyyy , %hh:%ii:%ss",AddDate( 1/1/1970,#PB_Date_Second, \LeaseObtained))
			LANInfo\DHCPLObt[i] = FormatDate("%dd/%mm/%yyyy , %hh:%ii:%ss",AddDate( ParseDate("%dd/%mm/%yyyy , %hh:%ii:%ss",tmp),#PB_Date_Minute,-TZResult ))
		Else
		LANInfo\DHCPLObt[i] = "NotAvailable"
		EndIf
		If \LeaseExpires > 10000 
			tmp = FormatDate("%dd/%mm/%yyyy , %hh:%ii:%ss",AddDate( 1/1/1970,#PB_Date_Second, \LeaseExpires))
			LANInfo\DHCPLExp[i] = FormatDate("%dd/%mm/%yyyy , %hh:%ii:%ss",AddDate( ParseDate("%dd/%mm/%yyyy , %hh:%ii:%ss",tmp),#PB_Date_Minute,-TZResult))
		Else
			LANInfo\DHCPLExp[i] = "NotAvailable"
		EndIf
		
		CopyMemory(@\IpAddressList,@IP_ADDR_STRING,SizeOf(IP_ADDR_STRING1))
		For ii=0 To 100
			If IP_ADDR_STRING\NextAdapter <> 0 
				If IsBadReadPtr_(@IP_ADDR_STRING\NextAdapter, SizeOf(IP_ADDR_STRING1)) = #False 
					MoveMemory(@IP_ADDR_STRING\NextAdapter, @IP_ADDR_STRING, SizeOf(IP_ADDR_STRING1))
				EndIf
			Else
				Break
			EndIf
		Next
		LANInfo\GateIPAddress[i] = PeekS(@\GatewayList\IpAddress,-1,#PB_Ascii)
		LANInfo\GateIPMask[i] = PeekS(@\GatewayList\IpMask,-1,#PB_Ascii)
		If \HaveWINS = 1:  LANInfo\HaveWINS[i] = "Yes": Else: LANInfo\HaveWINS[i] = "No": EndIf
		LANInfo\PWINSIPAddress[i] = PeekS(@\PrimaryWinsServer\IpAddress,-1,#PB_Ascii)
		LANInfo\PWINSIPMask[i] = PeekS(@\PrimaryWinsServer\IpMask,-1,#PB_Ascii)
		LANInfo\SWINSIPAddress[i] = PeekS(@\SecondaryWinsServer\IpAddress,-1,#PB_Ascii)
		LANInfo\SWINSIPMask[i] = PeekS(@\SecondaryWinsServer\IpMask,-1,#PB_Ascii)
	EndWith
Next
EndProcedure

Procedure SaveFile()
Pattern$ = "Text (*.txt)|*.txt|All files (*.*)|*.*"
Pattern = 0
File$ = SaveFileRequester("Please choose file name", "LAN Info", Pattern$, Pattern)
If File$
	If ReadFile(0,File$);file already exists
		CloseFile(0)
		i=MessageRequester("Warning","File already exists. Overwrite ?",#PB_MessageRequester_YesNo)
		If i= #PB_MessageRequester_No			
			ProcedureReturn
		EndIf
	EndIf
	If GetExtensionPart(File$) = ""
		File$ + ".txt"
	EndIf
	ii = OpenFile(#PB_Any,File$)
	If ii
		For i=0 To CountGadgetItems(0)
			tmp$ = GetGadgetItemText(0,i,0)
			If tmp$ = ""
				WriteStringN(ii, "")
			ElseIf FindString(tmp$,"Connection  #") > 0
				WriteStringN(ii,tmp$)
			Else
				WriteStringN(ii,LSet(tmp$,36," ") + " : " + GetGadgetItemText(0,i,1))
			EndIf
		Next
		CloseFile(ii)
		MessageRequester("","File created successfully.")
	Else
		MessageRequester("","Cannot create file.",#MB_ICONERROR)
	EndIf
EndIf
EndProcedure

If OpenWindow(0, 0, 0, 542, 510, "LAN", #PB_Window_SystemMenu | #PB_Window_ScreenCentered| #PB_Window_MinimizeGadget)
 		ListIconGadget(0,5,5,532,480,"Element",200,#PB_ListIcon_GridLines | #PB_ListIcon_FullRowSelect)
 		AddGadgetColumn(0,1,"Data",310)
 		ButtonGadget(1,450,485,70,25,"save data")
EndIf

LAN()
AddGadgetItem(0,-1,"Host  name"+Chr(10)+LANInfo\HostName)
AddGadgetItem(0,-1,"Domain  name"+Chr(10)+LANInfo\DomainName)
AddGadgetItem(0,-1,"DNS  enabled"+Chr(10)+LANInfo\DNSE)
For i=0 To 10
	If LANInfo\DNSIPAdd[i] <> ""
		AddGadgetItem(0,-1,"DNS  Server  IP  address  #" + Str(i+1)+Chr(10)+LANInfo\DNSIPAdd[i])
	EndIf
Next
AddGadgetItem(0,-1,"Node  type"+Chr(10)+LANInfo\nod)
AddGadgetItem(0,-1,"Scope  ID"+Chr(10)+LANInfo\ScopeID)
AddGadgetItem(0,-1,"WINS  Proxy  Enabled"+Chr(10)+LANInfo\ProxyE)
AddGadgetItem(0,-1,"IP  Routing  Enabled"+Chr(10)+LANInfo\RoutE)
For i=0 To 10
	If LANInfo\Addr[i] <> ""
		AddGadgetItem(0,-1,""+Chr(10)+"")
		AddGadgetItem(0,-1,"Connection  #"+Str(i+1)+Chr(10)+"")
		SetGadgetItemColor(0,CountGadgetItems(0)-1,#PB_Gadget_FrontColor,$906000,0)
		AddGadgetItem(0,-1,"Adapter  name"+Chr(10)+LANInfo\AdapterName[i])
		AddGadgetItem(0,-1,"Type"+Chr(10)+LANInfo\Type[i])
		AddGadgetItem(0,-1,"Speed"+Chr(10)+LANInfo\Speed[i])
		AddGadgetItem(0,-1,"Maximum  Transfer  Unit  Size  (MTU)"+Chr(10)+LANInfo\sMTU[i])
		AddGadgetItem(0,-1,"Packets  sent"+Chr(10)+LANInfo\packsS[i])
		AddGadgetItem(0,-1,"Bytes  sent"+Chr(10)+LANInfo\bytesS[i])
		AddGadgetItem(0,-1,"Packets  received"+Chr(10)+LANInfo\packsR[i])
		AddGadgetItem(0,-1,"Bytes  received"+Chr(10)+LANInfo\bytesR[i])
		AddGadgetItem(0,-1,"Status"+Chr(10)+LANInfo\status[i])
		For ii=1 To 256
			If LANInfo\IPAddr(i,ii) <> ""
				AddGadgetItem(0,-1,"IPv4"+Chr(10)+LANInfo\IPAddr(i,ii))
				AddGadgetItem(0,-1,"SubMask"+Chr(10)+LANInfo\SubMask(i,ii))
			EndIf
		Next
		AddGadgetItem(0,-1,"MAC Address"+Chr(10)+LANInfo\Addr[i])
		AddGadgetItem(0,-1,"Index"+Chr(10)+LANInfo\Indx[i])
		AddGadgetItem(0,-1,"DHCP  enabled"+Chr(10)+LANInfo\DHCPE[i])
		AddGadgetItem(0,-1,"DCHP  IP  address"+Chr(10)+LANInfo\DHCPIPAddr[i])
		AddGadgetItem(0,-1,"DCHP  IP  mask"+Chr(10)+LANInfo\DHCPIPMask[i])
		AddGadgetItem(0,-1,"DHCP lease obtained"+Chr(10)+LANInfo\DHCPLObt[i])
		AddGadgetItem(0,-1,"DHCP lease expires"+Chr(10)+LANInfo\DHCPLExp[i])
		AddGadgetItem(0,-1,"Gateway  IP  address"+Chr(10)+LANInfo\GateIPAddress[i])
		AddGadgetItem(0,-1,"Gateway  IP  mask"+Chr(10)+LANInfo\GateIPMask[i])
		AddGadgetItem(0,-1,"Have  WINS"+Chr(10)+LANInfo\HaveWINS[i])
		If LANInfo\HaveWINS[i] = "Yes"
			AddGadgetItem(0,-1,"Primary  WINS  Server  IP  address"+Chr(10)+LANInfo\PWINSIPAddress[i])
			AddGadgetItem(0,-1,"Primary  WINS  Server  IP  mask"+Chr(10)+LANInfo\PWINSIPMask[i])
			AddGadgetItem(0,-1,"Secondary  WINS  Server  IP  address"+Chr(10)+LANInfo\SWINSIPAddress[i])
			AddGadgetItem(0,-1,"Secondary  WINS  Server  IP  Mask"+Chr(10)+LANInfo\SWINSIPMask[i])
		EndIf
		If OSVersion() >= #PB_OS_Windows_Vista
			AddGadgetItem(0,-1,"Is a hardware interface"+Chr(10)+LANInfo\HWInterface[i])
			AddGadgetItem(0,-1,"Is a filter interface"+Chr(10)+LANInfo\FilterInterface[i])
			AddGadgetItem(0,-1,"Has a connector present"+Chr(10)+LANInfo\HasConntectorPresent[i])
			AddGadgetItem(0,-1,"Is port authenticated"+Chr(10)+LANInfo\PortAuthenticated[i])
			AddGadgetItem(0,-1,"Is media connected"+Chr(10)+LANInfo\MediaConnected[i])
			AddGadgetItem(0,-1,"Is paused"+Chr(10)+LANInfo\Paused[i])
			AddGadgetItem(0,-1,"Is at low power"+Chr(10)+LANInfo\LowPower[i])
			AddGadgetItem(0,-1,"Is an End-Point device"+Chr(10)+LANInfo\EndPoint[i])
		EndIf
	EndIf
Next
	
Repeat
	EventID = WaitWindowEvent()
	If EventID = #PB_Event_CloseWindow
		Quit = 1
	ElseIf EventID = #PB_Event_Gadget
		Select EventGadget()
			Case 1
				SaveFile()
		EndSelect
	EndIf
Until Quit = 1
End   
Damion12
User
User
Posts: 81
Joined: Tue Oct 30, 2012 1:39 am

Re: LAN info - Windows only

Post by Damion12 »

Using 5.43x64, this line

Code: Select all

LANInfo\DNSIPAdd[xx] = PeekS(@IP_ADDR_STRING\IpAddress[0],-1,#PB_Ascii)
generated an error:

Code: Select all

[13:55:27] Waiting for executable to start...
[13:55:27] Executable type: Windows - x64  (64bit, Unicode, Thread, Purifier)
[13:55:27] Executable started.
[13:55:27] [ERROR] LanInfo.pb (Line: 321)
[13:55:27] [ERROR] Structure array index out of bounds.
[13:55:32] [ERROR] LanInfo.pb (Line: 321)
[13:55:32] [ERROR] Invalid memory access. (read error at address 18446744073709551615)
Works perfect on x86
kvitaliy
Enthusiast
Enthusiast
Posts: 162
Joined: Mon May 10, 2010 4:02 pm

Re: LAN info - Windows only

Post by kvitaliy »

Good code.
But there is a way in short :D

Code: Select all

RunProgram("cmd.exe", "/c systeminfo > c:\log.txt", "", #PB_Program_Wait)
RunProgram("c:\log.txt")
User avatar
doctorized
Addict
Addict
Posts: 856
Joined: Fri Mar 27, 2009 9:41 am
Location: Athens, Greece

Re: LAN info - Windows only

Post by doctorized »

Damion12 wrote:Using 5.43x64, this line

Code: Select all

LANInfo\DNSIPAdd[xx] = PeekS(@IP_ADDR_STRING\IpAddress[0],-1,#PB_Ascii)
generated an error:

Code: Select all

[13:55:27] Waiting for executable to start...
[13:55:27] Executable type: Windows - x64  (64bit, Unicode, Thread, Purifier)
[13:55:27] Executable started.
[13:55:27] [ERROR] LanInfo.pb (Line: 321)
[13:55:27] [ERROR] Structure array index out of bounds.
[13:55:32] [ERROR] LanInfo.pb (Line: 321)
[13:55:32] [ERROR] Invalid memory access. (read error at address 18446744073709551615)
Works perfect on x86
I will check it ASAP.

kvitaliy wrote:Good code.
But there is a way in short :D

Code: Select all

RunProgram("cmd.exe", "/c systeminfo > c:\log.txt", "", #PB_Program_Wait)
RunProgram("c:\log.txt")
I tried it, cmd window shows the greek chars correctly but the log file shows them trancated, like chinese. I know it is a pagefile problem but how can I solve it?
kvitaliy
Enthusiast
Enthusiast
Posts: 162
Joined: Mon May 10, 2010 4:02 pm

Re: LAN info - Windows only

Post by kvitaliy »

doctorized wrote: I tried it, cmd window shows the greek chars correctly but the log file shows them trancated, like chinese. I know it is a pagefile problem but how can I solve it?
It is necessary to use the viewer with support for DOS encodings ( ASCII OEM)
SadStar
New User
New User
Posts: 4
Joined: Thu Nov 24, 2016 8:08 am

Re: LAN info - Windows only

Post by SadStar »

if allow I will publish the test code by way of illustration of my approach
to parsing of result of the GetAdaptersInfo_ ()

My way - without Dim IP_ADAPTER_INFO.IP_ADAPTER_INFO1(CardsFound)

Code: Select all


Structure IP_ADDR_STRING
    NextAdapter.i
    IpAddress.a[16];IP_ADDRESS_STRING
    IpMask.a[16];IP_ADDRESS_STRING
    Context.i
EndStructure

Structure FIXED_INFO
	HostName.a[132]            ;MAX_HOSTNAME_LEN + 4
	DomainName.a[132]		   ;MAX_DOMAIN_NAME_LEN + 4
	CurrentDnsServer.i
	DnsServerList.IP_ADDR_STRING
	NodeType.l
	ScopeId.a[260]             ;MAX_SCOPE_ID_LEN + 4
	EnableRouting.l
	EnableProxy.l
	EnableDns.l
EndStructure

Structure IP_ADAPTER_INFO
    NextAdapter.i
    ComboIndex.l
    AdapterName.a[260] ;MAX_ADAPTER_NAME_LENGTH + 4
    Description.a[132] ;MAX_ADAPTER_DESCRIPTION_LENGTH + 4
    AddressLength.l
    Address.a[8] ;MAX_ADAPTER_ADDRESS_LENGTH
    index.l
    Type.l
    DhcpEnabled.i
    CurrentIpAddress.i
    IpAddressList.IP_ADDR_STRING
    GatewayList.IP_ADDR_STRING
    DhcpServer.IP_ADDR_STRING
    HaveWINS.i
    PrimaryWinsServer.IP_ADDR_STRING
    SecondaryWinsServer.IP_ADDR_STRING
    LeaseObtained.i
    LeaseExpires.i
EndStructure

Procedure.s GetSysErrorText(ErrCode)
	Define result.s=""
	*Memory = AllocateMemory (255)
	length = FormatMessage_ (#FORMAT_MESSAGE_FROM_SYSTEM, #Null, ErrCode, 0, *Memory, 255, #Null)
	result=PeekS (*Memory, length - 2)
	FreeMemory (*Memory)
	ProcedureReturn result
EndProcedure

Procedure FatalError() 
   Protected Result$, Line 
   
   Result$="FatalError(): " 
   Line = ErrorLine() 
   If Line>=0 
     Result$+" в строке "+Str(Line)+", файла: "+ErrorFile() 
   EndIf 
   
   Result$+" Ошибка типа: "+Chr(34)+ErrorMessage()+Chr(34) 
   
   MessageRequester("Фатальная ошибка выполнения", Result$, #PB_MessageRequester_Ok )
   End 
EndProcedure

Procedure.s GetIPMask(*buff.IP_ADDR_STRING)
	ProcedureReturn PeekS(@*buff\IpAddress[0],16)+"/"+PeekS(@*buff\IpMask[0],16)
EndProcedure

OnErrorCall(@FatalError())

OpenConsole()

; networks ----------------
*Net_Fixed_INFO_buffer=AllocateMemory(SizeOf(FIXED_INFO),#PB_Memory_NoClear)
If Not *Net_Fixed_INFO_buffer
	PrintN("the memory cannot be allocated")
	Goto Exit
EndIf
lBufferLength.l = MemorySize(*Net_Fixed_INFO_buffer)
lErrors = GetNetworkParams_(*Net_Fixed_INFO_buffer, @lBufferLength)
If lErrors = #ERROR_BUFFER_OVERFLOW
	*Net_Fixed_INFO_buffer=ReAllocateMemory(*Net_Fixed_INFO_buffer,lBufferLength,#PB_Memory_NoClear)
	lErrors = GetNetworkParams_(*Net_Fixed_INFO_buffer, @lBufferLength)
EndIf
If lErrors <> #ERROR_SUCCESS
	PrintN("GetNetworkParams() error")
	Select lErrors
		Case #ERROR_BUFFER_OVERFLOW
			PrintN( "#ERROR_BUFFER_OVERFLOW")
		Case #ERROR_INVALID_DATA
			PrintN( "#ERROR_INVALID_DATA")
		Case #ERROR_INVALID_PARAMETER
			PrintN( "#ERROR_INVALID_PARAMETER")
		Case #ERROR_NO_DATA
			PrintN( "#ERROR_NO_DATA")
		Case #ERROR_NOT_SUPPORTED
			PrintN( "#ERROR_NOT_SUPPORTED")
		Default
			PrintN( GetSysErrorText(lErrors))
	EndSelect
	FreeMemory(*Net_Fixed_INFO_buffer)
	Goto Exit
Else
	*Fixed_Info.FIXED_INFO=*Net_Fixed_INFO_buffer
	PrintN("HostName="+PeekS(@*Fixed_Info\HostName[0],132))
	PrintN("DomainName="+PeekS(@*Fixed_Info\DomainName[0],132))
	;------
	Define *CurrentIpAddress.IP_ADDR_STRING
	*CurrentIpAddress=@*Fixed_Info\DnsServerList
	Repeat
		PrintN("DnsServer IP / MASK = "+GetIPMask(*CurrentIpAddress))
		If *CurrentIpAddress\NextAdapter=0
			Break
		EndIf
		*CurrentIpAddress=*CurrentIpAddress\NextAdapter
	ForEver
	;------
	PrintN("ScopeId="+PeekS(@*Fixed_Info\ScopeId[0],260))
	;-------------------------
	If *Fixed_Info\EnableProxy
		PrintN("local computer is acting as an ARP proxy")
	EndIf
	If *Fixed_Info\EnableRouting
		PrintN("routing is enabled on the local computer")
	EndIf
	If *Fixed_Info\EnableDns
		PrintN("DNS is enabled on the local computer")
	EndIf
EndIf

FreeMemory(*Net_Fixed_INFO_buffer)

; adapters ----------------

*AdaptersInfoBuffer=AllocateMemory(SizeOf(IP_ADAPTER_INFO),#PB_Memory_NoClear)
If Not *AdaptersInfoBuffer
	PrintN("the memory cannot be allocated")
	Goto Exit
EndIf

	lBufferLength.l = MemorySize(*AdaptersInfoBuffer)
	lErrors = GetAdaptersInfo_(*AdaptersInfoBuffer, @lBufferLength)
	If lErrors = #ERROR_BUFFER_OVERFLOW
		*AdaptersInfoBuffer=ReAllocateMemory(*AdaptersInfoBuffer,lBufferLength,#PB_Memory_NoClear)
		lBufferLength = MemorySize(*AdaptersInfoBuffer)
		lErrors = GetAdaptersInfo_(*AdaptersInfoBuffer, @lBufferLength)
	EndIf
	
	If lErrors <> #ERROR_SUCCESS
		PrintN("GetAdaptersInfo() error")
		Select lErrors
			Case #ERROR_BUFFER_OVERFLOW
				PrintN( "#ERROR_BUFFER_OVERFLOW")
			Case #ERROR_INVALID_DATA
				PrintN( "#ERROR_INVALID_DATA")
			Case #ERROR_INVALID_PARAMETER
				PrintN( "#ERROR_INVALID_PARAMETER")
			Case #ERROR_NO_DATA
				PrintN( "#ERROR_NO_DATA")
			Case #ERROR_NOT_SUPPORTED
				PrintN( "#ERROR_NOT_SUPPORTED")
			Default
				PrintN( GetSysErrorText(lErrors))
		EndSelect
		Goto Exit
	Else
		Define *CurrentAdapterInfoBuffer.IP_ADAPTER_INFO
		*CurrentAdapterInfoBuffer=*AdaptersInfoBuffer
		n=0
		Repeat
			PrintN("----------------------")
			PrintN("AdapterName:"+PeekS(@*CurrentAdapterInfoBuffer\AdapterName[0],260))
			PrintN("Description:"+PeekS(@*CurrentAdapterInfoBuffer\Description[0],132))
			MAC$=""
			For i = 0 To *CurrentAdapterInfoBuffer\AddressLength-2
				MAC$ + RSet(Hex(*CurrentAdapterInfoBuffer\Address[i]&255),2,"0") + ":"
			Next
			MAC$ + RSet(Hex(*CurrentAdapterInfoBuffer\Address[i]&255),2,"0")
			PrintN("Adapter address = "+MAC$)
			; IpAddressList -----------
			Define *CurrentIpAddress.IP_ADDR_STRING
			*CurrentIpAddress=@*CurrentAdapterInfoBuffer\IpAddressList
			IP$=""
			Repeat
				PrintN("IP / MASK = "+GetIPMask(*CurrentIpAddress))
				If *CurrentIpAddress\NextAdapter=0
					Break
				EndIf
				*CurrentIpAddress=*CurrentIpAddress\NextAdapter
			ForEver
			; GatewayList -----------
			*CurrentIpAddress=@*CurrentAdapterInfoBuffer\GatewayList
			Repeat
				PrintN("GateWay IP / MASK = "+GetIPMask(*CurrentIpAddress))
				If *CurrentIpAddress\NextAdapter=0
					Break
				EndIf
				*CurrentIpAddress=*CurrentIpAddress\NextAdapter
			ForEver
			;-------------------------
			If *CurrentAdapterInfoBuffer\DhcpEnabled
				PrintN("DHCP : "+GetIPMask(@*CurrentAdapterInfoBuffer\DhcpServer))
			Else
				PrintN("DHCP disable")
			EndIf
			;-------------------------
			If *CurrentAdapterInfoBuffer\NextAdapter=0
				Break
			EndIf
			*CurrentAdapterInfoBuffer=*CurrentAdapterInfoBuffer\NextAdapter
			n+1
			If n>4 ;debug trap
				PrintN("n>4!!!")
				Break
			EndIf
		ForEver
		
	EndIf


	Exit:
	FreeMemory(*AdaptersInfoBuffer)

	PrintN("================"+#CRLF$+"Press Any Key >")
	Repeat
		KeyPressed$ = Inkey()
		
		If KeyPressed$ <> ""
			Break
		EndIf
		Delay(20)
	Until KeyPressed$ = Chr(27)
on my computer the result looks so
--------------------------------------------------------------------
HostName=sadstar
DomainName=xxxxxxxx.xx
DnsServer IP / MASK = 192.168.0.1/
ScopeId=
----------------------
AdapterName:{80C9AF7D-09D4-4E6D-975A-3B872DD211E8}
Description:Realtek PCIe GBE Family Controller - Virtual Machine Network Services Driver
Adapter address = 74:27:EA:4F:3D:20
IP / MASK = 10.10.1.120/255.255.255.0
IP / MASK = 192.168.1.220/255.255.255.0
IP / MASK = 192.168.3.20/255.255.255.0
IP / MASK = 192.168.0.20/255.255.255.0
GateWay IP / MASK = 192.168.0.16/0.0.0.0
DHCP disable
----------------------
AdapterName:{D82D77BB-9FEE-42AF-9837-D33A66F219D9}
Description:VirtualBox Host-Only Ethernet Adapter - Virtual Machine Network Services Driver
Adapter address = 08:00:27:00:C0:50
IP / MASK = 192.168.56.1/255.255.255.0
GateWay IP / MASK = /
DHCP disable
================
Press Any Key >
-------------------------------------------------------------------------
Damion12
User
User
Posts: 81
Joined: Tue Oct 30, 2012 1:39 am

Re: LAN info - Windows only

Post by Damion12 »

SadStar wrote:if allow I will publish the test code by way of illustration of my approach
to parsing of result of the GetAdaptersInfo_ ()
Not to bash your work; but it failed to compile for me (5.50, 5.44 both x86 and x64)
Complained about the structure already being defined & peeks() using a a byte # for string...(ie: string[0])
Also didn't compile under unicode.

After changing (fixing)the errors, all I got for ip addresses on NIC display was 0.0.0.0

Code: Select all

AdapterName:{3B8EAE47-36DA-4289-9CEC-1B247EAC9A6D}
Description:Realtek PCIe FE Family Controller
Adapter address = 38:EA:A7:DA:5D:2D
IP / MASK = 0.0.0.0/0.0.0.0
GateWay IP / MASK = 0.0.0.0/255.255.255.255
DHCP : /
n>4!!!
SadStar
New User
New User
Posts: 4
Joined: Thu Nov 24, 2016 8:08 am

Re: LAN info - Windows only

Post by SadStar »

I suggest to try the next option
- Change the names of structures in order to eliminate the naming conflict

Code: Select all

Structure IP_ADDR_STRING_X
    NextAdapter.i
    IpAddress.a[16];IP_ADDRESS_STRING
    IpMask.a[16];IP_ADDRESS_STRING
    Context.i
EndStructure

Structure FIXED_INFO_X
   HostName.a[132]            ;MAX_HOSTNAME_LEN + 4
   DomainName.a[132]         ;MAX_DOMAIN_NAME_LEN + 4
   CurrentDnsServer.i
   DnsServerList.IP_ADDR_STRING_X
   NodeType.l
   ScopeId.a[260]             ;MAX_SCOPE_ID_LEN + 4
   EnableRouting.l
   EnableProxy.l
   EnableDns.l
EndStructure

Structure IP_ADAPTER_INFO_X
    NextAdapter.i
    ComboIndex.l
    AdapterName.a[260] ;MAX_ADAPTER_NAME_LENGTH + 4
    Description.a[132] ;MAX_ADAPTER_DESCRIPTION_LENGTH + 4
    AddressLength.l
    Address.a[8] ;MAX_ADAPTER_ADDRESS_LENGTH
    index.l
    Type.l
    DhcpEnabled.i
    CurrentIpAddress.i
    IpAddressList.IP_ADDR_STRING_X
    GatewayList.IP_ADDR_STRING_X
    DhcpServer.IP_ADDR_STRING_X
    HaveWINS.i
    PrimaryWinsServer.IP_ADDR_STRING_X
    SecondaryWinsServer.IP_ADDR_STRING_X
    LeaseObtained.i
    LeaseExpires.i
EndStructure

Procedure.s GetSysErrorText(ErrCode)
   Define result.s=""
   *Memory = AllocateMemory (255)
   length = FormatMessage_ (#FORMAT_MESSAGE_FROM_SYSTEM, #Null, ErrCode, 0, *Memory, 255, #Null)
   result=PeekS (*Memory, length - 2)
   FreeMemory (*Memory)
   ProcedureReturn result
EndProcedure

Procedure FatalError()
   Protected Result$, Line
   
   Result$="FatalError(): "
   Line = ErrorLine()
   If Line>=0
     Result$+" в строке "+Str(Line)+", файла: "+ErrorFile()
   EndIf
   
   Result$+" ќшибка типа: "+Chr(34)+ErrorMessage()+Chr(34)
   
   MessageRequester("‘атальна¤ ошибка выполнени¤", Result$, #PB_MessageRequester_Ok )
   End
EndProcedure

Procedure.s GetIPMask(*buff.IP_ADDR_STRING_X)
   ProcedureReturn PeekS(@*buff\IpAddress[0],16)+"/"+PeekS(@*buff\IpMask[0],16)
EndProcedure

OnErrorCall(@FatalError())

OpenConsole()

;- networks ----------------
*Net_Fixed_INFO_buffer=AllocateMemory(SizeOf(FIXED_INFO_X),#PB_Memory_NoClear)
If Not *Net_Fixed_INFO_buffer
   PrintN("the memory cannot be allocated")
   Goto Exit
EndIf
lBufferLength.l = MemorySize(*Net_Fixed_INFO_buffer)
lErrors = GetNetworkParams_(*Net_Fixed_INFO_buffer, @lBufferLength)
If lErrors = #ERROR_BUFFER_OVERFLOW
   *Net_Fixed_INFO_buffer=ReAllocateMemory(*Net_Fixed_INFO_buffer,lBufferLength,#PB_Memory_NoClear)
   lErrors = GetNetworkParams_(*Net_Fixed_INFO_buffer, @lBufferLength)
EndIf
If lErrors <> #ERROR_SUCCESS
   PrintN("GetNetworkParams() error")
   Select lErrors
      Case #ERROR_BUFFER_OVERFLOW
         PrintN( "#ERROR_BUFFER_OVERFLOW")
      Case #ERROR_INVALID_DATA
         PrintN( "#ERROR_INVALID_DATA")
      Case #ERROR_INVALID_PARAMETER
         PrintN( "#ERROR_INVALID_PARAMETER")
      Case #ERROR_NO_DATA
         PrintN( "#ERROR_NO_DATA")
      Case #ERROR_NOT_SUPPORTED
         PrintN( "#ERROR_NOT_SUPPORTED")
      Default
         PrintN( GetSysErrorText(lErrors))
   EndSelect
   FreeMemory(*Net_Fixed_INFO_buffer)
   Goto Exit
Else
   *Fixed_Info.FIXED_INFO_X=*Net_Fixed_INFO_buffer
   PrintN("HostName="+PeekS(@*Fixed_Info\HostName[0],132))
   PrintN("DomainName="+PeekS(@*Fixed_Info\DomainName[0],132))
   ; ------
   Define *CurrentIpAddress.IP_ADDR_STRING_X
   *CurrentIpAddress=@*Fixed_Info\DnsServerList
   Repeat
      PrintN("DnsServer IP / MASK = "+GetIPMask(*CurrentIpAddress))
      If *CurrentIpAddress\NextAdapter=0
         Break
      EndIf
      *CurrentIpAddress=*CurrentIpAddress\NextAdapter
   ForEver
   ; ------
   PrintN("ScopeId="+PeekS(@*Fixed_Info\ScopeId[0],260))
   ; -------------------------
   If *Fixed_Info\EnableProxy
      PrintN("local computer is acting as an ARP proxy")
   EndIf
   If *Fixed_Info\EnableRouting
      PrintN("routing is enabled on the local computer")
   EndIf
   If *Fixed_Info\EnableDns
      PrintN("DNS is enabled on the local computer")
   EndIf
EndIf

FreeMemory(*Net_Fixed_INFO_buffer)

;- adapters ----------------

*AdaptersInfoBuffer=AllocateMemory(SizeOf(IP_ADAPTER_INFO_X),#PB_Memory_NoClear)
If Not *AdaptersInfoBuffer
   PrintN("the memory cannot be allocated")
   Goto Exit
EndIf

   lBufferLength.l = MemorySize(*AdaptersInfoBuffer)
   lErrors = GetAdaptersInfo_(*AdaptersInfoBuffer, @lBufferLength)
   If lErrors = #ERROR_BUFFER_OVERFLOW
      *AdaptersInfoBuffer=ReAllocateMemory(*AdaptersInfoBuffer,lBufferLength,#PB_Memory_NoClear)
      lBufferLength = MemorySize(*AdaptersInfoBuffer)
      lErrors = GetAdaptersInfo_(*AdaptersInfoBuffer, @lBufferLength)
   EndIf
   
   If lErrors <> #ERROR_SUCCESS
      PrintN("GetAdaptersInfo() error")
      Select lErrors
         Case #ERROR_BUFFER_OVERFLOW
            PrintN( "#ERROR_BUFFER_OVERFLOW")
         Case #ERROR_INVALID_DATA
            PrintN( "#ERROR_INVALID_DATA")
         Case #ERROR_INVALID_PARAMETER
            PrintN( "#ERROR_INVALID_PARAMETER")
         Case #ERROR_NO_DATA
            PrintN( "#ERROR_NO_DATA")
         Case #ERROR_NOT_SUPPORTED
            PrintN( "#ERROR_NOT_SUPPORTED")
         Default
            PrintN( GetSysErrorText(lErrors))
      EndSelect
      Goto Exit
   Else
      Define *CurrentAdapterInfoBuffer.IP_ADAPTER_INFO_X
      *CurrentAdapterInfoBuffer=*AdaptersInfoBuffer
      n=0
      Repeat
         PrintN("----------------------")
         PrintN("AdapterName:"+PeekS(@*CurrentAdapterInfoBuffer\AdapterName[0],260))
         PrintN("Description:"+PeekS(@*CurrentAdapterInfoBuffer\Description[0],132))
         MAC$=""
         For i = 0 To *CurrentAdapterInfoBuffer\AddressLength-2
            MAC$ + RSet(Hex(*CurrentAdapterInfoBuffer\Address[i]&255),2,"0") + ":"
         Next
         MAC$ + RSet(Hex(*CurrentAdapterInfoBuffer\Address[i]&255),2,"0")
         PrintN("Adapter address = "+MAC$)
         ; IpAddressList -----------
         Define *CurrentIpAddress.IP_ADDR_STRING_X
         *CurrentIpAddress=@*CurrentAdapterInfoBuffer\IpAddressList
         IP$=""
         Repeat
            PrintN("IP / MASK = "+GetIPMask(*CurrentIpAddress))
            If *CurrentIpAddress\NextAdapter=0
               Break
            EndIf
            *CurrentIpAddress=*CurrentIpAddress\NextAdapter
         ForEver
         ; GatewayList -----------
         *CurrentIpAddress=@*CurrentAdapterInfoBuffer\GatewayList
         Repeat
            PrintN("GateWay IP / MASK = "+GetIPMask(*CurrentIpAddress))
            If *CurrentIpAddress\NextAdapter=0
               Break
            EndIf
            *CurrentIpAddress=*CurrentIpAddress\NextAdapter
         ForEver
         ; -------------------------
         If *CurrentAdapterInfoBuffer\DhcpEnabled
            PrintN("DHCP : "+GetIPMask(@*CurrentAdapterInfoBuffer\DhcpServer))
         Else
            PrintN("DHCP disable")
         EndIf
         ; -------------------------
         If *CurrentAdapterInfoBuffer\NextAdapter=0
            Break
         EndIf
         *CurrentAdapterInfoBuffer=*CurrentAdapterInfoBuffer\NextAdapter
         ; -------------------------
         n+1
         If n>4 ;debug trap
            PrintN("n>4!!!")
            Break
         EndIf
      ForEver
      
   EndIf


   Exit:
   FreeMemory(*AdaptersInfoBuffer)

   PrintN("================"+#CRLF$+"Press Any Key >")
   Repeat
      KeyPressed$ = Inkey()
      
      If KeyPressed$ <> ""
         Break
      EndIf
      Delay(20)
   Until KeyPressed$ = Chr(27)
I have checked this code for Win7(32) and Win10(64)
My compiler - PureBasic 5.40 LTS (Windows - x86)
EnableOnError
DisableDebugger

Result for Win10(64)

Code: Select all

HostName=Vlad
DomainName=zzzz.zz
DnsServer IP / MASK = 192.168.0.1/255.255.255.255
ScopeId=
----------------------
AdapterName:{145726CC-E25C-4908-B360-A33BA50EF8EC}
Description:Realtek PCIe GBE Family Controller
Adapter address = 90:2B:34:7C:6A:80
IP / MASK = 0.0.0.0/0.0.0.0
GateWay IP / MASK = 0.0.0.0/255.255.255.255
DHCP disable
----------------------
AdapterName:{53A3FA87-C6C0-45B5-83A6-4939FEF9812A}
Description:D-Link DGE-530T Gigabit Ethernet Adapter (rev.B)
Adapter address = 00:17:9A:06:07:E9
IP / MASK = 192.168.0.133/255.255.255.0
GateWay IP / MASK = 192.168.0.16/255.255.255.255
DHCP : 192.168.0.1/255.255.255.255
================
the first adapter - with the fixed IP address, without network cable
the second adapter - acting with the dynamic IP address
Damion12
User
User
Posts: 81
Joined: Tue Oct 30, 2012 1:39 am

Re: LAN info - Windows only

Post by Damion12 »

SadStar wrote:I suggest to try the next option
after fixing peeks() for unicode,

Code: Select all

HostName=mamoth2
DomainName=
DnsServer IP / MASK = 8.8.8.8/255.255.255.255
DnsServer IP / MASK = 8.8.4.4/255.255.255.255
ScopeId=
----------------------
AdapterName:{81659EC9-D7FC-47BD-9D71-853B9D2381ED}
Description:TeamViewer VPN Adapter
Adapter address = 00:FF:81:65:9E:C9
IP / MASK = 0.0.0.0/0.0.0.0
GateWay IP / MASK = 0.0.0.0/255.255.255.255
DHCP : /
----------------------
AdapterName:{72D44023-93DC-4372-B47D-57D86664212A}
Description:Microsoft Hosted Network Virtual Adapter
Adapter address = 42:16:D8:40:AE:FE
IP / MASK = 0.0.0.0/0.0.0.0
GateWay IP / MASK = 0.0.0.0/255.255.255.255
DHCP : /
----------------------
AdapterName:{25162047-569C-4B36-8204-22C10CCF6709}
Description:Microsoft Wi-Fi Direct Virtual Adapter
Adapter address = 12:16:D8:40:AE:FE
IP / MASK = 0.0.0.0/0.0.0.0
GateWay IP / MASK = 0.0.0.0/255.255.255.255
DHCP : /
----------------------
AdapterName:{10A84A06-830A-45C4-B8D7-3C9A563F8A63}
Description:VPN Client Adapter - VPN2
Adapter address = 00:AC:65:6F:8F:8F
IP / MASK = 0.0.0.0/0.0.0.0
GateWay IP / MASK = 0.0.0.0/255.255.255.255
DHCP : /
----------------------
AdapterName:{3B8EAE47-36DA-4289-9CEC-1B247EAC9A6D}
Description:Realtek PCIe FE Family Controller
Adapter address = 38:EA:A7:DA:5D:2D
IP / MASK = 0.0.0.0/0.0.0.0
GateWay IP / MASK = 0.0.0.0/255.255.255.255
DHCP : /
n>4!!!
================
Press Any Key >
Running in x86, ascii:

Code: Select all

HostName=mamoth2
DomainName=
DnsServer IP / MASK = 8.8.8.8/255.255.255.255
DnsServer IP / MASK = 8.8.4.4/255.255.255.255
ScopeId=
----------------------
AdapterName:{81659EC9-D7FC-47BD-9D71-853B9D2381ED}
Description:TeamViewer VPN Adapter
Adapter address = 00:FF:81:65:9E:C9
IP / MASK = 0.0.0.0/0.0.0.0
GateWay IP / MASK = 0.0.0.0/255.255.255.255
DHCP : /
----------------------
AdapterName:{72D44023-93DC-4372-B47D-57D86664212A}
Description:Microsoft Hosted Network Virtual Adapter
Adapter address = 42:16:D8:40:AE:FE
IP / MASK = 0.0.0.0/0.0.0.0
GateWay IP / MASK = 0.0.0.0/255.255.255.255
DHCP : /
----------------------
AdapterName:{25162047-569C-4B36-8204-22C10CCF6709}
Description:Microsoft Wi-Fi Direct Virtual Adapter
Adapter address = 12:16:D8:40:AE:FE
IP / MASK = 0.0.0.0/0.0.0.0
GateWay IP / MASK = 0.0.0.0/255.255.255.255
DHCP : /
----------------------
AdapterName:{10A84A06-830A-45C4-B8D7-3C9A563F8A63}
Description:VPN Client Adapter - VPN2
Adapter address = 00:AC:65:6F:8F:8F
IP / MASK = 0.0.0.0/0.0.0.0
GateWay IP / MASK = 0.0.0.0/255.255.255.255
DHCP : /
----------------------
AdapterName:{3B8EAE47-36DA-4289-9CEC-1B247EAC9A6D}
Description:Realtek PCIe FE Family Controller
Adapter address = 38:EA:A7:DA:5D:2D
IP / MASK = 0.0.0.0/0.0.0.0
GateWay IP / MASK = 0.0.0.0/255.255.255.255
DHCP : /
n>4!!!
================
Press Any Key >
SadStar
New User
New User
Posts: 4
Joined: Thu Nov 24, 2016 8:08 am

Re: LAN info - Windows only

Post by SadStar »

after fixing peeks() for unicode,
why unicode?
where unicode?

-----------------------------
https://msdn.microsoft.com/en-us/librar ... s.85).aspx

AdapterName
Type: char[MAX_ADAPTER_NAME_LENGTH + 4]
An ANSI character string of the name of the adapter.

Description
Type: char[MAX_ADAPTER_DESCRIPTION_LENGTH + 4]
An ANSI character string that contains the description of the adapter.
-------------------------
the result of the GetAdaptersInfo_() function has no unicode.

I didn't use unicode
but I have checked the following option
- I have changed all PeekS (....., #PB_Ascii)
- I have compiled in the mode "create unicode the application"
result - Ok

Or I have misunderstood you?

Please, Send your the last a code to me : sadstar3 @ Gmail. com
Not to litter a forum

__________________________________________________
URL tags added
09.12.2016
RSBasic
User avatar
doctorized
Addict
Addict
Posts: 856
Joined: Fri Mar 27, 2009 9:41 am
Location: Athens, Greece

Re: LAN info - Windows only

Post by doctorized »

SadStar wrote:
after fixing peeks() for unicode,
why unicode?
where unicode?
Unicode is everywhere, even in PB. That's why I use #PB_Ascii to see it as a simple ansi string and not unicode. PB now supports only Unicode. Also if the Description has non-english chars, like in my case, then unicode is used by the API to send me the correct name in my language.

In my case, with PB 5.30 x64 the code works fine. No error. The conflict with the structure's name occurs as PB 5.30 x64 that I use is not supporting IP_ADDR_STRING, as 5.50 does. So, I use it in order to support both versions.
Post Reply