Exemple #1
1
        // Initialize all of the default certificates and protocols
        public SslServer()
        {
            // Initialize the Socket
            serverSocketType = SocketType.Stream;
            serverProtocolType = ProtocolType.Tcp;

            if (Microsoft.SPOT.Hardware.SystemInfo.SystemID.SKU == 3)
            {
                cert = new X509Certificate(CertificatesAndCAs.emuCert, "NetMF");
                ca = new X509Certificate[] { new X509Certificate(CertificatesAndCAs.caEmuCert) };
            }
            else
            {
                // Initialize the SslStream
                cert = new X509Certificate(CertificatesAndCAs.newCert);
                ca = new X509Certificate[] { new X509Certificate(CertificatesAndCAs.caCert) };
            }
            verify = SslVerification.NoVerification;
            sslProtocols = new SslProtocols[] { SslProtocols.Default };

            // Create a TCP/IP (IPv4) socket and listen for incoming connections.
            serverSocket = new Socket(AddressFamily.InterNetwork, serverSocketType, serverProtocolType);
            serverSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, false);

            serverSocket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
            serverEp = (IPEndPoint)serverSocket.LocalEndPoint;

            Debug.Print("Listening for a client to connect...");
            serverSocket.Listen(1);
        }
        private DnsMessage ProcessQuery(DnsMessageBase queryBase, IPAddress clientAddress, ProtocolType protocol)
        {
            DnsMessage query = queryBase as DnsMessage;

            foreach (DnsQuestion q in query.Questions)
            {
                if (q.RecordType == RecordType.A)
                {
                    if (!q.Name.EndsWith(".p2p"))
                    {
                        query.ReturnCode = ReturnCode.Refused;
                        return query;
                    }

                    Console.WriteLine("DNS LOOKUP: " + q.Name);

                    DomainMapping mapping;
                    if (!mappingLookup.TryGetValue(q.Name, out mapping))
                    {
                        query.ReturnCode = ReturnCode.ServerFailure;
                        return query;
                    }

                    query.AnswerRecords.Add(new ARecord(mapping.Name, mapping.TimeToLive.Seconds, mapping.Address));
                    return query;
                }
                else
                    query.ReturnCode = ReturnCode.NotImplemented;
            }

            return query;
        }
		/// <summary>
		///   Creates a new instance of the WksRecord class
		/// </summary>
		/// <param name="name"> Name of the host </param>
		/// <param name="timeToLive"> Seconds the record should be cached at most </param>
		/// <param name="address"> IP address of the host </param>
		/// <param name="protocol"> Type of the protocol </param>
		/// <param name="ports"> List of ports which are supported by the host </param>
		public WksRecord(DomainName name, int timeToLive, IPAddress address, ProtocolType protocol, List<ushort> ports)
			: base(name, RecordType.Wks, RecordClass.INet, timeToLive)
		{
			Address = address ?? IPAddress.None;
			Protocol = protocol;
			Ports = ports ?? new List<ushort>();
		}
		/// <summary>
		///   Creates a new instance of the DiffieHellmanKeyRecord class
		/// </summary>
		/// <param name="name"> Name of the record </param>
		/// <param name="recordClass"> Class of the record </param>
		/// <param name="timeToLive"> Seconds the record should be cached at most </param>
		/// <param name="flags"> Flags of the key </param>
		/// <param name="protocol"> Protocol for which the key is used </param>
		/// <param name="prime"> Binary data of the prime of the key </param>
		/// <param name="generator"> Binary data of the generator of the key </param>
		/// <param name="publicValue"> Binary data of the public value </param>
		public DiffieHellmanKeyRecord(string name, RecordClass recordClass, int timeToLive, ushort flags, ProtocolType protocol, byte[] prime, byte[] generator, byte[] publicValue)
			: base(name, recordClass, timeToLive, flags, protocol, DnsSecAlgorithm.DiffieHellman)
		{
			Prime = prime ?? new byte[] { };
			Generator = generator ?? new byte[] { };
			PublicValue = publicValue ?? new byte[] { };
		}
