Eng-Tips is the largest engineering community on the Internet

Intelligent Work Forums for Engineering Professionals

  • Congratulations waross on being selected by the Eng-Tips community for having the most helpful posts in the forums last week. Way to Go!

Choose in wich computers a macro should run.

Status
Not open for further replies.

efighettib

Structural
Jan 13, 2004
26
CL
Hello

I think that this tip may be helpfull. If you want to authorize certain computers that can run an excel spreadsheet, you should do the following.

In a module,

Public Declare Function GetVolumeSerialNumber Lib "kernel32" Alias "GetVolumeInformationA" (ByVal lpRootPathName As String, ByVal lpVolumeNameBuffer As Long, ByVal nVolumeNameSize As Long, lpVolumeSerialNumber As Long, ByVal lpMaximumComponentLength As Long, ByVal lpFileSystemFlags As Long, ByVal lpFileSystemNameBuffer As Long, ByVal nFileSystemNameSize As Long) As Long

Public Function VolumeSerial(DriveLetter) As Long
Dim Serial As Long
Call GetVolumeSerialNumber(UCase(DriveLetter) & ":\", 0&, 0&, Serial, 0&, 0&, 0&, 0&)
VolumeSerial = Serial
End Function

this code will return the selected volume serial number, wich is unique.

Then,


Sub Auto_Open()

C1 = VolumeSerial("C")

if C1<>your serial thenActiveWorkbook.Close

end sub

Off course you can add more serials to run the spreadsheet.

Hope this helps.

Enzo.

 
Any ideas on how to expand this to;
-access the internet and store serial# on a server
-receive an authorization code from the server
 
What happens if they chose to not enable macros? Also, can they open the worksheet manually (Format->Sheet->Unhide)?
 
Melone. The only way I have found to "force" users to enable macros is to make sure that a vital (and difficult) part of the spreadsheet's capability is carried out by macros. Then if the user chooses not to enable macros various vital cells in the results section of the spreadsheet will fill up with lovely #NAME? or #VALUE! Works like a charm.

CTruax. I think I can guess what you are trying to do, and I cannot help you directly. But it might help you if I explained how I solved a similar problem. I have highly specialised spreadsheet, that is likely to be used by no more than a dozen people in the firm. It contains some extremely proprietary stuff, so the spreadsheet needs to be as thief-proof as possible. For no particular reason, I chose not to use the computer's volume serial number as the key identification (as per efighettib's approach above), preferring to use the MAC address. I also wanted to implement an "expiry date", to make life a bit more difficult for my notional thief.

