IOControl() public method

public IOControl ( IOControlCode ioControlCode, byte optionInValue, byte optionOutValue ) : int
ioControlCode IOControlCode
optionInValue byte
optionOutValue byte
return int
        public void RunReciever()
        {

            ListenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
            try
            {
                // Setup the Socket
                ListenSocket.Bind(new IPEndPoint(IPAddress.Parse(p_HostIP), 0));
                ListenSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, 1);
                ListenSocket.IOControl(unchecked((int) 0x98000001), new byte[4] {1, 0, 0, 0}, new byte[4]);
                while (true) //Infinite Loop keeps the Socket in Listen
                {
                    ListenSocket.BeginReceive(p_PacketBuffer, 0, p_PacketBufferSize, SocketFlags.None,
                                                new AsyncCallback(CallReceive), this); 

                    while (ListenSocket.Available == 0) // If no Data Sleep the thread for 1ms then check to see if there is data to be read
                    {
                        Thread.Sleep(1);
                    }
                }
            }
            catch (ThreadAbortException){}// Catch the ThreadAbort Exception that gets generated whenever a thread is closed with the Thread.Abort() method
            catch (Exception e) {new ErrorHandle(e);}
            finally //Shutdown the Socket when finished
            {
                if (ListenSocket != null)
                {
                    ListenSocket.Shutdown(SocketShutdown.Both);
                    ListenSocket.Close();
                }
            }
        }
Example #2
0
        /// <summary>
        /// Starts to listen
        /// </summary>
        /// <param name="config">The server config.</param>
        /// <returns></returns>
        public override bool Start(IServerConfig config)
        {
            try
            {
                m_ListenSocket = new Socket(this.EndPoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
                m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                m_ListenSocket.Bind(this.EndPoint);

                //Mono doesn't support it
                if (Platform.SupportSocketIOControlByCodeEnum)
                {
                    uint IOC_IN = 0x80000000;
                    uint IOC_VENDOR = 0x18000000;
                    uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;

                    byte[] optionInValue = { Convert.ToByte(false) };
                    byte[] optionOutValue = new byte[4];
                    m_ListenSocket.IOControl((int)SIO_UDP_CONNRESET, optionInValue, optionOutValue);
                }

                var eventArgs = m_SaePool.Get();

                m_ListenSocket.ReceiveFromAsync(eventArgs);

                return true;
            }
            catch (Exception e)
            {
                OnError(e);
                return false;
            }
        }
Example #3
0
        public static void Initialize()
        {
            try
            {
                var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.IOControl(IOControlCode.KeepAliveValues, null, null);
                SupportSocketIOControlByCodeEnum = true;
                IsMono = false;
            }
            catch (NotSupportedException)
            {
                SupportSocketIOControlByCodeEnum = false;
            }
            catch (NotImplementedException)
            {
                SupportSocketIOControlByCodeEnum = false;
            }
            catch (Exception)
            {
                SupportSocketIOControlByCodeEnum = true;
            }

            Type t = Type.GetType("Mono.Runtime");
            IsMono = t != null;
        }
Example #4
0
        public SslHelper(Socket socket, string host)
        {
            //The managed SocketOptionName enum doesn't have SO_SECURE so here we cast the integer value
            socket.SetSocketOption(SocketOptionLevel.Socket, (SocketOptionName)SO_SECURE, SO_SEC_SSL);

            //We need to pass a function pointer and a pointer to a string containing the host
            //to unmanaged code
            hookFunc = Marshal.GetFunctionPointerForDelegate(new SSLVALIDATECERTFUNC(ValidateCert));

            //Allocate the buffer for the string
            ptrHost = Marshal.AllocHGlobal(host.Length + 1);
            WriteASCIIString(ptrHost, host);

            //Now put both pointers into a byte[]
            var inBuffer = new byte[8];
            var hookFuncBytes = BitConverter.GetBytes(hookFunc.ToInt32());
            var hostPtrBytes = BitConverter.GetBytes(ptrHost.ToInt32());
            Array.Copy(hookFuncBytes, inBuffer, hookFuncBytes.Length);
            Array.Copy(hostPtrBytes, 0, inBuffer, hookFuncBytes.Length, hostPtrBytes.Length);

            unchecked
            {
                socket.IOControl((int)SO_SSL_SET_VALIDATE_CERT_HOOK, inBuffer, null);
            }
        }
        /// <summary>
        /// Starts to listen
        /// </summary>
        /// <param name="config">The server config.</param>
        /// <returns></returns>
        public override bool Start(IServerConfig config)
        {
            try
            {
                m_ListenSocket = new Socket(this.EndPoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
                m_ListenSocket.Bind(this.EndPoint);

                uint IOC_IN = 0x80000000;
                uint IOC_VENDOR = 0x18000000;
                uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;

                byte[] optionInValue = { Convert.ToByte(false) };
                byte[] optionOutValue = new byte[4];
                m_ListenSocket.IOControl((int)SIO_UDP_CONNRESET, optionInValue, optionOutValue);

                var eventArgs = new SocketAsyncEventArgs();

                eventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(eventArgs_Completed);
                eventArgs.RemoteEndPoint = new IPEndPoint(IPAddress.Any, 0);

                int receiveBufferSize = config.ReceiveBufferSize <= 0 ? 2048 : config.ReceiveBufferSize;
                var buffer = new byte[receiveBufferSize];
                eventArgs.SetBuffer(buffer, 0, buffer.Length);

                m_ListenSocket.ReceiveFromAsync(eventArgs);

                return true;
            }
            catch (Exception e)
            {
                OnError(e);
                return false;
            }
        }
Example #6
0
        public bool StartReceiving(bool bBind)
        {
#if !MONO
            /// See http://blog.devstone.com/aaron/archive/2005/02/20/460.aspx
            /// This will stop winsock errors when receiving an ICMP packet
            /// "Destination unreachable"
            byte[] inValue  = new byte[] { 0, 0, 0, 0 };    // == false
            byte[] outValue = new byte[] { 0, 0, 0, 0 };    // initialize to 0
            s.IOControl(SIO_UDP_CONNRESET, inValue, outValue);
#endif

            if ((bBind == true) && (Bind() == false))
            {
                return(false);
            }

            lock (SyncRoot)
            {
                m_bReceive = true;
                s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, 128000);
                /// have 8 pending receives in the queue at all times

                DoReceive();
#if !MONO
                if (System.Environment.OSVersion.Version.Major >= 6)
                {
                    DoReceive();
                    DoReceive();
                }
#endif
            }
            return(true);
        }
Example #7
0
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if ((sender as CheckBox).Checked)
            {
                (sender as CheckBox).Text = "&Stop me";
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
                try
                {
                    socket.Bind(new IPEndPoint(IPAddress.Parse(comboBox1.SelectedItem.ToString()), 0));
                    socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true);

                    byte[] byInc = new byte[] { 1, 0, 0, 0 };
                    byte[] byOut = new byte[4];
                    buffer = new byte[4096];
                    socket.IOControl(IOControlCode.ReceiveAll, byInc, byOut);
                    socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, OnReceive, null);
                }
                catch (SocketException se)
                {
                    MessageBox.Show(se.Message);
                }

            }
            else
            {
                socket.Close();
                (sender as CheckBox).Text = "&Start me";
            }
        }