Exemple #5
0
        /// <summary>
        /// 
        /// </summary>
        public SocketAsyncClient(IPEndPoint remoteEndPoint, int bufferSize, AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
        {
            _remoteEndPoint = remoteEndPoint;
            _client = new Socket(addressFamily, socketType, protocolType);
            socketObject = new SocketObject(Guid.NewGuid(), _client);
            int maxConnection = 1;
            int numOfSaeaForRecSend = maxConnection * OpsToPreAlloc;
            _readWritePool = new SocketAsyncPool(numOfSaeaForRecSend);
            int numSize = numOfSaeaForRecSend * bufferSize;
            _bufferManager = new BufferManager(numSize, bufferSize);
            _bufferManager.InitBuffer();

            _saeaProxy = new SocketAsyncEventArgsProxy(bufferSize);
            _saeaProxy.ReceiveCompleted += OnReceiveCompleted;
            _saeaProxy.SendCompleted += OnSendCompleted;
            _saeaProxy.ClosedHandle += OnSocketClosing;

            SocketAsyncEventArgs saea;
            for (int i = 0; i < numOfSaeaForRecSend; i++)
            {
                saea = _saeaProxy.CreateNewSaea();
                _bufferManager.SetBuffer(saea);
                saea.UserToken = new DataToken(saea.Offset);
                _readWritePool.Push(saea);
            }
        }
        /// <summary>
        /// Initializes the socket
        /// </summary>`
        public void init(int offset, string ipAddress)
        {
            socketType = SocketType.Stream;
            protocolType = ProtocolType.Tcp;
            //addressFamily = AddressFamily.InterNetwork;
            addressFamily = AddressFamily.InterNetwork;
            try
            {
                ipEntry = Dns.GetHostEntry(Dns.GetHostName());
                IPAddress[] addr = ipEntry.AddressList;
                //endpoint = new IPEndPoint(addr[0], port);
                for (int i = 0; i < addr.Length; i++)
                {
                    Console.WriteLine("IP Address {0}: {1} ", i, addr[i].ToString());
                }
                if (ipAddress == "")
                {
                    address = addr[addr.Length - offset];
                }
                else
                {
                    address = IPAddress.Parse(ipAddress);
                }
                Console.WriteLine("Using the Address {0}: {1}", address.ToString(), port);
                endpoint = new IPEndPoint(address, port);
            }
            catch (SocketException ex)
            {
                System.Console.WriteLine(ex.Message);
            }
            createSocket();

        }
		public NetworkInformationConnection(
			string       host,
			int          port,
			ProtocolType protocol,
			int          timeout
		)
		{
			if (string.IsNullOrWhiteSpace(host))
			{
				throw new ArgumentNullException("host");
			}

			if (port < 0 || port > short.MaxValue)
			{
				throw new ArgumentOutOfRangeException("port");
			}

			if (timeout < 0)
			{
				throw new ArgumentOutOfRangeException("timeout");
			}

			this.Host     = host;
			this.Port     = port;
			this.Protocol = protocol;
			this.Timeout  = timeout;
		}
 public SocketManager(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
 {
     _addressFamily = addressFamily;
     _socketType = socketType;
     _protocolType = protocolType;
     _listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 }
Exemple #9
0
        public static Socket GetNewSocket(ProtocolType type, EndPoint ep)
        {
            Socket sock = new Socket( AddressFamily.InterNetwork, SocketType.Stream, type );

            sock.Bind( ep );
            return sock;
        }
Exemple #10
0
        public static unsafe SafeCloseSocket CreateSocket(SocketInformation socketInformation, out AddressFamily addressFamily, out SocketType socketType, out ProtocolType protocolType)
        {
            SafeCloseSocket handle;
            Interop.Winsock.WSAPROTOCOL_INFO protocolInfo;

            fixed (byte* pinnedBuffer = socketInformation.ProtocolInformation)
            {
                handle = SafeCloseSocket.CreateWSASocket(pinnedBuffer);
                protocolInfo = (Interop.Winsock.WSAPROTOCOL_INFO)Marshal.PtrToStructure<Interop.Winsock.WSAPROTOCOL_INFO>((IntPtr)pinnedBuffer);
            }

            if (handle.IsInvalid)
            {
                SocketException e = new SocketException();
                if (e.SocketErrorCode == SocketError.InvalidArgument)
                {
                    throw new ArgumentException(SR.net_sockets_invalid_socketinformation, "socketInformation");
                }
                else
                {
                    throw e;
                }
            }

            addressFamily = protocolInfo.iAddressFamily;
            socketType = (SocketType)protocolInfo.iSocketType;
            protocolType = (ProtocolType)protocolInfo.iProtocol;
            return handle;
        }
Exemple #11
0
            public IPPacket(byte[] buffer)
            {
                try
                {
                    byte versionAndHeaderLength = buffer[0];
                    Version = (versionAndHeaderLength >> 4) == 4 ? ProtocolFamily.InterNetwork : ProtocolFamily.InterNetworkV6;
                    HeaderLength = (byte)((versionAndHeaderLength & 15) * 4); // 0b1111 = 15

                    Protocol = (ProtocolType)buffer[9];

                    SourceIPAddress = new IPAddress(BitConverter.ToUInt32(buffer, 12));
                    DestinationIPAddress = new IPAddress(BitConverter.ToUInt32(buffer, 16));

                    Data = buffer.Skip(HeaderLength).ToArray();

                    IsValid = true;
                }
                catch (Exception ex)
                {
                    Version = ProtocolFamily.Unknown;
                    HeaderLength = 0;

                    Protocol = ProtocolType.Unknown;

                    SourceIPAddress = null;
                    DestinationIPAddress = null;

                    Data = null;

                    IsValid = false;
                    Log.Ex(ex, "IP 패킷 파싱 에러");
                }
            }
		private IntPtr Socket_internal(AddressFamily family,
		SocketType type,
		ProtocolType proto,
		out int error)
		{
			throw new System.NotImplementedException();
		}
Exemple #13
0
    /// <summary>
    /// 
    /// </summary>
    /// <param name="intPort"></param>
    /// <returns></returns>
    public bool Host(int intPort, ProtocolType protocolType)
    {
        Debug.Log("Hosting on port " + intPort);

        if (protocolType == ProtocolType.Udp)
        {
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, protocolType);
        }
        else
        {
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, protocolType);
        }

        try
        {
            socket.Bind(new IPEndPoint(IPAddress.Parse(ViewerConstants.LocalHost), intPort));
            socket.Listen(kHostConnectionBacklog);
            socket.BeginAccept(new System.AsyncCallback(OnClientConnect), socket);
        }
        catch (System.Exception e)
        {
            Debug.LogError("Exception when attempting to host (" + intPort + "): " + e);

            socket = null;

            return false;
        }

        return true;
    }
 public Client(IPAddress ip, int port, ProtocolType protocol = ProtocolType.Tcp, string connectionKey = "")
 {
     initialized = false;
     key = System.Text.Encoding.UTF8.GetBytes(connectionKey);
     client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, protocol);
     Initialize(ip, port);
 }
        public byte[] Build(string host, NsType queryType, NsClass queryClass, ProtocolType protocol)
        {
            // Combind the NsFlags with our constant flags
            const ushort flags = (ushort)((ushort)QueryResponse.Query | (ushort)OpCode.QUERY | (ushort)NsFlags.RD);

            var bDnsQuery = GetMessageBytes(
                (ushort)_random.Next(),
                flags,
                1,
                0,
                0,
                host,
                queryType,
                queryClass);

            // Add two byte prefix that contains the packet length per RFC 1035 section 4.2.2
            if (protocol == ProtocolType.Tcp)
            {
                // 4.2.2. TCP usageMessages sent over TCP connections use server port 53 (decimal).  
                // The message is prefixed with a two byte length field which gives the message 
                // length, excluding the two byte length field.  This length field allows the 
                // low-level processing to assemble a complete message before beginning to parse 
                // it.
                var len = bDnsQuery.Length;
                Array.Resize<byte>(ref bDnsQuery, len + 2);
                Array.Copy(bDnsQuery, 0, bDnsQuery, 2, len);
                bDnsQuery[0] = (byte)((len >> 8) & 0xFF);
                bDnsQuery[1] = (byte)((len & 0xFF));
            }

            return bDnsQuery;
        }
Exemple #16
0
 private Socket(AddressFamily family, SocketType type, ProtocolType proto, IntPtr native)
 {
     this.family = family;
     this.type = type;
     this.proto = proto;
     this.native = native;
 }
Exemple #17
0
 /// <summary>
 /// Initializes a new instance of the ProxySocket class.
 /// </summary>
 /// <param name="addressFamily">One of the AddressFamily values.</param>
 /// <param name="socketType">One of the SocketType values.</param>
 /// <param name="protocolType">One of the ProtocolType values.</param>
 /// <param name="proxyUsername">The username to use when authenticating with the proxy server.</param>
 /// <param name="proxyPassword">The password to use when authenticating with the proxy server.</param>
 /// <exception cref="SocketException">The combination of addressFamily, socketType, and protocolType results in an invalid socket.</exception>
 /// <exception cref="ArgumentNullException"><c>proxyUsername</c> -or- <c>proxyPassword</c> is null.</exception>
 public ProxySocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, string proxyUsername, string proxyPassword)
     : base(addressFamily, socketType, protocolType)
 {
     ProxyUser = proxyUsername;
     ProxyPass = proxyPassword;
     ToThrow = new InvalidOperationException();
 }
 /// <summary>
 /// Creates a new instance of the WksRecord class.
 /// </summary>
 /// <param name="name">Name of the host.</param>
 /// <param name="timeToLive">Seconds the record should be cached at most.</param>
 /// <param name="address">IP address of the host.</param>
 /// <param name="protocol">Type of the protocol.</param>
 /// <param name="ports">List of ports which are supported by the host.</param>
 public WksRecord(string name, int timeToLive, IPAddress address, ProtocolType protocol, List<ushort> ports)
     : base(name, RecordType.Wks, RecordClass.INet, timeToLive)
 {
     this.Address = address ?? IPAddress.None;
     this.Protocol = protocol;
     this.Ports = ports ?? new List<ushort>();
 }