However I was worried that if I had a valid user who was in the middle of developing an extremely elaborate model when the spreadsheet expired, he would not thank me when I sent him a new (empty of data) version with an extended expiry date. So I put the two checks (the one to ensure that the user's MAC address was on a hard-coded list of authorised addresses, and the one to ensure that the expiry date had not passed) in an add-in rather than in the actual main spreadsheet. The spreadsheet contains VBA code that invokes the add-in to perform the checks.

When a new user comes along, I add his MAC address to the list in the add-in. So the list grows, and is always complete. I then send him both the main spreadsheet and the expanded add-in. When the expiry date needs to be extended, I change the add-in accordingly and send it out to all users.

This is all far from perfect, and far from bullet proof. But it is the best I have been able to come up with so far. Suggestions welcomed.
 
On auto-open macros: you can disable just the auto-open macro by holding Shift while the workbook opens, and keep the other code working. So I suggest that you check the authorization also inside your main code (and maybe a couple of times in different parts).

Cheers,
Joerd

Please see FAQ731-376 for tips on how to make the best use of Eng-Tips.
 
First of all, I want to thanks the comments and suggestions you made in this topic.

What I did to protect my spreadsheet is not to include formulas on it. It that case, you will not see the #NAME? or #VALUE! ceels results. Every result will be computed by a macro, which is going to be included in the sub

Private Sub Worksheet_Change(ByVal Target As Range)
...
End Sub

In this code, you should include conditions so that if the information supplied by the user is enough, then the macro will calculate the result.

In this way, you can have a clean solution if the user doesn't want to execute macros. Another solution is to create the hole spreadsheet in a macro, including text and format cells.


Denial: Do you know the function that can get the MAC address?
 
To obtain the MAC address;
From Windows ME, 98, 95:
START-RUN type; WINIPCFG
The Adapter address is the MAC
From Windows XP,2000,NT:
START-CMD command prompt type; IPCONFIG /ALL
The Physical address listed is the MAC
From MAC-X
AppleMenu-SystemPreferences-Network-BuiltInEthernet-TCP/IP
The Ethernet Address is the MAC
From LINUX:
ifconfig -a
From Visual Basic:
Code:
'Add the following namespaces
Imports System
Imports System.Runtime.InteropServices
Imports System.Text
Imports System.Threading
Imports Microsoft.VisualBasic.Constants
Imports Microsoft.VisualBasic.Conversion

'Constants used in the program as defined in IPExport.h and WinError.h
Public Class IPConfigConst
Public Const MAX_ADAPTER_NAME As Integer = 128
Public Const MAX_HOSTNAME_LEN As Integer = 128
Public Const MAX_DOMAIN_NAME_LEN As Integer = 128
Public Const MAX_SCOPE_ID_LEN As Integer = 256
Public Const MAX_ADAPTER_DESCRIPTION_LENGTH As Integer = 128
Public Const MAX_ADAPTER_NAME_LENGTH As Integer = 256
Public Const MAX_ADAPTER_ADDRESS_LENGTH As Integer = 8
Public Const DEFAULT_MINIMUM_ENTITIES As Integer = 32

Public Const ERROR_BUFFER_OVERFLOW As Integer = 111
Public Const ERROR_SUCCESS As Integer = 0
End Class

'Different Adapter types as defined in IPifcons.h
Public Class IPAdapterTypes
Public Const MIB_IF_TYPE_OTHER As Integer = 1
Public Const MIB_IF_TYPE_ETHERNET As Integer = 6
Public Const MIB_IF_TYPE_TOKENRING As Integer = 9
Public Const MIB_IF_TYPE_FDDI As Integer = 15
Public Const MIB_IF_TYPE_PPP As Integer = 23
Public Const MIB_IF_TYPE_LOOPBACK As Integer = 24
Public Const MIB_IF_TYPE_SLIP As Integer = 28
End Class

'typedef struct _IP_ADAPTER_INFO
'{
'    struct _IP_ADAPTER_INFO* Next;
'    DWORD ComboIndex;
'    char AdapterName[MAX_ADAPTER_NAME_LENGTH + 4];
'    char Description[MAX_ADAPTER_DESCRIPTION_LENGTH + 4];
'    UINT AddressLength;
'    BYTE Address[MAX_ADAPTER_ADDRESS_LENGTH];
'    DWORD Index;
'    UINT Type;
'    UINT DhcpEnabled;
'    PIP_ADDR_STRING CurrentIpAddress;
'    IP_ADDR_STRING IpAddressList;
'    IP_ADDR_STRING GatewayList;
'    IP_ADDR_STRING DhcpServer;
'    BOOL HaveWins;
'    IP_ADDR_STRING PrimaryWinsServer;
'    IP_ADDR_STRING SecondaryWinsServer;
'    time_t LeaseObtained;
'    time_t LeaseExpires;
'}

'declared as structure
<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Ansi)> _
Public Structure IPAdapterInfo

Public NextPointer As IntPtr
Public ComboIndex As Integer

<MarshalAs(UnmanagedType.ByValTStr, _
SizeConst:=IPConfigConst.MAX_ADAPTER_NAME_LENGTH + 4)> _
Public AdapterName As String