Example #8
0
        public bool init()
        {
            bool ret = true;
            try{
                m_socket = new Socket(AddressFamily.InterNetwork,
                SocketType.Dgram,
                ProtocolType.Udp);

                uint IOC_IN = 0x80000000;
                uint IOC_VENDOR = 0x18000000;
                uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;
                m_socket.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null);

                EndPoint localEP = new IPEndPoint(IPAddress.Parse(m_ip), m_port);
                m_socket.Bind(localEP);
                ret = true;
                initialized = true;
                destroyed = false;
            }
            catch(Exception e)
            {
                Console.WriteLine(e.Message);
                ret = false;
                initialized = false;
            }

            return ret;
        }
        protected ISocketSession RegisterSession(Socket client, ISocketSession session)
        {
            if (m_SendTimeOut > 0)
                client.SendTimeout = m_SendTimeOut;

            if (m_ReceiveBufferSize > 0)
                client.ReceiveBufferSize = m_ReceiveBufferSize;

            if (m_SendBufferSize > 0)
                client.SendBufferSize = m_SendBufferSize;

            if(!Platform.SupportSocketIOControlByCodeEnum)
                client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
            else
                client.IOControl(IOControlCode.KeepAliveValues, m_KeepAliveOptionValues, null);

            client.NoDelay = true;
            client.UseOnlyOverlappedIO = true;
            client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);

            IAppSession appSession = this.AppServer.CreateAppSession(session);

            if (appSession == null)
                return null;

            return session;
        }
Example #10
0
        public static int SetKeepAliveValues(System.Net.Sockets.Socket Socket, bool On_Off,
                                             uint KeepAliveTime, uint KeepAliveInterval)
        {
            int Result = -1;

            unsafe
            {
                TcpKeepAlive KeepAliveValues = new TcpKeepAlive();

                KeepAliveValues.On_Off            = Convert.ToUInt32(On_Off);
                KeepAliveValues.KeepAliveTime     = KeepAliveTime;
                KeepAliveValues.KeepAliveInterval = KeepAliveInterval;

                byte[] InValue = new byte[12];

                for (int I = 0; I < 12; I++)
                {
                    InValue[I] = KeepAliveValues.Bytes[I];
                }

                Result = Socket.IOControl(IOControlCode.KeepAliveValues, InValue, null);
            }

            return(Result);
        }
