Главная страница
    Top.Mail.Ru    Яндекс.Метрика
Форум: "Сети";
Текущий архив: 2007.04.15;
Скачать: [xml.tar.bz2];

Вниз

MAC-адрес   Найти похожие ветки 

 
apic ©   (2006-08-15 17:30) [0]

Как узнать MAC-адрес сетевухи, программно разумеется...
Заранее СПАСИБО!!!


 
Отец Кондратий   (2006-08-16 06:14) [1]

Без проблем. Есть несколько возможных реализаций. Вот одна, может не самая лучшая, но позволяет узнать всё про все адаптеры:


uses Windows, IpHlpAPI, WinSock2, IpRtrMib, Iptypes, IpIfConst;
...
type
// Структуры для выполнения GetAdaptersInfo
 IP_ADDRESS_STRING = record
   S: array [0..15] of Char;
end;

 IP_MASK_STRING = IP_ADDRESS_STRING;
 PIP_MASK_STRING = ^IP_MASK_STRING;

 PIP_ADDR_STRING = ^IP_ADDR_STRING;
 IP_ADDR_STRING = record
   Next: PIP_ADDR_STRING;             // Pointer to the next IP_ADDR_STRING structure in the list.
   IpAddress: IP_ADDRESS_STRING;      // Specifies a structure type with a single member, String.
                                      // The String member is a char array of size 16. This array holds the IP address.
   IpMask: IP_MASK_STRING;            // Specifies a structure type with a single member, String.
                                      //The String member is a char array of size 16. This array holds
                                      //the IP address mask.
   Context: DWORD;                    // Network table entry (NTE). This value corresponds to the NTEContext
                                      //parameters in the AddIPAddress and DeleteIPAddress functions.
end;
...
type
PIP_ADAPTER_INFO = ^IP_ADAPTER_INFO;
 IP_ADAPTER_INFO = record
   Next: PIP_ADAPTER_INFO;                //Pointer to the next adapter in the list of adapters.
   ComboIndex: DWORD;                     //Reserved.
   AdapterName: array [0..MAX_ADAPTER_NAME_LENGTH + 3] of Char;        //Name of the adapter.
   Description: array [0..MAX_ADAPTER_DESCRIPTION_LENGTH + 3] of Char; //Description for the adapter.
   AddressLength: UINT;                   //Length of the hardware address for the adapter.
   Address: array [0..MAX_ADAPTER_ADDRESS_LENGTH - 1] of BYTE;         //Hardware address for the adapter.
   Index: DWORD;                          // Adapter index. The adapter index may change when an adapter is
                                          //disabled and then enabled, or under other circumstances,
                                          //and should not be considered persistent.

   Type_: UINT;                           // Adapter type. The type must be of the following values:
                                          // MIB_IF_TYPE_OTHER
                                          // MIB_IF_TYPE_ETHERNET
                                          // MIB_IF_TYPE_TOKENRING
                                          // MIB_IF_TYPE_FDDI
                                          // MIB_IF_TYPE_PPP
                                          // MIB_IF_TYPE_LOOPBACK
                                          // MIB_IF_TYPE_SLIP
                                          // These values are defined in the header file IPIfCons.h.

   DhcpEnabled: UINT;                     // Specifies whether dynamic host configuration protocol
                                          //(DHCP) is enabled for this adapter.
   CurrentIpAddress: PIP_ADDR_STRING;     // Reserved.
   IpAddressList: IP_ADDR_STRING;         // List of IP addresses associated with this adapter.
   GatewayList: IP_ADDR_STRING;           // IP address of the default gateway for this adapter.
   DhcpServer: IP_ADDR_STRING;            // IP address of the DHCP server for this adapter. A value of
                                          //255.255.255.255 indicates the DHCP server could not be reached,
                                          // or is in the process of being reached.
   HaveWins: BOOL;                        // Specifies whether this adapter uses Windows Internet Name Service (WINS).
   PrimaryWinsServer: IP_ADDR_STRING;     // IP address of the primary WINS server.
   SecondaryWinsServer: IP_ADDR_STRING;   // IP address of the secondary WINS server.
   LeaseObtained: time_t;                 // Time when the current DHCP lease was obtained.
   LeaseExpires: time_t;                  // Time when the current DHCP lease expires.
end;

function GetAdaptersInfo(pAdapterInfo: PIP_ADAPTER_INFO; var pOutBufLen: ULONG): DWORD;stdcall; external "iphlpapi.dll";
...
...
function PhysAddrToString(Length: DWORD; PhysAddr: TPhysAddrByteArray): string;
var
 I: Integer;
begin
 Result := "";
 if Length = 0
 then Exit;
 for I := 0 to Length - 1 do
   if I = Integer(Length - 1)
   then Result := Result + Format("%.2x", [PhysAddr[I]])
   else Result := Result + (Format("%.2x-", [PhysAddr[I]]));
end;

function EnumAdapters:Integer;
var Size:ULONG;
   Adapter,Adapters:PIP_ADAPTER_INFO;
   IP:PIP_ADDR_STRING;
   IPAddress:String;