<MarshalAs(UnmanagedType.ByValTStr, _
SizeConst:=IPConfigConst.MAX_ADAPTER_DESCRIPTION_LENGTH + 4)> _
Public Description As String

Public AddressLength As Integer

<MarshalAs(UnmanagedType.ByValArray, _
SizeConst:=IPConfigConst.MAX_ADAPTER_ADDRESS_LENGTH)> _
Public Address() As Byte

Public Index As Integer
Public Type As Integer
Public DhcpEnabled As Integer
Public CurrentIPAddress As IntPtr
Public IPAddressList As IPAddrString
Public GatewayList As IPAddrString
Public DhcpServer As IPAddrString
Public HaveWins As Boolean
Public PrimaryWinsServer As IPAddrString
Public SecondaryWinsServer As IPAddrString
Public LeaseObtained As Integer
Public LeaseExpires As Integer
End Structure

'typedef struct _IP_ADDR_STRING
'{
'    struct _IP_ADDR_STRING* Next;
'    IP_ADDRESS_STRING IpAddress;
'    IP_MASK_STRING IpMask;
'    DWORD Context;
'}

'declared as structure
<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Ansi)> _
Public Structure IPAddrString

Public NextPointer As IntPtr

<MarshalAs(UnmanagedType.ByValTStr, SizeConst:=4 * 4)> _
Public IPAddressString As String

<MarshalAs(UnmanagedType.ByValTStr, SizeConst:=4 * 4)> _
Public IPMaskString As String

Public Context As Integer
End Structure

'typedef struct _IP_ADAPTER_INDEX_MAP
'{
'    ULONG Index // adapter index
'    WCHAR Name [MAX_ADAPTER_NAME]; // name of the adapter
'}

'declared as structure
<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Auto)> _
Public Structure IPAdapterIndexMap

Public Index As Integer

<MarshalAs(UnmanagedType.ByValTStr, _
SizeConst:=IPConfigConst.MAX_ADAPTER_NAME)> _
Public Name As String
End Structure

'typedef struct _IP_INTERFACE_INFO
'{
'    LONG NumAdapters; // number of adapters in array
'    IP_ADAPTER_INDEX_MAP Adapter[1]; // adapter indices and names
'}

'declared as structure
<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Auto)> _
Public Structure IPInterfaceInfo

Public NumAdapters As Integer
Public Adapter As IPAdapterIndexMap
End Structure

'typedef struct
'{
'    char HostName[MAX_HOSTNAME_LEN + 4] ;
'    char DomainName[MAX_DOMAIN_NAME_LEN + 4];
'    PIP_ADDR_STRING CurrentDnsServer;
'    IP_ADDR_STRING DnsServerList;
'    UINT NodeType;
'    char ScopeId[MAX_SCOPE_ID_LEN + 4];
'    UINT EnableRouting;
'    UINT EnableProxy;
'    UINT EnableDns;
'}

'declared as class
<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Ansi)> _
Public Class FixedInfo

<MarshalAs(UnmanagedType.ByValTStr, _
SizeConst:=IPConfigConst.MAX_HOSTNAME_LEN + 4)> _
Public HostName As String

<MarshalAs(UnmanagedType.ByValTStr, _
SizeConst:=IPConfigConst.MAX_DOMAIN_NAME_LEN + 4)> _
Public DomainName As String

Public CurrentServerList As IntPtr
Public DnsServerList As IPAddrString
Public NodeType As Integer

<MarshalAs(UnmanagedType.ByValTStr, _
SizeConst:=IPConfigConst.MAX_SCOPE_ID_LEN + 4)> _
Public ScopeId As String

Public EnableRouting As Integer
Public EnableProxy As Integer
Public EnableDns As Integer
End Class

'LibWrap is a class which contains invokation of the Win32 API's using
DllImport
Public Class LibWrap