Example #11
0
        /// <summary>
        /// 设置会话的心跳包
        /// </summary>
        /// <param name="socket">客户端</param>
        /// <param name="dueTime">延迟的时间量(以毫秒为单位)</param>
        /// <param name="period">时间间隔(以毫秒为单位)</param>
        /// <returns></returns>
        private bool TrySetKeepAlive(System.Net.Sockets.Socket socket, int dueTime, int period)
        {
            var inOptionValue  = new byte[12];
            var outOptionValue = new byte[12];

            ByteConverter.ToBytes(1, ByteConverter.Endian).CopyTo(inOptionValue, 0);
            ByteConverter.ToBytes(dueTime, ByteConverter.Endian).CopyTo(inOptionValue, 4);
            ByteConverter.ToBytes(period, ByteConverter.Endian).CopyTo(inOptionValue, 8);

            try
            {
                socket.IOControl(IOControlCode.KeepAliveValues, inOptionValue, outOptionValue);
                return(true);
            }
            catch (NotSupportedException)
            {
                socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, inOptionValue);
                return(true);
            }
            catch (NotImplementedException)
            {
                socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, inOptionValue);
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
        private void btnStart_Click(object sender, EventArgs e)
        {
            if (cmbInterfaces.Text == "")
            {
                MessageBox.Show("Select an Interface to capture the packets.", "Omkar_sniffer", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            try
            {
                if (!bContinueCapturing)        
                {
                    //Start capturing the packets...

                    btnStart.Text = "&Stop";

                    bContinueCapturing = true;

                    //For sniffing the socket to capture the packets has to be a raw socket, with the
                    //address family being of type internetwork, and protocol being IP
                    mainSocket = new Socket(AddressFamily.InterNetwork,
                        SocketType.Raw, ProtocolType.IP);
                    
                    //Bind the socket to the selected IP address
                    mainSocket.Bind(new IPEndPoint(IPAddress.Parse(cmbInterfaces.Text), 0));

                    //Set the socket  options
                    mainSocket.SetSocketOption(SocketOptionLevel.IP,            //Applies only to IP packets
                                               SocketOptionName.HeaderIncluded, //Set the include the header
                                               true);                           //option to true

                    byte[] byTrue = new byte[4] {1, 0, 0, 0};
                    byte[] byOut = new byte[4]{1, 0, 0, 0}; //Capture outgoing packets

                    //Socket.IOControl is analogous to the WSAIoctl method of Winsock 2
                    mainSocket.IOControl(IOControlCode.ReceiveAll,              //Equivalent to SIO_RCVALL constant
                                                                                //of Winsock 2
                                         byTrue,                                    
                                         byOut);

                    //Start receiving the packets asynchronously
                    mainSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None,
                        new AsyncCallback(OnReceive), null);
                }
                else
                {
                    btnStart.Text = "&Start";
                    bContinueCapturing = false;
                    //To stop capturing the packets close the socket
                    mainSocket.Close ();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Omkar_sniffer", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Example #13
0
 public void create(List<string> ipv4)
 {
     if (ipv4 != null && ipv4.Count > 0) {
         mSocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
         for(int i=0; i<ipv4.Count; i++) mSocket.Bind(new IPEndPoint(IPAddress.Parse(ipv4[i]), 0));
         mSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true);
         byte[] byTrue = new byte[4] { 1, 0, 0, 0 }, byOut = new byte[4] { 1, 0, 0, 0 };
         mSocket.IOControl(IOControlCode.ReceiveAll, byTrue, byOut);
         mSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(OnReceive), null);
     }
 }
 private void Init()
 {
     Debug.Assert(_socket == null);
     _socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
     if (_localIp != null)
         _socket.Bind(new IPEndPoint(_localIp, 0));
     _socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true);
     var receiveAllOn = BitConverter.GetBytes(1);
     _socket.IOControl(IOControlCode.ReceiveAll, receiveAllOn, null);
     Read();
 }
Example #15
0
        public SnifferBase(IPAddress bindTo)
        {
            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
            _socket .Bind(new IPEndPoint(bindTo, 0));
            _socket .SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true);                           //option to true

            var byTrue = new byte[] {0x1, 0x0, 0x0, 0x0};
            var byOut = new byte[] {0x1, 0x0, 0x0, 0x0};

            _socket.IOControl(IOControlCode.ReceiveAll, byTrue, byOut);
        }
Example #16
0
 private void CreateIcmpSocket(IPEndPoint endPoint)
 {
     icmpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp);
     LocalEndPoint = endPoint;
     icmpSocket.Bind(endPoint);
     PlatformID p = Environment.OSVersion.Platform;
     if (p == PlatformID.Win32NT && !endPoint.Address.Equals(IPAddress.Any))
     {
         icmpSocket.IOControl(IOControlCode.ReceiveAll, new byte[] { 1, 0, 0, 0 }, new byte[] { 1, 0, 0, 0 });
     }
     BeginReceiveFrom();
 }
