金鹏

|| 叶落知秋,见微知著。|| 不出户,知天下﹔不窥牖,见天道。其出弥远,其知弥少。是以圣人不行而知,不见而明,不为而成。

博客园 首页 新随笔 联系 订阅 管理

代码如下:

 

using System;
using System.Net;
using System.Threading;

using System.Runtime.InteropServices;

namespace LocalIP {
  
class LanSearch {

    
/// <summary>
    
/// 取MAC地址
    
/// </summary>
    
/// <param name="DestIP">目标IP</param>
    
/// <param name="SrcIP">源IP</param>
    
/// <param name="pMacAddr">MAC地址</param>
    
/// <param name="PhyAddrLen">MAC地址的长度</param>
    
/// <returns></returns>

    [DllImport("iphlpapi.dll", ExactSpelling = true)]
    
private static unsafe extern int SendARP(int DestIP, int SrcIP, [Out] byte[] pMacAddr, ref int PhyAddrLen);

    
/// <summary>
    
/// 在线程中扫描
    
/// </summary>

    private static void LanSearchThreadMethod() {
      
int i = Convert.ToUInt16(Thread.CurrentThread.Name);
      Console.Write(
".");

      
string strIP = "192.168.1." + i.ToString();

      
//IPHostEntry ip = null;
      IPAddress ip = null;
      
try {
        
//ip = Dns.GetHostEntry(strIP);
        ip = IPAddress.Parse(strIP);
      }

      
catch {
        
//Console.WriteLine("请勿输入非法IP地址");
        return;
      }


      
byte[] b = new byte[6];
      
int len = b.Length;
      
//int r = SendARP(BitConverter.ToInt32(ip.AddressList[0].GetAddressBytes(), 0), 0, b, ref len);
      int r = SendARP(BitConverter.ToInt32(ip.GetAddressBytes(), 0), 0, b, ref len);
      
int num = BitConverter.ToInt32(b, 0);
      
string mac = BitConverter.ToString(b, 06);

      
if (num != 0{//有效MAC
        
//Console.WriteLine("\r\n{0}--{1}--{2}", ip.AddressList[0].ToString(), ip.HostName, mac);
        Console.WriteLine("\r\n{0}--{1}", ip.ToString(), mac);
      }

    }


    
/// <summary>
    
/// 程序主入口
    
/// </summary>
    
/// <param name="args"></param>

    [STAThread]
    
static void Main(string[] args) {
      Thread[] thread 
= new Thread[255];
      ThreadStart threadMethod;

      
for (int i = 0; i < 255; i++{
        threadMethod 
= new ThreadStart(LanSearchThreadMethod);
        thread[i] 
= new Thread(threadMethod);
        thread[i].Name 
= i.ToString();
        thread[i].Start();
        
if (!thread[i].Join(100)) {
          thread[i].Abort();
        }

      }


      Console.WriteLine(
"\r\n按任意键返回");
      Console.ReadLine();
    }


  }

}

posted on 2008-08-29 12:31  金鹏  阅读(1716)  评论(0编辑  收藏  举报