新书推介:《语义网技术体系》
作者:瞿裕忠,胡伟,程龚
   XML论坛     W3CHINA.ORG讨论区     计算机科学论坛     SOAChina论坛     Blog     开放翻译计划     新浪微博  
 
  • 首页
  • 登录
  • 注册
  • 软件下载
  • 资料下载
  • 核心成员
  • 帮助
  •   Add to Google

    >> 本版讨论.NET,C#,ASP,VB技术
    [返回] 中文XML论坛 - 专业的XML技术讨论区计算机技术与应用『 Dot NET,C#,ASP,VB 』 → C# Socket 异步接受网络广播 查看新帖用户列表

      发表一个新主题  发表一个新投票  回复主题  (订阅本版) 您是本帖的第 5584 个阅读者浏览上一篇主题  刷新本主题   树形显示贴子 浏览下一篇主题
     * 贴子主题: C# Socket 异步接受网络广播 举报  打印  推荐  IE收藏夹 
       本主题类别:     
     卷积内核 帅哥哟,离线,有人找我吗?
      
      
      威望:8
      头衔:总统
      等级:博士二年级(版主)
      文章:3942
      积分:27590
      门派:XML.ORG.CN
      注册:2004/7/21

    姓名:(无权查看)
    城市:(无权查看)
    院校:(无权查看)
    给卷积内核发送一个短消息 把卷积内核加入好友 查看卷积内核的个人资料 搜索卷积内核在『 Dot NET,C#,ASP,VB 』的所有贴子 访问卷积内核的主页 引用回复这个贴子 回复这个贴子 查看卷积内核的博客楼主
    发贴心情 C# Socket 异步接受网络广播


    必须设置SOCKET为低级操作模式

                        byte[] InByte = new byte[4] { 1, 0, 0, 0 };
                        byte[] OutByte = new byte[4];
                        int SIO_RCVALL = unchecked((int)0x98000001);
                        int ScoketCode = MySocket.IOControl(SIO_RCVALL, InByte, OutByte);
                        ScoketCode = OutByte[0] + OutByte[1] + OutByte[2] + OutByte[3];

    数据包的结构
    [StructLayout(LayoutKind.Explicit)]
    public struct IPHeader
    {
      [FieldOffset(0)] public byte    ip_verlen; //IP version and IP Header length Combined
      [FieldOffset(1)] public byte    ip_tos; //Type of Service
      [FieldOffset(2)] public ushort  ip_totallength; //Total Packet Length
      [FieldOffset(4)] public ushort  ip_id; //Unique ID
      [FieldOffset(6)] public ushort  ip_offset; //Flags and Offset
      [FieldOffset(8)] public byte    ip_ttl; //Time To Live
      [FieldOffset(9)] public byte    ip_protocol; //Protocol (TCP, UDP, ICMP, Etc.)
      [FieldOffset(10)] public ushort ip_checksum; //IP Header Checksum
      [FieldOffset(12)] public uint   ip_srcaddr; //Source IP Address
      [FieldOffset(16)] public uint   ip_destaddr; //Destination IP Address
    }

    下面是全部代码

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Net;
    using System.Net.Sockets;
    using System.Runtime.InteropServices;

    namespace ReceiveAll
    {
        public class MyRawSocket
        {
            private IPAddress MyIP;
            private bool RunRawSocket = false;
            private Socket MySocket;

            public MyRawSocket(IPAddress MyIPAddress)
            {
                MyIP = MyIPAddress;

                MySocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
                MySocket.Blocking = false;
                MySocket.Bind(new IPEndPoint(MyIPAddress, 0));

                if (SetSocketIOControl() == false) return;
                RunRawSocket = true;
            }

            private bool SetSocketIOControl()
            {
                bool ReturnBool = true;
                try
                {
                    MySocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, 1);
                    byte[] InByte = new byte[4] { 1, 0, 0, 0 };
                    byte[] OutByte = new byte[4];
                    int SIO_RCVALL = unchecked((int)0x98000001);
                    int ScoketCode = MySocket.IOControl(SIO_RCVALL, InByte, OutByte);
                    ScoketCode = OutByte[0] + OutByte[1] + OutByte[2] + OutByte[3];
                    if (ScoketCode != 0) ReturnBool = false;
                }
                catch (SocketException)
                {
                    ReturnBool = false;
                }
                return ReturnBool;
            }

            public void Star()
            {
                byte[] Temp = new byte[0];
                IAsyncResult StarAsyncResult = MySocket.BeginReceive(Temp, 0, 0, SocketFlags.None, new AsyncCallback(CallReceive), MySocket);
            }
            public void Stop()
            {
                RunRawSocket = false;
            }

            private void CallReceive(IAsyncResult ar)
            {
                Socket sock = (Socket)ar.AsyncState;
                int ReceiveCount = sock.Available;

                if (ReceiveCount != 0)
                {
                    byte[] Data = new byte[ReceiveCount];
                    sock.Receive(Data);
                    AssayByte(Data);
                }
                if (RunRawSocket) Star();
            }

            /// <summary>
            /// 分析数据
            /// </summary>
            /// <param name="Data"></param>
            private void AssayByte(byte[] Data)
            {
                IPData MyData = new IPData();
                if (Data.Length >= 24)
                {

                    MyData.HeaderLength = (uint)(Data[0] & 0x0F) << 2;

                    MyData.Version = (uint)(Data[0] & 0xF0) >> 4;

                    switch (Data[9])
                    {
                        case 1: MyData.Protocol = "ICMP"; break;
                        case 2: MyData.Protocol = "IGMP"; break;
                        case 6: MyData.Protocol = "TCP"; break;
                        case 17: MyData.Protocol = "UDP"; break;
                        default: MyData.Protocol = "UNKNOWN"; break;
                    }

                    MyData.OriginationAddress = new IPAddress(new byte[] { Data[12], Data[13], Data[14], Data[15] });
                    MyData.DestinationAddress = new IPAddress(new byte[] { Data[16], Data[17], Data[18], Data[19] });

                    MyData.OriginationPort = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(new byte[] { Data[20], Data[21] }, 0));
                    MyData.DestinationPort = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(new byte[] { Data[22], Data[23] }, 0));

                    MyData.PacketLength = (uint)Data.Length;
                    MyData.MessageLength = (uint)Data.Length - MyData.HeaderLength;

                    MyData.PackByte = Data;
                }
                else
                {
                    MyData.PackByte = Data;
                }
                if (Receive != null) Receive(MyData);
            }

            public delegate void ReceiveData(IPData ReceiveClass);
            public event ReceiveData Receive;

            public class IPData
            {

                private uint _HeaderLength = 0;
                private uint _Version = 0;
                private string _Protocol = "";
                private IPAddress _OriginationAddress;
                private IPAddress _DestinationAddress;
                private short _OriginationPort = 0;
                private short _DestinationPort = 0;
                private uint _PacketLength = 0;
                private uint _MessageLength = 0;
                private byte[] _PackByte;
                /// <summary>
                /// IP头长度
                /// </summary>
                public uint HeaderLength { get { return _HeaderLength; } set { _HeaderLength = value; } }
                /// <summary>
                /// IP版本
                /// </summary>
                public uint Version { get { return _Version; } set { _Version = value; } }
                /// <summary>
                /// IP协议
                /// </summary>
                public string Protocol { get { return _Protocol; } set { _Protocol = value; } }
                /// <summary>
                /// 发送IP地址
                /// </summary>
                public IPAddress OriginationAddress { get { return _OriginationAddress; } set { _OriginationAddress = value; } }
                /// <summary>
                /// 接收IP地址
                /// </summary>
                public IPAddress DestinationAddress { get { return _DestinationAddress; } set { _DestinationAddress = value; } }
                /// <summary>
                /// 发送端口
                /// </summary>
                public short OriginationPort { get { return _OriginationPort; } set { _OriginationPort = value; } }
                /// <summary>
                /// 接收端口
                /// </summary>
                public short DestinationPort { get { return _DestinationPort; } set { _DestinationPort = value; } }
                /// <summary>
                /// 接收长度
                /// </summary>
                public uint PacketLength { get { return _PacketLength; } set { _PacketLength = value; } }
                /// <summary>
                /// 消息长度
                /// </summary>
                public uint MessageLength { get { return _MessageLength; } set { _MessageLength = value; } }

                /// <summary>
                /// 包数据
                /// </summary>
                public byte[] PackByte { get { return _PackByte; } set { _PackByte = value; } }

            }

        }
    }

    使用方式

       MyRawSocket myRawSock;
      private void MainForm_Load(object sender, System.EventArgs e)
      {
                myRawSock = new MyRawSocket(IPAddress.Parse("192.168.1.111"));
                myRawSock.Receive += new MyRawSocket.ReceiveData(myRawSock_Receive);         
      }

            void myRawSock_Receive(MyRawSocket.IPData ReceiveClass)
            {
                string Temp = ReceiveClass.OriginationAddress.ToString() + ":" + ReceiveClass.OriginationPort.ToString()+"\t";
                Temp+=ReceiveClass.DestinationAddress.ToString() + ":" + ReceiveClass.DestinationPort.ToString()+"\t";
                Temp+="{Size="+ReceiveClass.PackByte.Length.ToString()+"}";
                this.Invoke((MethodInvoker)delegate { listBox1.Items.Add(Temp); });
            }
            private void button1_Click(object sender, System.EventArgs e)
      {
                myRawSock.Star();
      }


       收藏   分享  
    顶(0)
      




    ----------------------------------------------
    事业是国家的,荣誉是单位的,成绩是领导的,工资是老婆的,财产是孩子的,错误是自己的。

    点击查看用户来源及管理<br>发贴IP:*.*.*.* 2012/7/24 10:07:00
     
     GoogleAdSense
      
      
      等级:大一新生
      文章:1
      积分:50
      门派:无门无派
      院校:未填写
      注册:2007-01-01
    给Google AdSense发送一个短消息 把Google AdSense加入好友 查看Google AdSense的个人资料 搜索Google AdSense在『 Dot NET,C#,ASP,VB 』的所有贴子 访问Google AdSense的主页 引用回复这个贴子 回复这个贴子 查看Google AdSense的博客广告
    2024/12/27 3:14:00

    本主题贴数1,分页: [1]

    管理选项修改tag | 锁定 | 解锁 | 提升 | 删除 | 移动 | 固顶 | 总固顶 | 奖励 | 惩罚 | 发布公告
    W3C Contributing Supporter! W 3 C h i n a ( since 2003 ) 旗 下 站 点
    苏ICP备05006046号《全国人大常委会关于维护互联网安全的决定》《计算机信息网络国际联网安全保护管理办法》
    6,686.523ms