Example #17
0
 public static void SetClient(Socket client)
 {
     //client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
     //client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, m_receiveBufferSize);
     //client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, m_sendBufferSize);
     client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
     #if mono
     client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
     #else
     client.IOControl(IOControlCode.KeepAliveValues, KeepValue, null);
     #endif
 }
Example #18
0
		/// <summary>
		/// Starts listening on the specified interface.
		/// </summary>
		/// <exception cref="SocketException">An error occurs when trying to intercept IP packets.</exception>
		public void Start() {
			if (m_Monitor == null) {
				try {
					m_Monitor = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
					m_Monitor.Bind(new IPEndPoint(IP, 0));
					m_Monitor.IOControl(SIO_RCVALL, BitConverter.GetBytes((int)1), null);
					m_Monitor.BeginReceive(m_Buffer, 0, m_Buffer.Length, SocketFlags.None, new AsyncCallback(this.OnReceive), null);
				} catch {
					m_Monitor = null;
					throw new SocketException();
				}
			}
		}
Example #19
0
        //设置心跳
        private void SetXinTiao(Socket tmpsock)
        {
            try
            {
                //int keepAlive = -1744830460;
                byte[] inValue = new byte[] { 1, 0, 0, 0, 0x20, 0x4e, 0, 0, 0xd0, 0x07, 0, 0 };// 首次探测时间20 秒, 间隔侦测时间2 秒
                tmpsock.IOControl(IOControlCode.KeepAliveValues, inValue, null);
            }
            catch
            {

            }
        }
Example #20
0
        /// <summary>
        /// Turn on keep alive on a socket.</summary>
        /// <param name="turnOnAfter">
        /// Specifies the timeout, in milliseconds, with no activity until the first keep-alive packet is sent
        /// <param name="keepAliveInterval">
        /// Specifies the interval in milliseconds to send the keep alive packet.</param>
        /// <remarks>The keepAliveInternal doesn't seem to do any difference!</remarks>
        public static bool SetKeepAlive(Socket socket, ulong turnOnAfter, ulong keepAliveInterval)
        {
            int bytesperlong = 4;   // in c++ a long is four bytes long
            int bitsperbyte = 8;

            try
            {
                // Enables or disables the per-connection setting of the TCP keep-alive option which 
                // specifies the TCP keep-alive timeout and interval. The argument structure for 
                // SIO_KEEPALIVE_VALS is specified in the tcp_keepalive structure defined in the Mstcpip.h 
                // header file. This structure is defined as follows: 
                // /* Argument structure for SIO_KEEPALIVE_VALS */
                // struct tcp_keepalive {
                //    u_long  onoff;
                //    u_long  keepalivetime;
                //    u_long  keepaliveinterval;
                //};
                // SIO_KEEPALIVE_VALS is supported on Windows 2000 and later.
                byte[] SIO_KEEPALIVE_VALS = new byte[3 * bytesperlong];
                ulong[] input = new ulong[3];

                // put input arguments in input array
                if (turnOnAfter == 0 || keepAliveInterval == 0) // enable disable keep-alive
                    input[0] = (0UL); // off
                else
                    input[0] = (1UL); // on

                input[1] = (turnOnAfter);
                input[2] = (keepAliveInterval); 

                // pack input into byte struct
                for (int i = 0; i < input.Length; i++)
                {
                    SIO_KEEPALIVE_VALS[i * bytesperlong + 3] = (byte)(input[i] >> ((bytesperlong - 1) * bitsperbyte) & 0xff);
                    SIO_KEEPALIVE_VALS[i * bytesperlong + 2] = (byte)(input[i] >> ((bytesperlong - 2) * bitsperbyte) & 0xff);
                    SIO_KEEPALIVE_VALS[i * bytesperlong + 1] = (byte)(input[i] >> ((bytesperlong - 3) * bitsperbyte) & 0xff);
                    SIO_KEEPALIVE_VALS[i * bytesperlong + 0] = (byte)(input[i] >> ((bytesperlong - 4) * bitsperbyte) & 0xff);
                }
                // create bytestruct for result (bytes pending on server socket)
                byte[] result = BitConverter.GetBytes(0);
                
                // write SIO_VALS to Socket IOControl
                socket.IOControl(IOControlCode.KeepAliveValues, SIO_KEEPALIVE_VALS, result);
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }
Example #21
0
        private void Form1_Load(object sender, EventArgs e)
        {  

            interfaceIPtoListen = Interaction.InputBox("Interface to listen", "Interface to listen", "X.X.X.X", 0, 0);

            mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
            mainSocket.Bind(new IPEndPoint(IPAddress.Parse(interfaceIPtoListen), 0));
            mainSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true);
            byte[] byTrue = new byte[4] { 1, 0, 0, 0 };
            byte[] byOut = new byte[4] { 1, 0, 0, 0 }; 
            mainSocket.IOControl(IOControlCode.ReceiveAll, byTrue, byOut);
            mainSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None,
                        new AsyncCallback(OnReceive), null);
        }