Exemple #19
0
	public TCPClient(string ip,int point,SocketType socketType=SocketType.Stream,ProtocolType protocolType=ProtocolType.Tcp)
	{
		this.ip=ip;
		this.point=point;
		this.protocolType =protocolType;
		this.socketType=socketType;
	}
Exemple #20
0
        public SocketServer(int portNumber, AddressFamily addressFamily, SocketType socketType,
            ProtocolType protocolType)
        {
            this.portNumber = portNumber;
            this.addressFamily = addressFamily;
            this.socketType = socketType;
            this.protocolType = protocolType;

            clientAddresses = new List<string>();
            clientTable = new Dictionary<string, StateObject>();
            recentlyReceivedStates = new List<StateObject>();
            removeList = new List<string>();

            listenEvent = new ManualResetEvent(false);
            shutDownEvent = new ManualResetEvent(false);
            sendEvent = new ManualResetEvent(false);

            listener = null;
            sendBufferSize = INITIAL_BUFFER_SIZE;
            recvBufferSize = INITIAL_BUFFER_SIZE;
            ShutdownWaitTimeout = 5000;

            enableEncryption = false;
            initialized = false;
            copyingRecvBuffer = false;
            isShuttingDown = false;
            transmittingData = false;
            receivingData = false;
        }
Exemple #21
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CMClient"/> class with a specific connection type.
        /// </summary>
        /// <param name="type">The connection type to use.</param>
        /// <exception cref="NotSupportedException">
        /// The provided <see cref="ProtocolType"/> is not supported.
        /// Only Tcp and Udp are available.
        /// </exception>
        public CMClient( ProtocolType type = ProtocolType.Tcp )
        {
            serverMap = new Dictionary<EServerType, List<IPEndPoint>>();

            switch ( type )
            {
                case ProtocolType.Tcp:
                    connection = new TcpConnection();
                    break;

                case ProtocolType.Udp:
                    connection = new UdpConnection();
                    break;

                default:
                    throw new NotSupportedException( "The provided protocol type is not supported. Only Tcp and Udp are available." );
            }

            connection.NetMsgReceived += NetMsgReceived;
            connection.Disconnected += Disconnected;
            connection.Connected += Connected;
            heartBeatFunc = new ScheduledFunction( () =>
            {
                Send( new ClientMsgProtobuf<CMsgClientHeartBeat>( EMsg.ClientHeartBeat ) );
            } );
        }
Exemple #22
0
 public ServerAcceptor(SocketType socketType, ProtocolType protocolType, ISocketAsyncEventArgsPool acceptorPool, Func<SocketAsyncEventArgs> acceptorFactory)
 {
     this.socketType = socketType;
     this.protocolType = protocolType;
     this.acceptorPool = acceptorPool;
     this.acceptorFactory = acceptorFactory;
 }
Exemple #23
0
        public IPHeader(byte[] byBuffer, int nReceived)
        {
            NetBinaryReader nbr = new NetBinaryReader(byBuffer, 0, nReceived);

            Version = nbr.ReadNible();
            HeaderLength = nbr.ReadNible();

            Precedence = (Precedence)nbr.ReadCustomAmount(3);
            LowDelay = nbr.ReadBit();
            HighThroughput = nbr.ReadBit();
            HighRelibility = nbr.ReadBit();
            nbr.SkipPadBits();

            TotalLength = nbr.ReadUInt16();
            Identification = nbr.ReadUInt16();

            nbr.ReadBit();
            MayFragment = !nbr.ReadBit();
            LastFragment = !nbr.ReadBit();
            FragmentOffset = (nbr.ReadPadBits() << 3) + nbr.ReadByte();

            TTL = nbr.ReadByte();
            Protocol = (ProtocolType)nbr.ReadByte();
            HeaderChecksum = IPAddress.NetworkToHostOrder(nbr.ReadInt16());

            Source = new IPAddress(nbr.ReadBytes(4));
            Destination = new IPAddress(nbr.ReadBytes(4));
        }
Exemple #24
0
			public void Reset (Socket socket, IPEndPoint ip)
			{
				this.addressFamily = socket.AddressFamily;
				this.socketType = socket.SocketType;
				this.protocolTtype = socket.ProtocolType;
				this.RemoteEndPoint = ip;
			}
 public NetworkDevice(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, EndPoint endPoint)
 {
     _AddressFamily = addressFamily;
     _SocketType = socketType;
     _ProtocolType = protocolType;
     _EndPoint = endPoint;
 }
Exemple #26
0
 public VNESBase(IPAddress ip, int port, ProtocolType protocol)
 {
     this.ip = ip;
     this.port = port;
     this.protocol = protocol;
     this.filter = this.BuildFilter();
 }
 /// <summary>
 /// 戻り値をAppVarで取得する通信。
 /// </summary>
 /// <param name="invoker">呼び出し元。</param>
 /// <param name="friendlyConnector">アプリケーションとの接続者。</param>
 /// <param name="protocolType">通信タイプ。</param>
 /// <param name="operationTypeInfo">操作タイプ情報。</param>
 /// <param name="varAddress">変数アドレス。</param>
 /// <param name="typeFullName">タイプフルネーム。</param>
 /// <param name="operation">操作名称。</param>
 /// <param name="arguments">引数。</param>
 /// <returns>変数。</returns>
 internal static AppVar SendAndVarReceive(object invoker, IFriendlyConnector friendlyConnector, ProtocolType protocolType,
     OperationTypeInfo operationTypeInfo, VarAddress varAddress, string typeFullName, string operation, object[] arguments)
 {
     object value = SendAndValueReceive(invoker, friendlyConnector, protocolType, operationTypeInfo, varAddress, typeFullName, operation, arguments);
     VarAddress retHandle = value as VarAddress;
     return (retHandle == null) ? (null) : (new AppVar(friendlyConnector, retHandle));
 }
Exemple #28
0
        public static async Task<IDisposableConnection<ArraySegment<byte>>> CreateConnection(
            EndPoint endpoint,
            SocketType socketType = SocketType.Stream,
            ProtocolType protocolType = ProtocolType.Tcp)
        {
            var socket = new Socket(socketType, protocolType);
            bool disposeSocket = false;
            try
            {                
                using (SocketAwaitableEventArgs args = new SocketAwaitableEventArgs())
                {
                    args.RemoteEndPoint = endpoint;
                    await socket.ConnectSocketAsync(args);
                }
            }
            catch (Exception)
            {
                disposeSocket = true;
                throw;
            }
            finally
            {
                if (disposeSocket)
                {
                    socket.Dispose();
                    socket = null;
                }
            }

            return socket.ToConnection();
        }
Exemple #29
0
 public Socket CreateSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
 {
     SetAddressFamily(addressFamily);
     SetProtocolType(protocolType);
     SetSocketType(socketType);
     return new Socket(this.addressFamily, this.socketType, this.protocolType);
 }
