CommHelper.cs 2.2 KB
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace DL.Com
{
    public class ComHelper
    {
        static UdpClient broadcastClient;     //广播客户端
        static IPEndPoint broadcastEndPoint;  //广播远程节点
        static byte[] broadcastBuffer;        //远程返回数据

        /// <summary>
        /// 自动获取IP地址,未连接前使用,必须在同一网段
        /// </summary>
        /// <param name="localIP">本地IP地址</param>
        /// <returns></returns>
        public static bool AutoIP(string localIP,out string ip)
        {
            ip = "";
            try
            {
                IPEndPoint local = new IPEndPoint(IPAddress.Parse(localIP), 55654);
                broadcastClient = new UdpClient(local);
                broadcastBuffer = null;

                Thread tTemp = new Thread(new ThreadStart(GetIP));
                tTemp.Start();
                broadcastEndPoint = new IPEndPoint(IPAddress.Parse("255.255.255.255"), 1024);
                byte[] dgram = new byte[] { 0x05, 0x00, 0x07, 0x00, 0x00, 0xC1, 0x59 };
                broadcastClient.Send(dgram, dgram.Length, broadcastEndPoint);
                Thread.Sleep(1000);
                tTemp.Abort();
                broadcastClient.Close();

                //ErrInfo = "无法访问";
                if (broadcastBuffer == null) return false;
                if (broadcastBuffer[0] != 0x3B) return false;

                byte[] buff = new byte[broadcastBuffer[7]];
                Array.Copy(broadcastBuffer, 9, buff, 0, buff.Length);
                ip = buff[buff.Length - 12] + "." + buff[buff.Length - 11] + "." + buff[buff.Length - 10] + "." + buff[buff.Length - 9];
                //ErrInfo = "OK";
                return true;
            }
            catch (Exception ex)
            {            
                return false;
            }
        }

        /// <summary>
        /// 获取目标IP地址
        /// </summary>
        static void GetIP()
        {
            broadcastBuffer = broadcastClient.Receive(ref broadcastEndPoint);
        }
    }
}