Example #22
0
 public SimpleTcpAdapter(Socket sc)
 {
     _sc = sc;
     _ReadEventArgs = InitEventArgs(OnReadCompleted);
     _WriteEventArgs = InitEventArgs(OnWriteCompleted);
     try {
         sc.IOControl(keepAlive, inValue, null);
     }
     catch {
     }
     var index = Interlocked.Increment(ref __ii);
     index = Math.Abs(index) % _schs.Length;
     _wsch = _schs[index];
 }
        public SignSocketClient()
        {
            ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            ClientSocket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
            

            //  心跳包http://www.cnblogs.com/csMapx/archive/2011/09/04/2166515.html
            uint dummy = 0;
            byte[] inOptionValues = new byte[System.Runtime.InteropServices.Marshal.SizeOf(dummy) * 3];
            BitConverter.GetBytes((uint)1).CopyTo(inOptionValues, 0);//是否启用Keep-Alive
            BitConverter.GetBytes((uint)120000).CopyTo(inOptionValues, System.Runtime.InteropServices.Marshal.SizeOf(dummy));//多长时间开始第一次探测
            BitConverter.GetBytes((uint)120000).CopyTo(inOptionValues, System.Runtime.InteropServices.Marshal.SizeOf(dummy) * 2);//探测时间间隔

            ClientSocket.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null);
            //  相当于如下代码 
            //byte[] buffer = new byte[12];
            //BitConverter.GetBytes(1).CopyTo(buffer, 0);     //  是否启用Keep-Alive
            //BitConverter.GetBytes(1000).CopyTo(buffer, 4);  //  多长时间开始第一次探测
            //BitConverter.GetBytes(1000).CopyTo(buffer, 8);  //  探测时间间隔

            ///  ClientSocket.IOControl(IOControlCode.KeepAliveValues, buffer, null); 
            ///  因此心跳包的设置我们长采用如下代码
            ///  http://blog.csdn.net/educast/article/details/7597829
            ///  http://www.cnblogs.com/csMapx/archive/2011/09/04/2166515.html
            ///  http://www.baidu.com

            
            try
            {
                ClientSocket.Connect(new IPEndPoint(IP, port));
                ClientSocket.ReceiveTimeout = 1000 * 10;            ///  设置连接超时
                Logging.AddLog("服务器连接成功!");

                try
                {
                    byte[] tmp = new byte[1];
                    ClientSocket.Send(tmp, 0, 0);
                }
                catch (SocketException e)
                {
                    Logging.AddLog(e.ToString());
                }
            }
            catch
            {
                Logging.AddLog("服务器未响应!");
            }
        }
        private void Init()
        {
            Debug.Assert(_socket == null);
            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);

            if (_localIp != null)
            {
                _socket.Bind(new IPEndPoint(_localIp, 0));
            }
            _socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true);
            var receiveAllIp = BitConverter.GetBytes(3);
            _socket.IOControl(IOControlCode.ReceiveAll, receiveAllIp, null);
            _socket.ReceiveBufferSize = 1 << 23;
            Task.Run(()=>ReadAsync(_socket));
        }
Example #25
0
        public SnifferSocket(IPEndPoint endPoint)
        {
            byte[] byTrue = new byte[4] { 1, 0, 0, 0 };
            byte[] byOut = new byte[4];

            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
            _socket.ReceiveTimeout = RECEIVE_TIMEOUT;
            _socket.Bind(endPoint);
            //_socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true);
            _socket.IOControl(IOControlCode.ReceiveAll, byTrue, byOut);

            _cts = new CancellationTokenSource();
            CancellationToken ct = _cts.Token;
            Task.Run(() => Listen(ct));
        }
Example #26
0
 //extension removed, Missing System.Core.dll which requires .NET FW 3.5
 /// <summary>
 ///     Sets the Keep-Alive values for the current tcp connection
 /// </summary>
 /// <param name="socket">Current socket instance</param>
 /// <param name="keepAliveInterval">Specifies how often TCP repeats keep-alive transmissions when no response is received. TCP sends keep-alive transmissions to verify that idle connections are still active. This prevents TCP from inadvertently disconnecting active lines.</param>
 /// <param name="keepAliveTime">Specifies how often TCP sends keep-alive transmissions. TCP sends keep-alive transmissions to verify that an idle connection is still active. This entry is used when the remote system is responding to TCP. Otherwise, the interval between transmissions is determined by the value of the keepAliveInterval entry.</param>
 public static void SetKeepAliveEx(Socket socket, uint keepAliveInterval, uint keepAliveTime)
 {
     var keepAlive = new TcpKeepAlive
     {
         onoff = 1,
         keepaliveinterval = keepAliveInterval,
         keepalivetime = keepAliveTime
     };
     int size = Marshal.SizeOf(keepAlive);
     IntPtr keepAlivePtr = Marshal.AllocHGlobal(size);
     Marshal.StructureToPtr(keepAlive, keepAlivePtr, true);
     var buffer = new byte[size];
     Marshal.Copy(keepAlivePtr, buffer, 0, size);
     Marshal.FreeHGlobal(keepAlivePtr);
     socket.IOControl(IOControlCode.KeepAliveValues, buffer, null);
 }