Exemple #30
0
	public P2PServer(int point,SocketType socketType=SocketType.Dgram,ProtocolType protocolType=ProtocolType.Udp)
	{
		this.point=point;
		this.protocolType =protocolType;
		this.socketType=socketType;
	
	}
Exemple #31
0
 protected WcfTwoWayAdapterBase(ProtocolType protocolType) : base(protocolType)
 {
 }
 /// <summary>
 /// 网络初始化
 /// </summary>
 /// <typeparam name="TProtocol">协议处理类</typeparam>
 /// <typeparam name="TSocket">Socket类</typeparam>
 /// <param name="protocolType">通讯协议</param>
 public static void Init <TProtocol, TSocket>(ProtocolType protocolType = ProtocolType.Tcp) where TProtocol : INetworkInterface, new() where TSocket : SocketBase, new()
 {
     Init <TProtocol, TSocket>(null, protocolType);
 }
        /// <summary>验证数据,通过抛出异常的方式提示验证失败。</summary>
        /// <param name="isNew">是否插入</param>
        public override void Valid(Boolean isNew)
        {
            // 如果没有脏数据,则不需要进行任何处理
            if (!HasDirty)
            {
                return;
            }

            // 这里验证参数范围,建议抛出参数异常,指定参数名,前端用户界面可以捕获参数异常并聚焦到对应的参数输入框
            if (ClientId.IsNullOrEmpty())
            {
                throw new ArgumentNullException(nameof(ClientId), "ClientId不能为空!");
            }
            if (ProtocolType.IsNullOrEmpty())
            {
                throw new ArgumentNullException(nameof(ProtocolType), "ProtocolType不能为空!");
            }
            if (ClientName.IsNullOrEmpty())
            {
                throw new ArgumentNullException(nameof(ClientName), "ClientName不能为空!");
            }
            if (Description.IsNullOrEmpty())
            {
                throw new ArgumentNullException(nameof(Description), "Description不能为空!");
            }
            if (ClientUri.IsNullOrEmpty())
            {
                throw new ArgumentNullException(nameof(ClientUri), "ClientUri不能为空!");
            }
            if (LogoUri.IsNullOrEmpty())
            {
                throw new ArgumentNullException(nameof(LogoUri), "LogoUri不能为空!");
            }
            if (FrontChannelLogoutUri.IsNullOrEmpty())
            {
                throw new ArgumentNullException(nameof(FrontChannelLogoutUri), "FrontChannelLogoutUri不能为空!");
            }
            if (BackChannelLogoutUri.IsNullOrEmpty())
            {
                throw new ArgumentNullException(nameof(BackChannelLogoutUri), "BackChannelLogoutUri不能为空!");
            }
            if (ClientClaimsPrefix.IsNullOrEmpty())
            {
                throw new ArgumentNullException(nameof(ClientClaimsPrefix), "ClientClaimsPrefix不能为空!");
            }
            if (PairWiseSubjectSalt.IsNullOrEmpty())
            {
                throw new ArgumentNullException(nameof(PairWiseSubjectSalt), "PairWiseSubjectSalt不能为空!");
            }
            if (Created.IsNullOrEmpty())
            {
                throw new ArgumentNullException(nameof(Created), "Created不能为空!");
            }
            if (Updated.IsNullOrEmpty())
            {
                throw new ArgumentNullException(nameof(Updated), "Updated不能为空!");
            }
            if (LastAccessed.IsNullOrEmpty())
            {
                throw new ArgumentNullException(nameof(LastAccessed), "LastAccessed不能为空!");
            }
            if (UserCodeType.IsNullOrEmpty())
            {
                throw new ArgumentNullException(nameof(UserCodeType), "UserCodeType不能为空!");
            }

            // 在新插入数据或者修改了指定字段时进行修正

            // 检查唯一索引
            // CheckExist(isNew, __.ClientId);
        }
Exemple #34
0
 public ISocket New_Socket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
 {
     return(client.aClient.GetSharedClass <ISocket>(typeof(Lite_Socket), addressFamily, socketType, protocolType));
 }
 /// <summary>
 ///   Creates a new instance of the DiffieHellmanKeyRecord class
 /// </summary>
 /// <param name="name"> Name of the record </param>
 /// <param name="recordClass"> Class of the record </param>
 /// <param name="timeToLive"> Seconds the record should be cached at most </param>
 /// <param name="flags"> Flags of the key </param>
 /// <param name="protocol"> Protocol for which the key is used </param>
 /// <param name="prime"> Binary data of the prime of the key </param>
 /// <param name="generator"> Binary data of the generator of the key </param>
 /// <param name="publicValue"> Binary data of the public value </param>
 public DiffieHellmanKeyRecord(string name, RecordClass recordClass, int timeToLive, ushort flags, ProtocolType protocol, byte[] prime, byte[] generator, byte[] publicValue)
     : base(name, recordClass, timeToLive, flags, protocol, DnsSecAlgorithm.DiffieHellman)
 {
     Prime       = prime ?? new byte[] { };
     Generator   = generator ?? new byte[] { };
     PublicValue = publicValue ?? new byte[] { };
 }
Exemple #36
0
        private async Task <DnsMessageBase> ProcessMessageAsync(DnsMessageBase query, ProtocolType protocolType, IPEndPoint remoteEndpoint)
        {
            if (query.TSigOptions != null)
            {
                switch (query.TSigOptions.ValidationResult)
                {
                case ReturnCode.BadKey:
                case ReturnCode.BadSig:
                    query.IsQuery             = false;
                    query.ReturnCode          = ReturnCode.NotAuthoritive;
                    query.TSigOptions.Error   = query.TSigOptions.ValidationResult;
                    query.TSigOptions.KeyData = null;

#pragma warning disable 4014
                    InvalidSignedMessageReceived.RaiseAsync(this, new InvalidSignedMessageEventArgs(query, protocolType, remoteEndpoint));
#pragma warning restore 4014

                    return(query);

                case ReturnCode.BadTime:
                    query.IsQuery               = false;
                    query.ReturnCode            = ReturnCode.NotAuthoritive;
                    query.TSigOptions.Error     = query.TSigOptions.ValidationResult;
                    query.TSigOptions.OtherData = new byte[6];
                    int tmp = 0;
                    TSigRecord.EncodeDateTime(query.TSigOptions.OtherData, ref tmp, DateTime.Now);

#pragma warning disable 4014
                    InvalidSignedMessageReceived.RaiseAsync(this, new InvalidSignedMessageEventArgs(query, protocolType, remoteEndpoint));
#pragma warning restore 4014

                    return(query);
                }
            }

            QueryReceivedEventArgs eventArgs = new QueryReceivedEventArgs(query, protocolType, remoteEndpoint);
            await QueryReceived.RaiseAsync(this, eventArgs);

            return(eventArgs.Response);
        }