begin
 Result := 0;
 Size := 0;
 MForm.AdapterBox.Items.Clear;
 MForm.IPAddressBox.Items.Clear;
 MForm.NICindex.Items.Clear;
 if GetAdaptersInfo(nil,Size) <> ERROR_BUFFER_OVERFLOW
 then Exit;
 Adapters := AllocMem(Size);
 TRY
   if GetAdaptersInfo(Adapters,Size) = NO_ERROR
   then begin
          Adapter := Adapters;
          while Adapter <> nil do
          begin
            if Adapter.Type_ = MIB_IF_TYPE_ETHERNET // Ну или какую там тебе надо...
            then begin
                   IP := @Adapter.IpAddressList;
                   MForm.NICindex.Items.Add(IntToStr(Adapter.Index));
                   IPAddress := "";
                   repeat
                     IPAddress := IPAddress + (Format("%s  ",[IP^.IpAddress.S]));
                     IP := IP.Next;
                   until IP = nil;
                   MForm.AdapterBox.Items.Add(Adapter.AdapterName);
                   MForm.DescAdapterBox.Items.Add(Adapter.Description);
                   MForm.IPAddressBox.Items.Add(IPAddress);
                   MForm.MACbox.Items.Add(PhysAddrToString(6, TPhysAddrByteArray(Adapter.Address)));
                   Inc(Result);
                 end;
            Adapter := Adapter^.Next;
          end;
        end;
 FINALLY
   FreeMem(Adapters);
 END;
end;

А вообще тут много раз уже проскакивали подобные запросы... Всех отправляли RTFM.


 
apic ©   (2006-08-17 18:01) [2]

Отец Кондратий, ты "красавчик"!


 
Микс   (2006-10-22 22:43) [3]

А вы не могли бы написать как в С++ Builder это выглядит?


 
piople ©   (2006-10-24 09:21) [4]

есть гараздо удобнее функции...


 
Микс   (2006-10-24 18:02) [5]

piople ты помочь можешь с С++ Builder ?


 
Falcao   (2006-10-24 21:53) [6]

"есть гараздо удобнее функции..." - точнее, наверное, СПОСОБЫ=)
Например, через getsockopt, Netbios(NCB *).
Микс, а на МСДН зайти лень? =)))
Вот рабочий пример :Р
http://www.sysman.ru/index.php?showtopic=7350


 
Микс   (2006-10-24 23:57) [7]

Очень много ошибок в этом коде
[C++ Error] Unit1.cpp(58): E2451 Undefined symbol "Memo1"
[C++ Error] Unit1.cpp(59): E2316 "Desc_ription" is not a member of "_IP_ADAPTER_INFO"
[C++ Warning] Unit1.cpp(61): W8012 Comparing signed and unsigned values
[C++ Error] Unit1.cpp(70): E2134 Compound statement missing }
[C++ Warning] Unit1.cpp(70): W8070 Function should return a value


 
Falcao   (2006-10-25 10:03) [8]

Микс, если ты не знаешь что такое Мемо1 и как исправить "Desc_ription"(читай внимательнее весь тот топик!).... то ... тебе очень трудно будет помочь. Начни с азов программирования/проектирования в RAD-системе Borland C++ Builder (VCL Win32) :D .
Микс, обсуждение того кода должно вестись там, где он собссно есть.
___
Уважаемые учаснеги ДельфиМастер, прошу прощения...


 
Микс   (2006-10-26 11:31) [9]

Falcao всё в норме, не надо меня поссылать в такую дать, бывает торможу. Праздники всякие мешаю работе =))



Страницы: 1 вся ветка

Форум: "Сети";
Текущий архив: 2007.04.15;
Скачать: [xml.tar.bz2];

Наверх





Память: 0.48 MB
Время: 0.036 c
15-1174641109
RDen
2007-03-23 12:11
2007.04.15
ICQ


2-1174912697
Mechanikus
2007-03-26 16:38
2007.04.15
minimize - maximize


15-1174119405
Vlad Oshin
2007-03-17 11:16
2007.04.15
Мысли про детей женского пола


2-1175127004
Lavrenty
2007-03-29 04:10
2007.04.15
Курсор в TMemo


2-1174824828
tar
2007-03-25 16:13
2007.04.15
Рамеры формы и экрана





Afrikaans Albanian Arabic Armenian Azerbaijani Basque Belarusian Bulgarian Catalan Chinese (Simplified) Chinese (Traditional) Croatian Czech Danish Dutch English Estonian Filipino Finnish French
Galician Georgian German Greek Haitian Creole Hebrew Hindi Hungarian Icelandic Indonesian Irish Italian Japanese Korean Latvian Lithuanian Macedonian Malay Maltese Norwegian
Persian Polish Portuguese Romanian Russian Serbian Slovak Slovenian Spanish Swahili Swedish Thai Turkish Ukrainian Urdu Vietnamese Welsh Yiddish Bengali Bosnian
Cebuano Esperanto Gujarati Hausa Hmong Igbo Javanese Kannada Khmer Lao Latin Maori Marathi Mongolian Nepali Punjabi Somali Tamil Telugu Yoruba
Zulu
Английский Французский Немецкий Итальянский Португальский Русский Испанский