Example #27
0
        public UdpServer(int port)
        {
            receiveAsync = new SocketAsyncEventArgs();
            receiveAsync.Completed += new EventHandler<SocketAsyncEventArgs>(Receive);
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            socket.ReceiveBufferSize = 8 * 1024;
            socket.SendBufferSize = 8 * 1024;
            socket.Bind(new IPEndPoint(IPAddress.Any, port));

            // Ignores connection resets, which isn't all that good but solves the problem for now
            // http://social.microsoft.com/Forums/en-US/netfxnetcom/thread/6b7aa353-259b-4637-b0ae-d4e550c13e38
            uint IOC_IN = 0x80000000;
            uint IOC_VENDOR = 0x18000000;
            uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;
            socket.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null);
        }
Example #28
0
		internal PhysicalSocket()
		{
			_socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
			_socket.DontFragment = true;
			//_socket.Blocking = false;

			// To avoid : "An existing connection was forcibly closed by the remote host"
			uint IOC_IN = 0x80000000;
			uint IOC_VENDOR = 0x18000000;
			uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;
			_socket.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null);

			// Setup a default Send/Rcv buffer size
			_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, 100 * 1024);
			_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, 1000 * 1024);
		}
Example #29
0
        public static void Sniff(int port = 0)
        {
            IPEndPoint localEP = GetLocalEndPort(port);
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);

            if (!TryBindSocket(localEP)) return;

            socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true);

            byte[] byTrue = new byte[4] { 1, 0, 0, 0 };
            socket.IOControl(IOControlCode.ReceiveAll, byTrue, null);

            buffer = new byte[4096];
            working = true;
            socket.BeginReceive(buffer, 0, buffer.Length, 0, HandlePackage, null);
        }
Example #30
0
        public void Initialize()
        {
            ListenPort = Network.IsLookup ? Network.Lookup.Ports.Udp : Core.User.Settings.UdpPort;

            if (Core.Sim != null)
                return;

            UdpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            try
            {
                uint IOC_IN = 0x80000000;
                uint IOC_VENDOR = 0x18000000;
                uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;

                UdpSocket.IOControl((int)SIO_UDP_CONNRESET, new byte[] { 0 }, null);
            }
            catch
            {
                // will fail in mono
            }

            // listen
            bool bound    = false;
            int  attempts = 0;
            while( !bound && attempts < 5)
            {
                try
                {
                    UdpSocket.Bind( new IPEndPoint( System.Net.IPAddress.Any, ListenPort) );
                    bound = true;

                    EndPoint tempSender = (EndPoint) new IPEndPoint(IPAddress.Any, 0);
                    UdpSocket.BeginReceiveFrom(ReceiveBuff, 0, ReceiveBuff.Length, SocketFlags.None, ref tempSender, new AsyncCallback(UdpSocket_Receive), UdpSocket);

                    Network.UpdateLog("Network", "Listening for UDP on port " + ListenPort.ToString());

                }
                catch(Exception ex)
                {
                    Network.UpdateLog("Exception", "UdpHandler::UdpHandler: " + ex.Message);

                    attempts++;
                    ListenPort++;
                }
            }
        }
Example #31
0
        internal PhysicalSocket()
        {
            _socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            _socket.DontFragment = true;
            //_socket.Blocking = false;

            // To avoid : "An existing connection was forcibly closed by the remote host"
            uint IOC_IN            = 0x80000000;
            uint IOC_VENDOR        = 0x18000000;
            uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;

            _socket.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null);

            // Setup a default Send/Rcv buffer size
            _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, 100 * 1024);
            _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, 1000 * 1024);
        }