'DWORD GetNetworkParams(PFIXED_INFO pFixedInfo,PULONG pOutBufLen);
Declare Auto Function GetNetworkParams Lib "Iphlpapi.dll" _
(ByVal PFixedInfoBuffer As Byte(), ByRef size As Integer) As Integer

'DWORD GetAdaptersInfo(PIP_ADAPTER_INFO pAdapterInfo,PULONG pOutBufLen);
Declare Auto Function GetAdaptersInfo Lib "Iphlpapi.dll" _
(ByVal PAdapterInfoBuffer As Byte(), ByRef size As Integer) As Integer

'DWORD GetInterfaceInfo(PIP_INTERFACE_INFO pIfTable, PULONG
dwOutBufLen);
Declare Auto Function GetInterfaceInfo Lib "Iphlpapi.dll" _
(ByVal PIfTableBuffer As Byte(), ByRef size As Integer) As Integer

'copymemory function has many declarations depending on the type of
parameters
'VOID CopyMemory(PVOID Destination, CONST VOID* Source,
'SIZE_T Length);

'copying from Byte[] to FixedInfo class. Passes the class as In/Out
Parameter
Declare Auto Sub CopyMemoryFixedInfo Lib "Kernel32.dll" Alias
"CopyMemory" _
(<Out()> ByVal dest As FixedInfo, _
ByVal source As Byte(), ByVal size As Integer)

'copying from IntPtr to IPAddrString structure
Declare Auto Sub CopyMemoryIPAddrString Lib "Kernel32.dll" Alias
"CopyMemory" _
(ByRef dest As IPAddrString, ByVal source As IntPtr, ByVal size As
Integer)

'copying from Byte[] to IPAdapterInfo structure
Declare Auto Sub CopyMemoryIPAdapterInfo Lib "Kernel32.dll" Alias
"CopyMemory" _
(ByRef dest As IPAdapterInfo, ByVal source As Byte(), ByVal
size As Integer)

'copying from IntPtr to IPAdapterInfo structure
Declare Auto Sub CopyMemoryIPAdapterInfoP Lib "Kernel32.dll" Alias
"CopyMemory" _
(ByRef dest As IPAdapterInfo, ByVal source As IntPtr, ByVal size As
Integer)

'copying from byte to int variable
Declare Auto Sub CopyMemoryInt Lib "Kernel32.dll" Alias "CopyMemory" _
(ByRef dest As Integer, ByRef source As Byte, ByVal size As Integer)

'copying from byte to IPAdapterIndexMap structure
Declare Auto Sub CopyMemoryIPAdapterIndexMap Lib "Kernel32.dll" Alias
"CopyMemory" _
(ByRef dest As IPAdapterIndexMap, ByRef source As Byte, ByVal size
As Integer)

'DWORD IpReleaseAddress(PIP_ADAPTER_INDEX_MAP AdapterInfo)
Declare Auto Function IpReleaseAddress Lib "Iphlpapi.dll" _
(ByRef AdapterInfo As IPAdapterIndexMap) As Integer

'DWORD IpRenewAddress(PIP_ADAPTER_INDEX_MAP AdapterInfo)
Declare Auto Function IpRenewAddress Lib "Iphlpapi.dll" _
(ByRef AdapterInfo As IPAdapterIndexMap) As Integer

End Class

Public Class App