Exemple #37
0
        protected internal virtual ISocket CreateSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
        {
            var proxy = new SocketProxy(addressFamily, socketType, protocolType);

            Uri uri;

            if (Uri.TryCreate(Address, UriKind.Absolute, out uri) &&
                uri.Host.Equals(IPAddress.Broadcast.ToString(), StringComparison.OrdinalIgnoreCase))
            {
                proxy.UnderlyingSocket.EnableBroadcast = true;
            }

            return(proxy);
        }
Exemple #38
0
        public static void Remove(int eport, ProtocolType type)
        {
            var mapping = new UPnPNAT().StaticPortMappingCollection;

            mapping.Remove(eport, type.ToString().ToUpper());
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="SocketProxy"/> class.
 /// </summary>
 /// <param name="addressFamily">The address family.</param>
 /// <param name="socketType">Type of the socket.</param>
 /// <param name="protocolType">Type of the protocol.</param>
 internal SocketProxy(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
 {
     _socket = new Socket(addressFamily, socketType, protocolType);
 }
 public static void Init <T>(ProtocolType protocolType = ProtocolType.Tcp) where T : INetworkInterface, new()
 {
     Init <T, SocketService>();
 }
Exemple #41
0
 public TestLabelsInfoCollector(ProtocolType protocolType)
 {
     TestLabelsInfo = new TestLabelsInfo();
     TypeClassBP    = Type.GetType("NetcoreDbgTest." + protocolType.ToString() + "."
                                   + protocolType.ToString() + "LineBreakpoint");
 }
Exemple #42
0
        public ControlScript(string pathToTestFiles, ProtocolType protocolType)
        {
            ControlScriptDummyText =
                @"using System;
using System.IO;
using System.Diagnostics;
using System.Collections.Generic;
using NetcoreDbgTest;
using NetcoreDbgTest.Script;
using Newtonsoft.Json;
using NetcoreDbgTest." + protocolType.ToString() + @";

namespace NetcoreDbgTest.Script
{
}

namespace NetcoreDbgTestCore
{
    public class GeneratedScript
    {
        static Context m_Context;

        public static void Setup(ControlInfo controlInfo, DebuggerClient debuggerClient)
        {
            m_Context = new Context(controlInfo, debuggerClient);
        }

        public static void ExecuteCheckPoints() {}

        public static void Invoke(string id, string next_id, Checkpoint checkpoint)
        {
            checkpoint(m_Context);
        }
    }
}";

            // we may have list of files separated by ';' symbol
            string[]          pathToFiles = pathToTestFiles.Split(';');
            List <SyntaxTree> trees       = new List <SyntaxTree>();

            foreach (string pathToFile in pathToFiles)
            {
                if (String.IsNullOrEmpty(pathToFile))
                {
                    continue;
                }

                // Read file text and replace __FILE__ and __LINE__ markers.
                string[]      lines   = File.ReadAllLines(pathToFile);
                List <string> list    = new List <string>();
                int           lineNum = 1;
                foreach (string line in lines)
                {
                    list.Add(line.Replace("__LINE__", lineNum.ToString()));
                    lineNum++;
                }
                string testSource = String.Join("\n", list.ToArray()).Replace("__FILE__", pathToFile);

                SyntaxTree testTree = CSharpSyntaxTree.ParseText(testSource)
                                      .WithFilePath(pathToFile);
                trees.Add(testTree);
            }

            TestLabelsInfo     = CollectTestLabelsInfo(trees, protocolType);
            ScriptDeclarations = CollectScriptDeclarations(trees);
            SyntaxTree         = BuildTree();
            Compilation compilation    = CompileTree(SyntaxTree);
            Assembly    scriptAssembly = MakeAssembly(compilation);

            generatedScriptClass = scriptAssembly.GetType("NetcoreDbgTestCore.GeneratedScript");
            Breakpoints          = TestLabelsInfo.Breakpoints;
        }
Exemple #43
0
 public ChannelProfile()
 {
     _sshPort  = 22;
     _authType = AuthenticationType.Password;
     _protocol = ProtocolType.Tcp;
 }
Exemple #44
0
 public XSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType) : base(addressFamily, socketType, protocolType)
 {
 }
Exemple #45
0
 private DynamicWinsockMethods(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
 {
     _addressFamily = addressFamily;
     _socketType    = socketType;
     _protocolType  = protocolType;
     _lockObject    = new object();
 }
Exemple #46
0
        private async Task <PingReply> SendIcmpEchoRequestOverRawSocket(IPAddress address, byte[] buffer, int timeout, PingOptions options)
        {
            EndPoint endPoint = new IPEndPoint(address, 0);

            bool         isIpv4       = address.AddressFamily == AddressFamily.InterNetwork;
            ProtocolType protocolType = isIpv4 ? ProtocolType.Icmp : ProtocolType.IcmpV6;
            // Use the current thread's ID as the identifier.
            ushort     identifier = (ushort)Environment.CurrentManagedThreadId;
            IcmpHeader header     = new IcmpHeader()
            {
                Type           = isIpv4 ? (byte)IcmpV4MessageType.EchoRequest : (byte)IcmpV6MessageType.EchoRequest,
                Code           = 0,
                HeaderChecksum = 0,
                Identifier     = identifier,
                SequenceNumber = 0,
            };

            byte[] sendBuffer = CreateSendMessageBuffer(header, buffer);

            using (Socket socket = new Socket(address.AddressFamily, SocketType.Raw, protocolType))
            {
                socket.ReceiveTimeout = timeout;
                socket.SendTimeout    = timeout;
                // Setting Socket.DontFragment and .Ttl is not supported on Unix, so ignore the PingOptions parameter.

                int ipHeaderLength = isIpv4 ? IpHeaderLengthInBytes : 0;
                await socket.SendToAsync(new ArraySegment <byte>(sendBuffer), SocketFlags.None, endPoint).ConfigureAwait(false);

                byte[] receiveBuffer = new byte[ipHeaderLength + IcmpHeaderLengthInBytes + buffer.Length];

                long      elapsed;
                Stopwatch sw = Stopwatch.StartNew();
                // Read from the socket in a loop. We may receive messages that are not echo replies, or that are not in response
                // to the echo request we just sent. We need to filter such messages out, and continue reading until our timeout.
                // For example, when pinging the local host, we need to filter out our own echo requests that the socket reads.
                while ((elapsed = sw.ElapsedMilliseconds) < timeout)
                {
                    Task <SocketReceiveFromResult> receiveTask = socket.ReceiveFromAsync(
                        new ArraySegment <byte>(receiveBuffer),
                        SocketFlags.None,
                        endPoint);
                    var  cts      = new CancellationTokenSource();
                    Task finished = await Task.WhenAny(receiveTask, Task.Delay(timeout - (int)elapsed, cts.Token)).ConfigureAwait(false);

                    cts.Cancel();
                    if (finished != receiveTask)
                    {
                        sw.Stop();
                        return(CreateTimedOutPingReply());
                    }

                    SocketReceiveFromResult receiveResult = receiveTask.GetAwaiter().GetResult();
                    int bytesReceived = receiveResult.ReceivedBytes;
                    if (bytesReceived - ipHeaderLength < IcmpHeaderLengthInBytes)
                    {
                        continue; // Not enough bytes to reconstruct IP header + ICMP header.
                    }

                    byte type, code;
                    unsafe
                    {
                        fixed(byte *bytesPtr = receiveBuffer)
                        {
                            int        icmpHeaderOffset = ipHeaderLength;
                            IcmpHeader receivedHeader   = *((IcmpHeader *)(bytesPtr + icmpHeaderOffset)); // Skip IP header.

                            type = receivedHeader.Type;
                            code = receivedHeader.Code;

                            if (identifier != receivedHeader.Identifier ||
                                type == (byte)IcmpV4MessageType.EchoRequest ||
                                type == (byte)IcmpV6MessageType.EchoRequest)    // Echo Request, ignore
                            {
                                continue;
                            }
                        }
                    }

                    sw.Stop();
                    long roundTripTime = sw.ElapsedMilliseconds;
                    int  dataOffset    = ipHeaderLength + IcmpHeaderLengthInBytes;
                    // We want to return a buffer with the actual data we sent out, not including the header data.
                    byte[] dataBuffer = new byte[bytesReceived - dataOffset];
                    Buffer.BlockCopy(receiveBuffer, dataOffset, dataBuffer, 0, dataBuffer.Length);

                    IPStatus status = isIpv4
                                        ? IcmpV4MessageConstants.MapV4TypeToIPStatus(type, code)
                                        : IcmpV6MessageConstants.MapV6TypeToIPStatus(type, code);

                    return(new PingReply(address, options, status, roundTripTime, dataBuffer));
                }

                // We have exceeded our timeout duration, and no reply has been received.
                sw.Stop();
                return(CreateTimedOutPingReply());
            }
        }
 public ProxyEncryptSocket(AddressFamily af, SocketType type, ProtocolType protocol)
 {
     _socket = new Socket(af, type, protocol);
 }
Exemple #48
0
        public static DynamicWinsockMethods GetMethods(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
        {
            lock (s_methodTable)
            {
                DynamicWinsockMethods methods;

                for (int i = 0; i < s_methodTable.Count; i++)
                {
                    methods = s_methodTable[i];
                    if (methods._addressFamily == addressFamily && methods._socketType == socketType && methods._protocolType == protocolType)
                    {
                        return(methods);
                    }
                }

                methods = new DynamicWinsockMethods(addressFamily, socketType, protocolType);
                s_methodTable.Add(methods);
                return(methods);
            }
        }
Exemple #49
0
 public MelsecEthClient(ProtocolType protocoltype, string ip, ushort port, int receiveTimeout, int sendTimeout)
     : base(protocoltype, ip, port, receiveTimeout, sendTimeout)
 {
 }
 public ProxySocketTunLocal(AddressFamily af, SocketType type, ProtocolType protocol)
     : base(af, type, protocol)
 {
 }
Exemple #51
0
 protected ReactorBase(IPAddress localAddress, int localPort, NetworkEventLoop eventLoop, IMessageEncoder encoder, IMessageDecoder decoder, IByteBufAllocator allocator, SocketType socketType = SocketType.Stream, ProtocolType protocol = ProtocolType.Tcp, int bufferSize = NetworkConstants.DEFAULT_BUFFER_SIZE)
 {
     Decoder       = decoder;
     Encoder       = encoder;
     Allocator     = allocator;
     LocalEndpoint = new IPEndPoint(localAddress, localPort);
     Listener      = new Socket(AddressFamily.InterNetwork, socketType, protocol);
     if (protocol == ProtocolType.Tcp)
     {
         Transport = TransportType.Tcp;
     }
     else if (protocol == ProtocolType.Udp)
     {
         Transport = TransportType.Udp;
     }
     Backlog           = NetworkConstants.DefaultBacklog;
     EventLoop         = eventLoop;
     ConnectionAdapter = new ReactorConnectionAdapter(this);
     BufferSize        = bufferSize;
 }
Exemple #52
0
 /// <summary>
 /// Constructor for client
 /// </summary>
 /// <param name="host"></param>
 /// <param name="port"></param>
 /// <param name="protocol"></param>
 public Riemann(string host = "localhost", int port = 5555, ProtocolType protocol = ProtocolType.Udp)
 {
     this.host     = host;
     this.port     = port;
     this.protocol = protocol;
 }
Exemple #53
0
        public static async void SendToElastic(this sFlowDatagram datagram)
        {
            string request  = "";
            string datetime = DateTime.Now.ToString("o");

            foreach (Sample sample in datagram.Samples)
            {
                if (sample == null)
                {
                    continue;
                }
                Dictionary <string, object> doc = new Dictionary <string, object>();
                doc.Add("@timestamp", datetime);
                doc.Add("sflow_source", datagram.AgentAddress.ToString());
                doc.Add("sflow_sequence", datagram.SequenceNumber);
                if (sample.Type == SampleType.Flow)
                {
                    FlowSample flowSample = (FlowSample)sample;
                    doc.Add("sampling_rate", flowSample.SamplingRate);
                    doc.Add("sampling_pool", flowSample.SamplingPool);
                    doc.Add("dropped_packets", flowSample.DroppedPackets);
                    doc.Add("frame_in_interface_value", flowSample.InputInterface.Value);
                    doc.Add("frame_out_interface_value", flowSample.OutputInterface.Value);
                    doc.Add("frame_out_interface_format", flowSample.OutputInterface.Format.ToString());
                    doc.Add("frame_out_interface_discard", flowSample.OutputInterface.DiscardReason.ToString());
                    foreach (FlowRecord record in flowSample.Records)
                    {
                        if (record.Type == FlowRecordType.RawPacketHeader)
                        {
                            RawPacketHeader rawPacketHeader = (RawPacketHeader)record;
                            doc.Add("frame_length_octets", rawPacketHeader.FrameLength);
                            if (rawPacketHeader.HeaderProtocol == HeaderProtocol.Ethernet)
                            {
                                EthernetFrame ethFrame = (EthernetFrame)rawPacketHeader.Header;
                                doc.Add("mac_source", ethFrame.SourceMAC.ToString());
                                doc.Add("mac_destination", ethFrame.DestinationMAC.ToString());
                                doc.Add("packet_type", ethFrame.PacketType.ToString());
                                ProtocolType ProtocolType = 0;
                                if (ethFrame.PacketType == PacketType.IPv4)
                                {
                                    IPv4Packet packet = (IPv4Packet)ethFrame.Packet;
                                    doc.Add("ip_source", packet.SourceAddress.ToString());
                                    doc.Add("ip_destination", packet.DestinationAddress.ToString());
                                    doc.Add("ip_ttl", packet.TimeToLive);
                                    doc.Add("protocol_type", packet.ProtocolType.ToString());
                                    ProtocolType = packet.ProtocolType;
                                }
                                if (ProtocolType == ProtocolType.TCP)
                                {
                                    TCP TCP = (TCP)ethFrame.Packet.Payload;
                                    doc.Add("port_source", TCP.SourcePort);
                                    doc.Add("port_destination", TCP.DestinationPort);
                                }
                                else if (ProtocolType == ProtocolType.UDP)
                                {
                                    UDP UDP = (UDP)ethFrame.Packet.Payload;
                                    doc.Add("port_source", UDP.SourcePort);
                                    doc.Add("port_destination", UDP.DestinationPort);
                                }
                            }
                        }
                        else if (record.Type == FlowRecordType.ExtSwitchData)
                        {
                            SwitchData switchData = (SwitchData)record;
                            doc.Add("vlan_in", switchData.IncomingVLAN);
                            doc.Add("vlan_out", switchData.OutgoingVLAN);
                        }
                    }
                }
                else if (sample.Type == SampleType.Counter)
                {
                    CounterSample countSample = (CounterSample)sample;
                    foreach (CounterRecord record in countSample.Records)
                    {
                        if (record.Type == CounterRecordType.GenericInterface)
                        {
                            Generic gi = (Generic)record;
                            doc.Add("if_direction", gi.IfDirection.ToString());
                            doc.Add("if_in_broadcast_pkts", gi.IfInBroadcastPkts);
                            doc.Add("if_index", gi.IfIndex);
                            doc.Add("if_in_discards", gi.IfInDiscards);
                            doc.Add("if_in_errors", gi.IfInErrors);
                            doc.Add("if_in_multicast_pkts", gi.IfInMulticastPkts);
                            doc.Add("if_in_octets", gi.IfInOctets);
                            doc.Add("if_in_unicast_pkts", gi.IfInUcastPkts);
                            doc.Add("if_in_unknown_protos", gi.IfInUnknownProtos);
                            doc.Add("if_out_broadcast_pkts", gi.IfOutBroadcastPkts);
                            doc.Add("if_out_discards", gi.IfOutDiscards);
                            doc.Add("if_out_errors", gi.IfOutErrors);
                            doc.Add("if_out_multicast_pkts", gi.IfOutMulticastPkts);
                            doc.Add("if_out_octets", gi.IfOutOctets);
                            doc.Add("if_out_unicast_ptks", gi.IfOutUcastPkts);
                            doc.Add("if_promiscuous_mode", gi.IfPromiscuousMode);
                            doc.Add("if_speed", gi.IfSpeed);
                            doc.Add("if_type", gi.IfType);
                            doc.Add("if_status_up_admin", gi.IfStatus.HasFlag(Generic.IfStatusFlags.IfAdminStatusUp));
                            doc.Add("if_status_up_operational", gi.IfStatus.HasFlag(Generic.IfStatusFlags.IfOperStatusUp));
                        }
                        else if (record.Type == CounterRecordType.EthernetInterface)
                        {
                            Ethernet eth = (Ethernet)record;
                            doc.Add("eth_alignment_errors", eth.AlignmentErrors);
                            doc.Add("eth_carrier_sense_errors", eth.CarrierSenseErrors);
                            doc.Add("eth_deferred_transmissions", eth.DeferredTransmissions);
                            doc.Add("eth_excessive_collisions", eth.ExcessiveCollisions);
                            doc.Add("eth_fcs_errors", eth.FCSErrors);
                            doc.Add("eth_frame_too_longs", eth.FrameTooLongs);
                            doc.Add("eth_mac_recieve_errors", eth.InternalMacReceiveErrors);
                            doc.Add("eth_mac_transmit_errors", eth.InternalMacTransmitErrors);
                            doc.Add("eth_late_collisions", eth.LateCollisions);
                            doc.Add("eth_multiple_collision_frames", eth.MultipleCollisionFrames);
                            doc.Add("eth_single_collision_frames", eth.SingleCollisionFrames);
                            doc.Add("eth_sqe_test_errors", eth.SQETestErrors);
                            doc.Add("eth_symbol_errors", eth.SymbolErrors);
                        }
                        else if (record.Type == CounterRecordType.VLAN)
                        {
                            VLAN vlan = (VLAN)record;
                            doc.Add("vlan_multicast_pkts", vlan.MulticastPkts);
                            doc.Add("vlan_octets", vlan.Octets);
                            doc.Add("vlan_unicast_pkts", vlan.UCastPkts);
                            doc.Add("vlan_id", vlan.VlanID);
                        }
                        else if (record.Type == CounterRecordType.ProcessorInformation)
                        {
                            ProcessorInfo pi = (ProcessorInfo)record;
                            doc.Add("stats_cpu_percent_1m", pi.Cpu1mPercentage);
                            doc.Add("stats_cpu_percent", pi.Cpu5mPercentage);
                            doc.Add("stats_cpu_5s_percent", pi.Cpu5sPercentage);
                            doc.Add("stats_memory_free", pi.FreeMemory);
                            doc.Add("stats_memory_total", pi.TotalMemory);
                        }
                    }
                }
                request += "{\"create\":{\"_index\":\"" + PREFIX + sample.Type.ToString().ToLower() + "\"}}\n";
                request += JsonConvert.SerializeObject(doc) + '\n';
            }
            try
            {
                MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(request));
                await HC.PostAsync(URI + "/_bulk", new StreamContent(ms)
                {
                    Headers =
                    {
                        ContentType = MediaTypeHeaderValue.Parse("application/json")
                    }
                });

                ms.Dispose();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Exemple #54
0
 public AsyncSocket(AddressFamily family, SocketType type, ProtocolType protocol)
 {
     _socket = new Socket(family, type, protocol);
 }
Exemple #55
0
 public override bool Initialize(int iPort, int iBaud, ProtocolType iProtocol)
 {
     return(Initialize(iPort, iBaud));
 }
 public MdoSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
     : base(addressFamily, socketType, protocolType)
 {
     allDone = new ManualResetEvent(false);
 }
Exemple #57
0
        /// <summary>
        /// This is the main routine that parses the command line and invokes the server with the
        /// given parameters. For TCP, it creates a listening socket and waits to accept a client
        /// connection. Once a client connects, it waits to receive a "request" message. The
        /// request is terminated by the client shutting down the connection. After the request is
        /// received, the server sends a response followed by shutting down its connection and
        /// closing the socket. For UDP, the socket simply listens for incoming packets. The "request"
        /// message is a single datagram received. Once the request is received, a number of datagrams
        /// are sent in return followed by sending a few zero byte datagrams. This way the client
        /// can determine that the response has completed when it receives a zero byte datagram.
        /// </summary>
        /// <param name="args">Command line arguments</param>
        public static void Main(string[] args)
        {
            string       textMessage = "Server: ServerResponse";
            int          localPort = 5150, sendCount = 10, bufferSize = 4096;
            IPAddress    localAddress = IPAddress.Any;
            SocketType   sockType     = SocketType.Stream;
            ProtocolType sockProtocol = ProtocolType.Tcp;

            // Parse the command line
            for (int i = 0; i < args.Length; i++)
            {
                try {
                    if ((args[i][0] == '-') || (args[i][0] == '/'))
                    {
                        switch (Char.ToLower(args[i][1]))
                        {
                        case 'l':           // Local interface to bind to
                            localAddress = IPAddress.Parse(args[++i]);
                            break;

                        case 'm':           // Text message to put into the send buffer
                            textMessage = args[++i];
                            break;

                        case 'n':           // Number of times to send the response
                            sendCount = System.Convert.ToInt32(args[++i]);
                            break;

                        case 'p':           // Port number for the destination
                            localPort = System.Convert.ToInt32(args[++i]);
                            break;

                        case 't':           // Specified TCP or UDP
                            i++;
                            if (String.Compare(args[i], "tcp", true) == 0)
                            {
                                sockType     = SocketType.Stream;
                                sockProtocol = ProtocolType.Tcp;
                            }
                            else if (String.Compare(args[i], "udp", true) == 0)
                            {
                                sockType     = SocketType.Dgram;
                                sockProtocol = ProtocolType.Udp;
                            }
                            else
                            {
                                FillServerUsage();
                                return;
                            }
                            break;

                        case 'x':           // Size of the send and receive buffers
                            bufferSize = System.Convert.ToInt32(args[++i]);
                            break;

                        default:
                            //queueSocketServer = FillServerUsage();
                            return;
                        }
                    }
                } catch {
                    //MainForm.queueSocketServer = FillServerUsage();
                    return;
                }
            }

            Socket serverSocket = null;

            try {
                IPEndPoint localEndPoint = new IPEndPoint(localAddress, localPort), senderAddress = new IPEndPoint(localAddress, 0);
                Console.WriteLine("Server: IPEndPoint is OK...");
                EndPoint castSenderAddress;
                Socket   clientSocket;
                byte[]   receiveBuffer = new byte[bufferSize], sendBuffer = new byte[bufferSize];
                int      rc;

                FormatBuffer(sendBuffer, textMessage);

                // Create the server socket
                serverSocket = new Socket(localAddress.AddressFamily, sockType, sockProtocol);

                Console.WriteLine("Server: Socket() is OK...");
                // Bind the socket to the local interface specified
                serverSocket.Bind(localEndPoint);

                Console.WriteLine("Server: {0} server socket bound to {1}", sockProtocol.ToString(), localEndPoint.ToString());

                if (sockProtocol == ProtocolType.Tcp)
                {
                    // If TCP socket, set the socket to listening
                    serverSocket.Listen(1);
                    Console.WriteLine("Server: Listen() is OK, I'm listening for connection buddy!");
                }
                else
                {
                    byte[] byteTrue = new byte[4];

                    // Set the SIO_UDP_CONNRESET ioctl to true for this UDP socket. If this UDP socket
                    //    ever sends a UDP packet to a remote destination that exists but there is
                    //    no socket to receive the packet, an ICMP port unreachable message is returned
                    //    to the sender. By default, when this is received the next operation on the
                    //    UDP socket that send the packet will receive a SocketException. The native
                    //    (Winsock) error that is received is WSAECONNRESET (10054). Since we don't want
                    //    to wrap each UDP socket operation in a try/except, we'll disable this error
                    //    for the socket with this ioctl call.
                    byteTrue[byteTrue.Length - 1] = 1;
                    serverSocket.IOControl(ServerSocket.SIO_UDP_CONNRESET, byteTrue, null);
                    Console.WriteLine("Server: IOControl() is OK...");
                }

                // Service clients in a loop
                while (true)
                {
                    if (sockProtocol == ProtocolType.Tcp)
                    {
                        // Wait for a client connection
                        clientSocket = serverSocket.Accept();
                        Console.WriteLine("Server: Accept() is OK...");
                        Console.WriteLine("Server: Accepted connection from: {0}", clientSocket.RemoteEndPoint.ToString());

                        // Receive the request from the client in a loop until the client shuts
                        //    the connection down via a Shutdown.
                        Console.WriteLine("Server: Preparing to receive using Receive()...");
                        while (true)
                        {
                            rc = clientSocket.Receive(receiveBuffer);

                            Console.WriteLine("Server: Read {0} bytes", rc);
                            if (rc == 0)
                            {
                                break;
                            }
                        }

                        // Send the indicated number of response messages
                        Console.WriteLine("Server: Preparing to send using Send()...");
                        for (int i = 0; i < sendCount; i++)
                        {
                            rc = clientSocket.Send(sendBuffer);
                            Console.WriteLine("Server: Sent {0} bytes", rc);
                        }

                        // Shutdown the client connection
                        clientSocket.Shutdown(SocketShutdown.Send);
                        Console.WriteLine("Server: Shutdown() is OK...");
                        clientSocket.Close();
                        Console.WriteLine("Server: Close() is OK...");
                    }
                    else
                    {
                        castSenderAddress = (EndPoint)senderAddress;

                        // Receive the initial request from the client
                        rc = serverSocket.ReceiveFrom(receiveBuffer, ref castSenderAddress);
                        Console.WriteLine("Server: ReceiveFrom() is OK...");
                        senderAddress = (IPEndPoint)castSenderAddress;
                        Console.WriteLine("Server: Received {0} bytes from {1}", rc, senderAddress.ToString());

                        // Send the response to the client the requested number of times
                        for (int i = 0; i < sendCount; i++)
                        {
                            try {
                                rc = serverSocket.SendTo(sendBuffer, senderAddress);
                                Console.WriteLine("Server: SendTo() is OK...");
                            } catch {
                                // If the sender's address is being spoofed we may get an error when sending
                                //    the response. You can test this by using IPv6 and using the RawSocket
                                //    sample to spoof a UDP packet with an invalid link local source address.
                                continue;
                            }
                            Console.WriteLine("Server: Sent {0} bytes to {1}", rc, senderAddress.ToString());
                        }

                        // Send several zero byte datagrams to indicate to client that no more data
                        //    will be sent from the server. Multiple packets are sent since UDP
                        //    is not guaranteed and we want to try to make an effort the client
                        //    gets at least one.
                        Console.WriteLine("Server: Preparing to send using SendTo(), on the way do sleeping, Sleep(250)...");
                        for (int i = 0; i < 3; i++)
                        {
                            serverSocket.SendTo(sendBuffer, 0, 0, SocketFlags.None, senderAddress);
                            // Space out sending the zero byte datagrams a bit. UDP is unreliable and
                            //   the local stack can even drop them before even hitting the wire!
                            System.Threading.Thread.Sleep(250);
                        }
                    }
                }
            } catch (SocketException err) {
                Console.WriteLine("Server: Socket error occurred: {0}", err.Message);
            } finally {
                // Close the socket if necessary
                if (serverSocket != null)
                {
                    Console.WriteLine("Server: Closing using Close()...");
                    serverSocket.Close();
                }
            }
        }
 public void Ctor_Failure(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
 {
     Assert.Throws <SocketException>(() => new Socket(addressFamily, socketType, protocolType));
 }
 public void Ctor_Success(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
 {
     using (new Socket(addressFamily, socketType, protocolType))
     {
     }
 }
Exemple #60
0
 public ProtocolChangedEventArgs(ProtocolType protocol)
 {
     Protocol = protocol;
 }