Example #32
0
        /// <summary>
        /// Starts to listen
        /// </summary>
        /// <param name="config">The server config.</param>
        /// <returns></returns>
        public override bool Start(IServerConfig config)
        {
            SaeState saeState = null;

            try
            {
                m_ListenSocket = new Socket(this.EndPoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
                m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                m_ListenSocket.Bind(this.EndPoint);

                //Mono doesn't support it
                if (Platform.SupportSocketIOControlByCodeEnum)
                {
                    uint IOC_IN = 0x80000000;
                    uint IOC_VENDOR = 0x18000000;
                    uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;

                    byte[] optionInValue = { Convert.ToByte(false) };
                    byte[] optionOutValue = new byte[4];
                    m_ListenSocket.IOControl((int)SIO_UDP_CONNRESET, optionInValue, optionOutValue);
                }

                saeState = m_SaePool.Get();
                var sae = saeState.Sae;
                sae.UserToken = saeState;
                sae.RemoteEndPoint = m_AnyEndPoint;
                sae.Completed += new EventHandler<SocketAsyncEventArgs>(eventArgs_Completed);

                if (!m_ListenSocket.ReceiveFromAsync(sae))
                    eventArgs_Completed(this, sae);

                return true;
            }
            catch (Exception e)
            {
                if (saeState != null)
                {
                    saeState.Sae.Completed -= new EventHandler<SocketAsyncEventArgs>(eventArgs_Completed);
                    m_SaePool.Return(saeState);
                }
                
                OnError(e);
                return false;
            }
        }
Example #33
0
        public void StartSniffingClick(object sender, RoutedEventArgs e)
        {
            if (combInterfaces.Text == "")
            {
                MessageBox.Show("Select an Interface to capture the packets.", nameWindow,
                    MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            try
            {
                if (!bContinueCapturing)
                {
                    startSniffingButton.Content = "Stop";
                    combInterfaces.IsEnabled = false;
                    bContinueCapturing = true;

                    mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw,
                        ProtocolType.IP);
                    //Bind the socket to the selected IP address
                    mainSocket.Bind(new IPEndPoint(IPAddress.Parse(combInterfaces.Text), 0));
                    mainSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true);
                    byte[] byTrue = new byte[4] { 1, 0, 0, 0 };
                    byte[] byOut = new byte[4] { 1, 0, 0, 0 };
                    mainSocket.IOControl(IOControlCode.ReceiveAll, byTrue, byOut);

                    mainSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None,
                        new AsyncCallback(OnReceive), null);
                }
                else
                {
                    startSniffingButton.Content = "Start";
                    combInterfaces.IsEnabled = true;
                    bContinueCapturing = false;
                    //To stop capturing the packets close the socket
                    mainSocket.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, nameWindow, MessageBoxButton.OK,
                    MessageBoxImage.Error);
            }
        }
        /// <summary>
        /// 开启服务端socket监听
        /// </summary>
        public static void ServerSocketListing(SocketConnectConfig sktconfig)
        {
            DicSockectConnection.Clear();
            _cancellationTocken = new CancellationTokenSource();
            if (sktconfig == null)
            {
                sktconfig = new SocketConnectConfig()
                {
                    ServerSocket = ServerSocketListenner
                }
            }
            ;
            else if (sktconfig.ServerSocket == null)
            {
                sktconfig.ServerSocket = ServerSocketListenner;
            }
            Sktconfig = sktconfig;
            try
            {
                if (SocketConnectionClient.SocketClient != null && SocketConnectionClient.SocketClient.Connected)
                {
                    SocketConnectionClient.SocketClientConnection.Disconnect();
                }

                SocketConnectionClient.ClientSocketStarting(connection =>
                {
                    ServerSocketClient = (SocketConnection)connection;
                    SendCurrentConnectionCount();
                }     //监听打开后,发送当前上位机的连接数目信息
                                                            );

                ServerSocketListenner.IOControl(IOControlCode.KeepAliveValues, KeepAlive(1, Sktconfig.KeepAliveTime ?? 2 * 60 * 1000, Sktconfig.KeepAliveTime ?? 2 * 60 * 1000), null); //设置心跳检测
                ServerSocketListenner.BeginAccept(AcceptCallback, sktconfig);
                Task.Run(() =>                                                                                                                                                          //解决主线程直接调用报错
                {
                    ShowMsg($"socket server listening at {ServerSocketListenner.LocalEndPoint}...");
                });
            }
            catch (SocketException se)
            {
                SocketException(ServerSocketListenner, se);
            }
        }
