Get Mac NetBIOS

Socket programmer:

Tcp

Code:

/*----------------------------------------------------------*/
//CopyRight @ WWW.cnblogs.com
//Simple Tcp Client.
//Leo.wl
//2010-09-25
//qq:382448649
/*---------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Net;
using System.Net.Sockets;

namespace TcpClient
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            //
            //TODO:start
            //
            byte[] data = new byte[1024];
            Socket newclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            Console.Write("please input the server ip:");
            string ipadd = Console.ReadLine();
            Console.WriteLine();
            Console.Write("please input the server port:");
            int port = Convert.ToInt32(Console.ReadLine());
            IPEndPoint ie = new IPEndPoint(IPAddress.Parse(ipadd), port);//服务器的IP和端口
            try
            {
                //因为客户端只是用来向特定的服务器发送信息,所以不需要绑定本机的IP和端口。不需要监听。
                newclient.Connect(ie);
            }
            catch (SocketException e)
            {
                Console.WriteLine("unable to connect to server");
                Console.WriteLine(e.ToString());
                return;
            }
            int recv = newclient.Receive(data);
            string stringdata = Encoding.ASCII.GetString(data, 0, recv);
            Console.WriteLine(stringdata);
            while (true)
            {
                string input = Console.ReadLine();
                if (input == "exit")
                    break;
                newclient.Send(Encoding.ASCII.GetBytes(input));
                data = new byte[1024];
                recv = newclient.Receive(data);
                stringdata = Encoding.ASCII.GetString(data, 0, recv);
                Console.WriteLine(stringdata);
            }
            Console.WriteLine("disconnect from sercer");
            newclient.Shutdown(SocketShutdown.Both);
            newclient.Close();

        }
    }
}

/*----------------------------------------------------------*/
//CopyRight @ WWW.cnblogs.com
//Simple Tcp Server.
//Leo.wl
//2010-09-25
//qq:382448649
/*---------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Net;
using System.Net.Sockets;

namespace TcpServer
{
    
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            //
            // TODO: 在此处添加代码以启动应用程序
            //
            int recv;//用于表示客户端发送的信息长度
            byte[] data = new byte[1024];//用于缓存客户端所发送的信息,通过socket传递的信息必须为字节数组
            Console.WriteLine("IP: " + IPAddress.Any);
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);//本机预使用的IP和端口
            Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            newsock.Bind(ipep);//绑定
            newsock.Listen(10);//监听
            Console.WriteLine("waiting for a client");
            Socket client = newsock.Accept();//当有可用的客户端连接尝试时执行,并返回一个新的socket,用于与客户端之间的通信
            IPEndPoint clientip = (IPEndPoint)client.RemoteEndPoint;
            Console.WriteLine("connect with client:" + clientip.Address + " at port:" + clientip.Port);
            string welcome = "welcome here!";
            data = Encoding.ASCII.GetBytes(welcome);
            client.Send(data, data.Length, SocketFlags.None);//发送信息
            while (true)
            {//用死循环来不断的从客户端获取信息
                data = new byte[1024];
                recv = client.Receive(data);
                Console.WriteLine("recv=" + recv);
                if (recv == 0)//当信息长度为0,说明客户端连接断开
                    break;
                Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
                client.Send(data, recv, SocketFlags.None);
            }
            Console.WriteLine("Disconnected from" + clientip.Address);
            client.Close();
            newsock.Close();

        }
    }
}

UDP Code :

/*----------------------------------------------------------*/
//CopyRight @ WWW.cnblogs.com
//Simple Udp Client.
//Leo.wl
//2010-09-25
//qq:382448649
/*---------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Net;
using System.Net.Sockets;

namespace SimpleUdpClient
{
    /// <summary>
    /// UDP Class
    /// </summary>
    class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            //
            // TODO: 在此处添加代码以启动应用程序
            //
            byte[] data = new byte[1024];//定义一个数组用来做数据的缓冲区
            string input, stringData;
            IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            string welcome = "Hello,are you there?";
            data = Encoding.ASCII.GetBytes(welcome);
            server.SendTo(data, data.Length, SocketFlags.None, ipep);//将数据发送到指定的终结点

            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
            EndPoint Remote = (EndPoint)sender;
            data = new byte[1024];
            int recv = server.ReceiveFrom(data, ref Remote);//接受来自服务器的数据

            Console.WriteLine("Message received from{0}:", Remote.ToString());
            Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
            while (true)//读取数据
            {
                input = Console.ReadLine();//从键盘读取数据
                if (input == "text")//结束标记
                {
                    break;
                }
                server.SendTo(Encoding.ASCII.GetBytes(input), Remote);//将数据发送到指定的终结点Remote
                data = new byte[1024];
                recv = server.ReceiveFrom(data, ref Remote);//从Remote接受数据
                stringData = Encoding.ASCII.GetString(data, 0, recv);
                Console.WriteLine(stringData);
            }
            Console.WriteLine("Stopping client");
            server.Close();
        

        }
    }
}

/*----------------------------------------------------------*/
//CopyRight @ WWW.cnblogs.com
//Simple Udp Server.
//Leo.wl
//2010-09-25
//qq:382448649
/*---------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Net;
using System.Net.Sockets;

namespace SimpleUdpServer
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            //
            //TODO:start
            //
            int recv;
            byte[] data = new byte[1024];
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);//定义一网络端点
            Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);//定义一个Socket
            newsock.Bind(ipep);//Socket与本地的一个终结点相关联
            Console.WriteLine("Waiting for a client..");

            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);//定义要发送的计算机的地址
            EndPoint Remote = (EndPoint)(sender);//
            recv = newsock.ReceiveFrom(data, ref Remote);//接受数据           
            Console.WriteLine("Message received from{0}:", Remote.ToString());
            Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));

            string welcome = "Welcome to my test server!";
            data = Encoding.ASCII.GetBytes(welcome);
            newsock.SendTo(data, data.Length, SocketFlags.None, Remote);
            while (true)
            {
                data = new byte[1024];
                recv = newsock.ReceiveFrom(data, ref Remote);
                Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
                newsock.SendTo(data, recv, SocketFlags.None, Remote);
            }

        }
    }
}

Get Mac Address:

/*----------------------------------------------------------*/
//CopyRight @ WWW.cnblogs.com
//Simple GetMacTest.
//Leo.wl
//2010-09-25
//qq:382448649
/*---------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Net;
using System.Net.Sockets;
using System.IO;


namespace GetMacTest
{
    /// <summary>
    /// Program is class name.
    /// Get Remote Client Mac Address.
    /// </summary>
    public class Program
    {
        int recv = 0;
        int iRemotePort = 137;
        string sRemoteAddr = "61.191.148.2";
        byte[] data = new byte[1024];
        byte[] buffer = new byte[1024]; 
        Socket newsock = null;

        [STAThread]
        static void Main(string[] args)
        {
            try
            {
                Program o = new Program();
                Console.WriteLine("Mac Addr :  "+ o.GetRemoteMacAddr());
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

        }

        /// <summary>
        /// 1.发送NetBIOS数据查询包到远程客户端。
        /// 2.接受远程客户端返回的NetBIOS数据包。
        /// 3.137端口是NetBIOS名称UDP,138端口是NetBIOS数据报UDP,139端口是NetBIOS会话TCP
        /// </summary>
        /// <param name="bytes">查询包内容</param>
        /// <returns></returns>
        protected byte[]  MySendAndReceive(byte[] bytes)
        {
            try
            {
                IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(sRemoteAddr), iRemotePort);//定义一网络端点
                newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);//定义一个Socket
                //newsock.Bind(ipep);//Socket与本地的一个终结点相关联
                newsock.SendTo(bytes, bytes.Length, SocketFlags.None, ipep);
                EndPoint Remote = (EndPoint)(ipep);
                recv = newsock.ReceiveFrom(data, ref Remote);//接受数据           
                Console.WriteLine("Message received from: {0} ", Remote.ToString());
                Console.WriteLine("接受到的远程NetBIOS数据: ");
                Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
                return data;

            }
            catch (IOException ex)
            {
                throw new Exception(ex.Message);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// NetBIOS查询包结构
        /// </summary>
        /// <returns>NetBIOS查询包</returns>
        protected byte[] GetQueryCmd()
        {
            try
            {
                byte[] t_ns = new byte[50];
                t_ns[0] = 0x00;
                t_ns[1] = 0x00;
                t_ns[2] = 0x00;
                t_ns[3] = 0x10;
                t_ns[4] = 0x00;
                t_ns[5] = 0x01;
                t_ns[6] = 0x00;
                t_ns[7] = 0x00;
                t_ns[8] = 0x00;
                t_ns[9] = 0x00;
                t_ns[10] = 0x00;
                t_ns[11] = 0x00;
                t_ns[12] = 0x20;
                t_ns[13] = 0x43;
                t_ns[14] = 0x4B;

                for (int i = 15; i < 45; i++)
                {
                    t_ns[i] = 0x41;
                }

                t_ns[45] = 0x00;
                t_ns[46] = 0x00;
                t_ns[47] = 0x21;
                t_ns[48] = 0x00;
                t_ns[49] = 0x01;
                return t_ns;
            }
            catch (Exception ex)
            {
                throw new  Exception(ex.Message);
            }
        }

        /// <summary>
        /// 客户端返回的NetBIOS包中的网卡(MAC)编号。
        /// </summary>
        /// <param name="brevdata">客户端返回的NetBIOS包</param>
        /// <returns>远程客户端的网卡地址</returns>
        protected String GetMacAddr(byte[] brevdata)
        {
            try
            {
                int i = brevdata[56] * 18 + 56;
                String sAddr = "";
                StringBuilder sb = new StringBuilder(17);

                for (int j = 1; j < 7; j++)
                {
                    sAddr = Convert.ToInt32((0xFF & brevdata[i + j])).ToString("x");
                    if (sAddr.Length < 2)
                    {
                        sb.Append(0);
                    }
                    sb.Append(sAddr.ToUpper());
                    if (j < 6)
                        sb.Append(':');
                }
                return sb.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// 关闭套接字
        /// </summary>
        protected void MyClose()
        {
            try
            {
                newsock.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// 查询获得远程网卡地址
        /// </summary>
        /// <returns>远程客户端网卡地址</returns>
        protected  string GetRemoteMacAddr()
        {
            try
            {
                byte[] bqcmd = GetQueryCmd();
                buffer = MySendAndReceive(bqcmd);
                string remoteMac = GetMacAddr(buffer);
                MyClose();
                return remoteMac;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
    }
}

/**原理:
* 主机A向主机B发送“UDP-NetBIOS-NS”询问包,即向主机B的137端口,发Query包来询问主机B的NetBIOS Names信息。
* 其次,主机B接收到“UDP-NetBIOS-NS”询问包,假设主机B正确安装了NetBIOS服务........... 而且137端口开放,则主机B会向主机A发送一个“UDP-NetBIOS-NS”应答包,即发Answer包给主机A。
* 并利用UDP(NetBIOS Name Service)来快速获取远程主机MAC地址的方法     *
* @author Hyey.wl
*/
原文地址:https://www.cnblogs.com/Leo_wl/p/1833844.html