'define usage of the program
Public Shared Sub usage()
Console.WriteLine("Usage: Iprenew [ -l ] [ -r<index id> ] [
-n<index id>]")
Console.WriteLine(vbTab & "-l List adapters with corresponding
index ID and other information")
Console.WriteLine(vbTab & "-r Release IP address for adapter index
ID")
Console.WriteLine(vbTab & "-n Renew IP address for adapter index
ID")
End Sub

Public Shared Sub Main(ByVal args() As String)

'used while invoking win32 API's
Dim retValue As Integer
Dim size As Integer

'for command line arguments
Dim optList As Boolean = False
Dim optRelease As Boolean = False
Dim optRenew As Boolean = False
Dim temp As String

'to check if adapter is of type Ethernet Adapter
Dim ifEthernet As Boolean = False

'index for which address is released or renewed
Dim index As Integer = 0

'local variable
Dim i As Integer

If args.Length = 0 Then
usage()
Return
End If

'checking for command line arguments    
For i = 0 To args.Length - 1
If ((args(i).Chars(0) = "-") Or (args(i).Chars(0) = "/")) Then

Select Case args(i).Chars(1)
Case "l"
'to list all adapter information
optList = True

Case "r"
'to release IP address for given index
optRelease = True
If (args(i).Length >= 2) Then
temp = args(i).Substring(2, args(i).Length - 2)
index = Int32.Parse(temp)
Else
usage()
End If

Case "n"
'to renew IP address for given index
optRenew = True
If (args(i).Length >= 2) Then
temp = args(i).Substring(2, args(i).Length - 2)
index = Int32.Parse(temp)
Else
usage()
End If

Case Else
usage()
Return
End Select

End If
Next i

If (optRelease Or optRenew) Then
Console.WriteLine("Given Adapter Index : " & index)
End If

'print all the network adapter information
If (optList) Then

'since Byte[] is class, we can pass Nothing as parameter
'to get the required buffer size
retValue = LibWrap.GetNetworkParams(Nothing, size)

'checking for error
If (retValue <> IPConfigConst.ERROR_SUCCESS And _
retValue <> IPConfigConst.ERROR_BUFFER_OVERFLOW) Then
Console.WriteLine("Error invoking GetNetworkParams() : " +
retValue)
Return
End If

'creating a buffer with required size
Dim PFixedInfoBuffer(size) As Byte

'Invoking GetNetworkParams()
retValue = LibWrap.GetNetworkParams(PFixedInfoBuffer, size)

If (retValue <> IPConfigConst.ERROR_SUCCESS) Then
Console.WriteLine("Error invoking GetNetworkParams() " +
retValue)
Return
End If

Dim PFixedInfo As New FixedInfo()

'copy from the Buffer to the FIXED_INFO structure
LibWrap.CopyMemoryFixedInfo(PFixedInfo, PFixedInfoBuffer, _
Marshal.SizeOf(PFixedInfo))

Console.WriteLine("Windows IP Configuration:")
Console.WriteLine()
Console.WriteLine(vbTab & vbTab & "HostName....................
: " + _
PFixedInfo.HostName)
Console.WriteLine(vbTab & vbTab & "DomainName..................
: " + _
PFixedInfo.DomainName)

Dim List As New IPAddrString()
Dim ListNext As New IntPtr()

'Linked list of IP_ADDR_STRING structures that
'specify the set of DNS servers used by the local computer.
Console.Write(vbTab & vbTab & "DnsServerList............... : ")
Console.WriteLine(PFixedInfo.DnsServerList.IPAddressString)
ListNext = PFixedInfo.DnsServerList.NextPointer
While (ListNext.ToInt32() <> 0)
LibWrap.CopyMemoryIPAddrString(List, ListNext,
Marshal.SizeOf(List))
Console.WriteLine(vbTab & vbTab & _
vbTab & vbTab & vbTab & _
vbTab & List.IPAddressString)
ListNext = List.NextPointer
End While
Select Case (PFixedInfo.NodeType)

Case 1
Console.WriteLine(vbTab & vbTab & "Node
Type................... : Broadcast")
Case 2
Console.WriteLine(vbTab & vbTab & "Node
Type................... : Peer to Peer")
Case 4
Console.WriteLine(vbTab & vbTab & "Node
Type................... : Mixed")
Case 8
Console.WriteLine(vbTab & vbTab & "Node
Type................... : Hybrid")
Case Else
Console.WriteLine(vbTab & vbTab & "Node
Type................... : Unknown")
End Select

If (PFixedInfo.EnableRouting <> 0) Then
Console.WriteLine(vbTab & vbTab & "IP Routing
Enabled.......... : Yes")
Else
Console.WriteLine(vbTab & vbTab & "IP Routing
enabled.......... : No")
End If

If (PFixedInfo.EnableProxy <> 0) Then
Console.WriteLine(vbTab & vbTab & "WINS Proxy
Enabled.......... : Yes")
Else
Console.WriteLine(vbTab & vbTab & "WINS Proxy not
enabled...... : No")
End If

If (PFixedInfo.EnableDns <> 0) Then
Console.WriteLine(vbTab & vbTab & "NetBIOS Resolution Uses
DNS : Yes")
Else
Console.WriteLine(vbTab & vbTab & "NetBIOS Resolution Uses
DNS : No")
End If
Console.WriteLine()
Console.WriteLine()

're-intializing the size
size = 0

'since Byte[] is class, we can pass null as parameter
'to get the required buffer size
retValue = LibWrap.GetAdaptersInfo(Nothing, size)

'checking for error
If (retValue <> IPConfigConst.ERROR_SUCCESS And _
retValue <> IPConfigConst.ERROR_BUFFER_OVERFLOW) Then
Console.WriteLine("Error invoking GetAdaptersInfo() : " +
retValue)
Return
End If

Dim IPAdapterInfoBuffer(size) As Byte
Dim PAdapterInfo As New IPAdapterInfo()

'Invoking GetAdapterInfo()
retValue = LibWrap.GetAdaptersInfo(IPAdapterInfoBuffer, size)

'checking for error
If (retValue <> IPConfigConst.ERROR_SUCCESS) Then
Console.WriteLine("Error invoking GetAdaptersInfo() : " +
retValue)
Return
End If

'copy from the Buffer to the IP_ADAPTER_INFO structure
LibWrap.CopyMemoryIPAdapterInfo(PAdapterInfo,
IPAdapterInfoBuffer, _
Marshal.SizeOf(PAdapterInfo))

'pointing next block for IP_ADAPTER_INFO
Dim AdapterInfoNext As New IntPtr()

Do
Select Case PAdapterInfo.Type
Case IPAdapterTypes.MIB_IF_TYPE_ETHERNET
Console.Write("Ethernet adapter ")
ifEthernet = True

Case IPAdapterTypes.MIB_IF_TYPE_TOKENRING
Console.Write("Token Ring adapter ")

Case IPAdapterTypes.MIB_IF_TYPE_FDDI
Console.Write("FDDI adapter ")

Case IPAdapterTypes.MIB_IF_TYPE_PPP
Console.Write("PPP adapter ")

Case IPAdapterTypes.MIB_IF_TYPE_LOOPBACK
Console.Write("Loopback adapter ")

Case IPAdapterTypes.MIB_IF_TYPE_SLIP
Console.Write("Slip adapter ")

Case IPAdapterTypes.MIB_IF_TYPE_OTHER
Console.Write("Other type of adapter")

Case Else
Console.Write("Other adapter ")
End Select
Console.WriteLine(PAdapterInfo.AdapterName & vbCr)
Console.WriteLine(vbTab & vbTab & "Adapter
Index............... : " + _
PAdapterInfo.Index.ToString())
Console.WriteLine(vbTab & vbTab &
"Description................. : " + _
PAdapterInfo.Description)
Console.Write(vbTab & vbTab & "Physical Address............
: ")

Dim l As Integer
For l = 0 To PAdapterInfo.AddressLength - 1
If (l = PAdapterInfo.AddressLength - 1) Then
Console.WriteLine(Hex(PAdapterInfo.Address(l)))
Else
Console.Write(Hex(PAdapterInfo.Address(l)) + "-")
End If
Next l

If (PAdapterInfo.DhcpEnabled <> 0) Then
Console.WriteLine(vbTab & vbTab & "DHCP
Enabled................ : Yes")
Else
Console.WriteLine(vbTab & vbTab & "DHCP
Enabled................ : No")
End If

'IP Address list
Console.WriteLine(vbTab & vbTab & "IP
Address.................. : " + _
PAdapterInfo.IPAddressList.IPAddressString)
Console.WriteLine(vbTab & vbTab & "Subnet
Mask................. : " + _
PAdapterInfo.IPAddressList.IPMaskString)
Dim PIPList As New IntPtr()
PIPList = PAdapterInfo.IPAddressList.NextPointer
Dim IPAddressList As New IPAddrString()
While (PIPList.ToInt32() <> 0)
LibWrap.CopyMemoryIPAddrString(IPAddressList, PIPList, _
Marshal.SizeOf(IPAddressList))
Console.WriteLine(vbTab & vbTab & "IP
Address.................. : " _
+ IPAddressList.IPAddressString)
Console.WriteLine(vbTab & vbTab & "Subnet
Mask................. : " _
+ IPAddressList.IPMaskString)
PIPList = IPAddressList.NextPointer
End While

'Gateway List                    
Console.WriteLine(vbTab & vbTab & " Default
Gateway............. : " + PAdapterInfo.GatewayList.IPAddressString)
Dim PGateway As New IntPtr()
PGateway = PAdapterInfo.GatewayList.NextPointer
Dim IPGatewayList As New IPAddrString()
While (PGateway.ToInt32 <> 0)
LibWrap.CopyMemoryIPAddrString(IPGatewayList, PGateway,
Marshal.SizeOf(IPGatewayList))
Console.WriteLine(vbTab & vbTab & "Gateway
Address............. : " + IPGatewayList.IPAddressString)
PGateway = IPGatewayList.NextPointer
End While

Console.WriteLine(vbTab & vbTab & "DHCP
Server................. : " + PAdapterInfo.DhcpServer.IPAddressString)
Console.WriteLine(vbTab & vbTab & "Primary WINS
Server......... : " + PAdapterInfo.PrimaryWinsServer.IPAddressString)
Console.WriteLine(vbTab & vbTab & "Gateway
Address............. : " + PAdapterInfo.SecondaryWinsServer.IPAddressString)

'date and time when Lease is obtained and expired
If (ifEthernet) Then

Dim LeaseObt = New DateTime(1970, 1, 1)
Dim LeaseExp = New DateTime(1970, 1, 1)
LeaseObt =
LeaseObt.AddSeconds(PAdapterInfo.LeaseObtained)
LeaseExp =
LeaseExp.AddSeconds(PAdapterInfo.LeaseExpires)

Console.WriteLine(vbTab & vbTab & "Lease
Obtained.............. : " + LeaseObt.ToString())
Console.WriteLine(vbTab & vbTab & "Lease
Expires............... : " + LeaseExp.ToString())
End If

'setting it to next Adapter information
AdapterInfoNext = PAdapterInfo.NextPointer

If (AdapterInfoNext.ToInt32 <> 0) Then
LibWrap.CopyMemoryIPAdapterInfoP(PAdapterInfo,
AdapterInfoNext, Marshal.SizeOf(PAdapterInfo))
End If
Console.WriteLine()
Console.WriteLine()

Loop While (AdapterInfoNext.ToInt32 <> 0)
'Depending on the number of adapters
End If

'Re-initializing the size
size = 0

'if IP Release or Renew
If (optRelease Or optRenew) Then

'since Byte[] is class, we can pass null as parameter
'to get the required buffer size
LibWrap.GetInterfaceInfo(Nothing, size)

'Checking for error
If (retValue <> IPConfigConst.ERROR_SUCCESS And _
retValue <> IPConfigConst.ERROR_BUFFER_OVERFLOW) Then
Console.WriteLine("Error invoking GetInterfaceInfo() : " +
retValue)
Return
End If

Dim PIfTableBuffer(size) As Byte
Dim PIfTable As New IPInterfaceInfo()

'invoking GetInterfaceInfo()
retValue = LibWrap.GetInterfaceInfo(PIfTableBuffer, size)

'checking for error
If (retValue <> IPConfigConst.ERROR_SUCCESS) Then
Console.WriteLine("Error Value from GetInterfaceInfo(): " +
retValue)
Return
End If

Dim NumAdapters As Integer = 0
Dim byteCount As Integer = 0

'copy from PIfTableBuffer to NumAdapters
LibWrap.CopyMemoryInt(NumAdapters, PIfTableBuffer(byteCount), 4)

byteCount = byteCount + 4

If (NumAdapters = 0) Then
Console.WriteLine("No Adpaters found")
Return
End If

Dim PIPAdapterIndexMap As New IPAdapterIndexMap()

For i = 0 To NumAdapters - 1
'copy from PIfTableBuffer to IP_ADAPTER_INDEX_MAP Structure
LibWrap.CopyMemoryIPAdapterIndexMap(PIPAdapterIndexMap,
PIfTableBuffer(byteCount), Marshal.SizeOf(PIPAdapterIndexMap))
byteCount = byteCount + Marshal.SizeOf(PIPAdapterIndexMap)

'checking for index number
If (index = PIPAdapterIndexMap.Index) Then

'if IP Release
If (optRelease) Then

retValue =
LibWrap.IpReleaseAddress(PIPAdapterIndexMap)
If (retValue <> IPConfigConst.ERROR_SUCCESS) Then
Console.WriteLine("Error invoking IPRelease: "
& retValue)
Return
End If

Console.WriteLine("IP Address Released....")
End If

'if IP Renew
If (optRenew) Then

retValue =
LibWrap.IpRenewAddress(PIPAdapterIndexMap)
If (retValue <> IPConfigConst.ERROR_SUCCESS) Then
Console.WriteLine("Error invoking IPRenew: " &
retValue)
Return
End If

Console.WriteLine("IP Address Renewed....")
End If
End If

Next i
End If

End Sub

End Class
'Use the following syntax to get the result
'  <name of the exe>.exe -l
 
Efighettib,

The code I use is attached. I grabbed it off the internet some time ago, and (contrary to my usual practice) did not record the source at the time. Probably (unfortunately uncontrary to my usual practice) I would have tinkered with it slightly.

I have a feeling I concluded that it was not all that robust, but I use it because it works on all the computers in my employer's firm. Ctruax's code looks to be much more comprehensive, so maybe it is more universally applicable.

So, FWIW:
Code:
Public Function GetMACAddress()
'
'  Returns the (first) MAC address for the computer.
'  Uses "-" as its presentation delimiter.
'
Dim Net As Object
Dim SH As Object
Dim FSO As Object
Dim TS As Object
Dim Data As String
Dim MACAddress As String
'
On Error GoTo ErrorHandler
'
Set Net = CreateObject("wscript.network")
'
Set SH = CreateObject("wscript.shell")
SH.Run "%comspec% /c nbtstat -a " _
    & Net.computername & " > c:\nbtstat.txt", 0, True
Set SH = Nothing
Set Net = Nothing
'
Set FSO = CreateObject("scripting.filesystemobject")
Set TS = FSO.opentextfile("c:\nbtstat.txt")
MACAddress = ""
Do While Not TS.AtEndOfStream
    Data = UCase(Trim(TS.readline))
    If InStr(Data, "MAC ADDRESS") Then
        MACAddress = Right(WorksheetFunction.Clean(Data), 17)
        Exit Do
    End If
Loop
'
TS.Close
Set TS = Nothing
FSO.deletefile "c:\nbtstat.txt"
Set FSO = Nothing
'
If Len(MACAddress) < 2 Then GoTo ErrorHandler
GetMACAddress = MACAddress
Exit Function
'
ErrorHandler:
GetMACAddress = "Error in GetMACAddress function"
End Function
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top