Example #35
0
        public void Create()
        {
            foreach (var endpoint in _settings.IpEndpoint)
            {
                try
                {
                    var socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);

                    socket.Bind(endpoint);
                    socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, 1);
                    var inBytes = new byte[] { 1, 0, 0, 0 };
                    socket.IOControl(IOControlCode.ReceiveAll, inBytes, null);

                    //todo catch exceptions -> iscreated = false if unable to handle exception
                    IsCreated = true;
                    _sockets.Add(socket);
                }
                catch
                {
                    // do not add it to the list
                }
            }
        }
        /// <summary>
        /// Sets the keep-alive interval for the socket.
        /// </summary>
        /// <param name="socket">The socket.</param>
        /// <param name="time">Time between two keep alive "pings".</param>
        /// <param name="interval">Time between two keep alive "pings" when first one fails.</param>
        /// <returns>If the keep alive infos were succefully modified.</returns>
        public static bool SetKeepAlive(this Socket socket, ulong time, ulong interval)
        {
            try
            {
                // Array to hold input values.
                var input = new[]
                {
                    (time == 0 || interval == 0) ? 0UL : 1UL, // on or off
                    time,
                    interval
                };

                // Pack input into byte struct.
                byte[] inValue = new byte[3 * BytesPerLong];
                for (int i = 0; i < input.Length; i++)
                {
                    inValue[i * BytesPerLong + 3] = (byte)(input[i] >> ((BytesPerLong - 1) * BitsPerByte) & 0xff);
                    inValue[i * BytesPerLong + 2] = (byte)(input[i] >> ((BytesPerLong - 2) * BitsPerByte) & 0xff);
                    inValue[i * BytesPerLong + 1] = (byte)(input[i] >> ((BytesPerLong - 3) * BitsPerByte) & 0xff);
                    inValue[i * BytesPerLong + 0] = (byte)(input[i] >> ((BytesPerLong - 4) * BitsPerByte) & 0xff);
                }

                // Create bytestruct for result (bytes pending on server socket).
                byte[] outValue = BitConverter.GetBytes(0);

                // Write SIO_VALS to Socket IOControl.
                socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.KeepAlive, true);
                socket.IOControl(IOControlCode.KeepAliveValues, inValue, outValue);
            }
            catch (SocketException e)
            {
                Console.WriteLine("Failed to set keep-alive: {0} {1}", e.ErrorCode, e);
                return(false);
            }

            return(true);
        }
Example #37
0
 int Utils.Wrappers.Interfaces.ISocket.IOControl(int ioControlCode, byte[] optionInValue, byte[] optionOutValue)
 {
     return(InternalSocket.IOControl(ioControlCode, optionInValue, optionOutValue));
 }
Example #38
0
        private void btnStart_Click(object sender, EventArgs e)
        {
            if (cmbInterfaces.Text == "")
            {
                MessageBox.Show("请选择一个网卡接口进行抓包!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                cmbInterfaces.Focus();
                return;
            }

            try
            {
                _AssumeMaskAddress = System.Text.RegularExpressions.Regex.Replace(cmbInterfaces.Text, "\\.(\\d{1,3})$", ".255");

                if (!bContinueCapturing)
                {
                    //Start capturing the packets...

                    btnStart.Text = "暂停(&S)";

                    bContinueCapturing = true;

                    //For sniffing the socket to capture the packets has to be a raw socket, with the
                    //address family being of type internetwork, and protocol being IP
                    mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);

                    //Bind the socket to the selected IP address
                    mainSocket.Bind(new IPEndPoint(IPAddress.Parse(cmbInterfaces.Text), 0));

                    //Set the socket  options
                    mainSocket.SetSocketOption(SocketOptionLevel.IP,            //Applies only to IP packets
                                               SocketOptionName.HeaderIncluded, //Set the include the header
                                               true);                           //option to true

                    byte[] incoming = new byte[4] {
                        1, 0, 0, 0
                    };
                    byte[] outgoing = new byte[4] {
                        1, 0, 0, 0
                    };

                    //Socket.IOControl is analogous to the WSAIoctl method of Winsock 2
                    mainSocket.IOControl(IOControlCode.ReceiveAll, //Equivalent to SIO_RCVALL constant of Winsock 2
                                         incoming,
                                         outgoing);

                    //Start receiving the packets asynchronously
                    mainSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None,
                                            new AsyncCallback(OnReceive), mainSocket);
                }
                else
                {
                    btnStart.Text      = "抓包(&S)";
                    bContinueCapturing = false;

                    //To stop capturing the packets close the socket
                    if (mainSocket != null)
                    {
                        mainSocket.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex is SocketException)
                {
                    SocketException sEx = (SocketException)ex;
                    if (sEx.SocketErrorCode == SocketError.AccessDenied)
                    {
                        MessageBox.Show("权限不足:请以管理员方式运行本程序!", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show(ex.Message, Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    MessageBox.Show(ex.Message, Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Example #39
-1
        public static bool Initialize()
        {
            try
            {
                EndPoint ep = new IPEndPoint(IPAddress.Any, 0);
                _listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                _listenSocket.Bind(new IPEndPoint(IPAddress.Any, Globals.Config.Udp.Port));

                if (Type.GetType("Mono.Runtime") == null)
                    _listenSocket.IOControl(-1744830452, new byte[] { Convert.ToByte(false) }, null);

                _listenSocket.BeginReceiveFrom(_udpBuffer, 0, _udpBuffer.Length, SocketFlags.None, ref ep, RecieveFromCallback, null);
                return true;
            }
            catch
            {
                return false;
            }
        }