Ejemplo n.º 1
0
        private void btnConnect_Click(object sender, EventArgs e)
        {
            //Binding socket
            epLocal = new IPEndPoint(IPAddress.Parse(txtLocalIP.Text), Convert.ToInt32(txtLocalPort.Text));
            sck.Bind(epLocal);

            //Connecting to remote IP
            epRemote = new IPEndPoint(IPAddress.Parse(txtRemoteIP.Text), Convert.ToInt32(txtRemotePort.Text));
            sck.Connect(epRemote);

            //Listening the specific port
            buffer = new byte[1500];
            sck.BeginReceiveMessageFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
        }
Ejemplo n.º 2
0
        [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/987
        public void Success_APM()
        {
            if (Socket.OSSupportsIPv4)
            {
                using (Socket receiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
                {
                    int port = receiver.BindToAnonymousPort(IPAddress.Loopback);
                    receiver.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true);

                    Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                    sender.Bind(new IPEndPoint(IPAddress.Loopback, 0));

                    for (int i = 0; i < TestSettings.UDPRedundancy; i++)
                    {
                        sender.SendTo(new byte[1024], new IPEndPoint(IPAddress.Loopback, port));
                    }

                    IPPacketInformation packetInformation;
                    SocketFlags         flags    = SocketFlags.None;
                    EndPoint            remoteEP = new IPEndPoint(IPAddress.Any, 0);

                    IAsyncResult ar = receiver.BeginReceiveMessageFrom(new byte[1024], 0, 1024, flags, ref remoteEP, null, null);
                    ar.AsyncWaitHandle.WaitOne();
                    int len = receiver.EndReceiveMessageFrom(ar, ref flags, ref remoteEP, out packetInformation);

                    Assert.Equal(1024, len);
                    Assert.Equal(sender.LocalEndPoint, remoteEP);
                    Assert.Equal(((IPEndPoint)sender.LocalEndPoint).Address, packetInformation.Address);

                    sender.Dispose();
                }
            }
        }
Ejemplo n.º 3
0
        // ToDo: Supposedly the Event Asynchronous Pattern (EAP) can be turned into the Task Asynchronous Pattern (TAP)
        // with one line. Couldn't make it work as yet.
        //public Task<int> ReceiveAsync(byte[] buffer, int offset, int count, SocketFlags flags)
        //{
        //    return Task<int>.Factory.FromAsync(m_udpSocket.BeginReceive, m_udpSocket.EndReceive,
        //        buffer, offset, count, flags, null, TaskCreationOptions.None);
        //}

        /// <summary>
        /// Starts the receive. This method returns immediately. An event will be fired in the corresponding "End" event to
        /// return any data received.
        /// </summary>
        public void BeginReceive()
        {
            try
            {
                EndPoint recvEndPoint = (m_udpSocket.LocalEndPoint.AddressFamily == AddressFamily.InterNetwork) ? new IPEndPoint(IPAddress.Any, 0) : new IPEndPoint(IPAddress.IPv6Any, 0);
                m_udpSocket.BeginReceiveMessageFrom(m_recvBuffer, 0, m_recvBuffer.Length, SocketFlags.None, ref recvEndPoint, EndReceiveMessageFrom, null);
            }
            catch (ObjectDisposedException) { } // Thrown when socket is closed. Can be safely ignored.
            // This exception can be thrown in response to an ICMP packet. The problem is the ICMP packet can be a false positive.
            // For example if the remote RTP socket has not yet been opened the remote host could generate an ICMP packet for the
            // initial RTP packets. Experience has shown that it's not safe to close an RTP connection based solely on ICMP packets.
            catch (SocketException)
            {
                //logger.LogWarning($"Socket error {sockExcp.SocketErrorCode} in UdpReceiver.BeginReceive. {sockExcp.Message}");
                //Close(sockExcp.Message);
            }
            catch (Exception excp)
            {
                // From https://github.com/dotnet/corefx/blob/e99ec129cfd594d53f4390bf97d1d736cff6f860/src/System.Net.Sockets/src/System/Net/Sockets/Socket.cs#L3056
                // the BeginReceiveMessageFrom will only throw if there is an problem with the arguments or the socket has been disposed of. In that
                // case the socket can be considered to be unusable and there's no point trying another receive.
                logger.LogError($"Exception UdpReceiver.BeginReceive. {excp.Message}");
                Close(excp.Message);
            }
        }
Ejemplo n.º 4
0
        public void BeginReceiveMessageFrom_RemoteEpIsReturnedWhenCompletedSynchronously()
        {
            EndPoint anyEp    = new IPEndPoint(IPAddress.Any, 0);
            EndPoint remoteEp = anyEp;

            using Socket receiver = CreateSocket();
            receiver.BindToAnonymousPort(IPAddress.Loopback);
            using Socket sender = CreateSocket();
            sender.BindToAnonymousPort(IPAddress.Loopback);

            sender.SendTo(new byte[1], receiver.LocalEndPoint);

            IAsyncResult iar = receiver.BeginReceiveMessageFrom(new byte[1], 0, 1, SocketFlags.None, ref remoteEp, null, null);

            if (iar.CompletedSynchronously)
            {
                _output.WriteLine("Completed synchronously, updated endpoint.");
                Assert.Equal(sender.LocalEndPoint, remoteEp);
            }
            else
            {
                _output.WriteLine("Completed asynchronously, did not update endPoint");
                Assert.Equal(anyEp, remoteEp);
            }
        }
Ejemplo n.º 5
0
        private void OnMessageReceived(IAsyncResult ar)
        {
            Socket   socket         = (Socket)ar.AsyncState;
            EndPoint clientEndPoint = new IPEndPoint(IPAddress.Any, 0);

            SocketFlags         flags = new SocketFlags();
            IPPacketInformation ipInf = new IPPacketInformation();

            int packetLength = socket.EndReceiveMessageFrom(ar, ref flags, ref clientEndPoint, out ipInf);

            byte[] packet = new byte[packetLength];
            Array.Copy(_buffer, packet, packetLength);

            EndPoint newClientEndPoint = new IPEndPoint(IPAddress.Any, 0);

            socket.BeginReceiveMessageFrom(
                _buffer, 0, _buffer.Length, SocketFlags.None, ref newClientEndPoint, OnMessageReceived, (object)socket);

            string messageId = string.Empty;

            if (_messageUtils.ParseProbe(packet, ref messageId))
            {
                SendMessage(
                    _messageUtils.BuildProbeMatches(_scopes.ToArray(), false, new string[] { _xAddr }, messageId),
                    false, clientEndPoint);
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Extends BeginReceiveMessageFrom so that when a state object is not needed, null does not need to be passed.
        /// <example>
        /// socket.BeginReceiveMessageFrom(buffer, offset, size, socketFlags, remoteEP, callback);
        /// </example>
        /// </summary>
        public static IAsyncResult BeginReceiveMessageFrom(this Socket socket, Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags, ref System.Net.EndPoint remoteEP, AsyncCallback callback)
        {
            if (socket == null)
            {
                throw new ArgumentNullException("socket");
            }

            return(socket.BeginReceiveMessageFrom(buffer, offset, size, socketFlags, ref remoteEP, callback, null));
        }
Ejemplo n.º 7
0
 /// <inheritdoc />
 public IAsyncResult BeginReceiveMessageFrom(byte[] buffer,
                                             int offset,
                                             int size,
                                             SocketFlags socketFlags,
                                             ref EndPoint remoteEP,
                                             AsyncCallback callback,
                                             object state)
 {
     return(_socket.BeginReceiveMessageFrom(buffer, offset, size, socketFlags, ref remoteEP, callback, state));
 }
Ejemplo n.º 8
0
        public void Success_APM(bool ipv4)
        {
            AddressFamily     family;
            IPAddress         loopback, any;
            SocketOptionLevel level;

            if (ipv4)
            {
                if (!Socket.OSSupportsIPv4)
                {
                    return;
                }
                family   = AddressFamily.InterNetwork;
                loopback = IPAddress.Loopback;
                any      = IPAddress.Any;
                level    = SocketOptionLevel.IP;
            }
            else
            {
                if (!Socket.OSSupportsIPv6)
                {
                    return;
                }
                family   = AddressFamily.InterNetworkV6;
                loopback = IPAddress.IPv6Loopback;
                any      = IPAddress.IPv6Any;
                level    = SocketOptionLevel.IPv6;
            }

            using (var receiver = new Socket(family, SocketType.Dgram, ProtocolType.Udp))
                using (var sender = new Socket(family, SocketType.Dgram, ProtocolType.Udp))
                {
                    int port = receiver.BindToAnonymousPort(loopback);
                    receiver.SetSocketOption(level, SocketOptionName.PacketInformation, true);
                    sender.Bind(new IPEndPoint(loopback, 0));

                    for (int i = 0; i < TestSettings.UDPRedundancy; i++)
                    {
                        sender.SendTo(new byte[1024], new IPEndPoint(loopback, port));
                    }

                    IPPacketInformation packetInformation;
                    SocketFlags         flags    = SocketFlags.None;
                    EndPoint            remoteEP = new IPEndPoint(any, 0);

                    IAsyncResult ar  = receiver.BeginReceiveMessageFrom(new byte[1024], 0, 1024, flags, ref remoteEP, null, null);
                    int          len = receiver.EndReceiveMessageFrom(ar, ref flags, ref remoteEP, out packetInformation);

                    Assert.Equal(1024, len);
                    Assert.Equal(sender.LocalEndPoint, remoteEP);
                    Assert.Equal(((IPEndPoint)sender.LocalEndPoint).Address, packetInformation.Address);
                }
        }
Ejemplo n.º 9
0
        public void EndReceiveMessageFrom_AddressFamilyDoesNotMatch_Throws_ArgumentException()
        {
            SocketFlags socketFlags     = SocketFlags.None;
            EndPoint    validEndPoint   = new IPEndPoint(IPAddress.Loopback, 1);
            EndPoint    invalidEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, 1);

            using Socket socket = CreateSocket();
            socket.BindToAnonymousPort(IPAddress.Loopback);
            IAsyncResult iar = socket.BeginReceiveMessageFrom(new byte[1], 0, 1, SocketFlags.None, ref validEndPoint, null, null);

            Assert.Throws <ArgumentException>("endPoint", () => socket.EndReceiveMessageFrom(iar, ref socketFlags, ref invalidEndPoint, out _));
        }
        private void ReceiveCallback(IAsyncResult ar)
        {
            // end the receive
            Socket sock = (Socket)ar.AsyncState;

            try {
                SocketFlags         sf = SocketFlags.None;
                IPPacketInformation packetInfo;
                int bytes = sock.EndReceiveMessageFrom(ar, ref sf, ref receiveEndpoint, out packetInfo);

                lock (lockobj) {
                    IPEndPoint ep = receiveEndpoint as IPEndPoint;
                    if (ep != null)
                    {
                        ChannelSender sender = null;
                        for (int i = 0; i < senders.Count; i++)
                        {
                            if (senders[i].Endpoint.Equals(ep))
                            {
                                sender = senders[i];
                                break;
                            }
                        }

                        if (sender == null)
                        {
                            sender = new ChannelSender(ep);
                            senders.Add(sender);
                        }

                        // parse out the version, serialization type, sequence number
                        int seqNumber = int.MinValue;
                        switch (channelType)
                        {
                        case ChannelType.UDPChannel:
                            ParseUDPChannelPacket(buf, bytes, ref seqNumber);
                            break;
                        }
                        sender.OnPacketReceived(seqNumber);

                        packetCount++;
                        byteCount += bytes;
                    }
                }

                receiveEndpoint = new IPEndPoint(IPAddress.Any, 0);
                sock.BeginReceiveMessageFrom(buf, 0, buf.Length, SocketFlags.None, ref receiveEndpoint, ReceiveCallback, sock);
            }
            catch (Exception) {
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Extends BeginReceiveMessageFrom so that buffer offset of 0 and call to Array.Length are not needed.
        /// <example>
        /// socket.BeginReceiveMessageFrom(buffer, socketFlags, remoteEP, callback);
        /// </example>
        /// </summary>
        public static IAsyncResult BeginReceiveMessageFrom(this Socket socket, Byte[] buffer, SocketFlags socketFlags, ref System.Net.EndPoint remoteEP, AsyncCallback callback)
        {
            if (socket == null)
            {
                throw new ArgumentNullException("socket");
            }

            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }

            return(socket.BeginReceiveMessageFrom(buffer, 0, buffer.Length, socketFlags, ref remoteEP, callback));
        }
Ejemplo n.º 12
0
        public SharedSocket(int port)
        {
            addressEntries = new List <AddressEntry>();

            this.port = port;

            buffer          = new byte[65535];
            receiveEndpoint = new IPEndPoint(IPAddress.Any, 0);

            socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            socket.Bind(new IPEndPoint(IPAddress.Any, port));
            socket.BeginReceiveMessageFrom(buffer, 0, buffer.Length, SocketFlags.None, ref receiveEndpoint, OnDataReceived, null);
        }
Ejemplo n.º 13
0
        public MessInterface()
        {
            this.receiveEndpoint = new IPEndPoint(IPAddress.Any, 0);

            this.buf = new byte[65536];

            receiveEndpoint = new IPEndPoint(IPAddress.Any, 0);

            socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            socket.Bind(new IPEndPoint(IPAddress.Any, 30040));
            socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse("239.132.1.40")));
            socket.BeginReceiveMessageFrom(buf, 0, buf.Length, SocketFlags.None, ref receiveEndpoint, ReceiveCallback, socket);
        }
Ejemplo n.º 14
0
        // ToDo: Supposedly the Event Asynchronous Pattern (EAP) can be turned into the Task Asynchronous Pattern (TAP)
        // with one line. Couldn't make it work as yet.
        //public Task<int> ReceiveAsync(byte[] buffer, int offset, int count, SocketFlags flags)
        //{
        //    return Task<int>.Factory.FromAsync(m_udpSocket.BeginReceive, m_udpSocket.EndReceive,
        //        buffer, offset, count, flags, null, TaskCreationOptions.None);
        //}

        /// <summary>
        /// Starts the receive. This method returns immediately. An event will be fired in the corresponding "End" event to
        /// return any data received.
        /// </summary>
        public void BeginReceive()
        {
            try
            {
                EndPoint recvEndPoint = (m_udpSocket.LocalEndPoint.AddressFamily == AddressFamily.InterNetwork) ? new IPEndPoint(IPAddress.Any, 0) : new IPEndPoint(IPAddress.IPv6Any, 0);
                m_udpSocket.BeginReceiveMessageFrom(m_recvBuffer, 0, m_recvBuffer.Length, SocketFlags.None, ref recvEndPoint, EndReceiveMessageFrom, null);
            }
            catch (ObjectDisposedException) { } // Thrown when socket is closed. Can be safely ignored.
            catch (Exception excp)
            {
                // From https://github.com/dotnet/corefx/blob/e99ec129cfd594d53f4390bf97d1d736cff6f860/src/System.Net.Sockets/src/System/Net/Sockets/Socket.cs#L3056
                // the BeginReceiveMessageFrom will only throw if there is an problem with the arguments or the socket has been disposed of. In that
                // case the socket can be considered to be unusable and there's no point trying another receive.
                logger.LogError($"Exception UdpReceiver.BeginReceive. {excp.Message}");
                Close(excp.Message);
            }
        }
Ejemplo n.º 15
0
 private void Receive()
 {
     try
     {
         EndPoint recvEndPoint = (ListeningIPAddress.AddressFamily == AddressFamily.InterNetwork) ? new IPEndPoint(IPAddress.Any, 0) : new IPEndPoint(IPAddress.IPv6Any, 0);
         m_udpSocket.BeginReceiveMessageFrom(m_recvBuffer, 0, m_recvBuffer.Length, SocketFlags.None, ref recvEndPoint, EndReceiveMessageFrom, null);
     }
     catch (Exception excp)
     {
         // From https://github.com/dotnet/corefx/blob/e99ec129cfd594d53f4390bf97d1d736cff6f860/src/System.Net.Sockets/src/System/Net/Sockets/Socket.cs#L3056
         // the BeginReceiveMessageFrom will only throw if there is an problem with the arguments or the socket has been disposed of. In that
         // case the sopcket can be considered to be unusable adn there's no point trying another receive.
         logger.LogError($"Exception Receive. {excp.Message}");
         logger.LogDebug($"SIPUDPChannel socket on {ListeningEndPoint} listening halted.");
         Closed = true;
     }
 }
Ejemplo n.º 16
0
        private void ReceiveCallback(IAsyncResult ar)
        {
            try {
                Socket              socket = (Socket)ar.AsyncState;
                SocketFlags         sf     = SocketFlags.None;
                IPPacketInformation packetInfo;
                int bytesRecevied = socket.EndReceiveMessageFrom(ar, ref sf, ref receiveEndpoint, out packetInfo);
                if (bytesRecevied >= 2)
                {
                    OnMessPacketReceived(buf, bytesRecevied);
                }

                receiveEndpoint = new IPEndPoint(IPAddress.Any, 0);
                socket.BeginReceiveMessageFrom(buf, 0, buf.Length, SocketFlags.None, ref receiveEndpoint, ReceiveCallback, socket);
            }
            catch (Exception) {
            }
        }
Ejemplo n.º 17
0
        private void OnDataReceived(IAsyncResult ar)
        {
            bool doBeginReceive = true;

            try {
                SocketFlags         flags = SocketFlags.None;
                IPPacketInformation packetInfo;
                int bytesRead = socket.EndReceiveMessageFrom(ar, ref flags, ref receiveEndpoint, out packetInfo);

                IPEndPoint fromEndpoint = receiveEndpoint as IPEndPoint;
                IPAddress  destAddress  = packetInfo.Address;

                SocketDataReceivedEventArgs e = new SocketDataReceivedEventArgs(fromEndpoint, new IPEndPoint(destAddress, port), buffer, bytesRead);

                lock (addressEntries) {
                    foreach (AddressEntry entry in addressEntries)
                    {
                        if (CompareSourceIP(entry.sourceAddress, fromEndpoint.Address) && CompareDestIP(entry.destAddress, destAddress))
                        {
                            entry.callback(e);
                        }
                    }
                }
            }
            catch (ObjectDisposedException) {
                doBeginReceive = false;
            }

            if (doBeginReceive)
            {
                int tryCount = 0;
                while (tryCount < 3)
                {
                    try {
                        receiveEndpoint = new IPEndPoint(IPAddress.Any, 0);
                        socket.BeginReceiveMessageFrom(buffer, 0, buffer.Length, SocketFlags.None, ref receiveEndpoint, OnDataReceived, null);
                        break;
                    }
                    catch (Exception) {
                    }
                    tryCount++;
                }
            }
        }
Ejemplo n.º 18
0
        private void OnMessageReceived(IAsyncResult ar)
        {
            Socket socket = (Socket)ar.AsyncState;

            try
            {
                EndPoint clientEndPoint = new IPEndPoint(IPAddress.Any, 0);

                SocketFlags         flags = new SocketFlags();
                IPPacketInformation ipInf = new IPPacketInformation();

                int packetLength = socket.EndReceiveMessageFrom(ar, ref flags, ref clientEndPoint, out ipInf);

                byte[] packet = new byte[packetLength];
                Array.Copy(_buffer, packet, packetLength);

                char[] packetChar = new char[packet.Length];
                Array.Copy(_buffer, packetChar, packet.Length);
                String packetStr = new String(packetChar);
                System.IO.File.AppendAllText(Environment.GetEnvironmentVariable("TEMP") + @"\test.log",
                                             "\n[" + DateTime.Now.ToString() + "]\nMessage: " + packetStr + "\n");

                string messageId = string.Empty;
                if (_messageUtils.ParseProbe(packet, ref messageId))
                {
                    System.IO.File.AppendAllText(Environment.GetEnvironmentVariable("TEMP") + @"\test.log",
                                                 "Parsed Id: " + messageId + "\n");

                    SendMessage(
                        _messageUtils.BuildProbeMatches(_scopes.ToArray(), false, _xAddr.ToArray(), messageId),
                        false, clientEndPoint);
                }
            }
            catch (Exception exc)
            {
            }
            finally
            {
                EndPoint newClientEndPoint = new IPEndPoint(IPAddress.Any, 0);
                socket.BeginReceiveMessageFrom(
                    _buffer, 0, _buffer.Length, SocketFlags.None, ref newClientEndPoint, OnMessageReceived, (object)socket);
            }
        }
Ejemplo n.º 19
0
        public void StartServer()
        {
            try
            {
                var _endPointReference = (EndPoint) new IPEndPoint(IPAddress.Any, 53);
                LocalListener.Bind(_endPointReference);

                var parser   = new FileIniDataParser();
                var initData = parser.ReadFile($"{AppDomain.CurrentDomain.BaseDirectory}{@"\Configuration.ini"}");
                var realDns  = IPAddress.Parse(initData["IKDNS"]["DNSIP"]);

                RemoteSocket.Connect(realDns, 53);
                LocalListener.BeginReceiveMessageFrom(LocalBuffer, 0, LocalBuffer.Length, 0, ref _endPointReference, Receive, LocalListener);
            }
            catch (Exception ex)
            {
                NonBlockingConsole.WriteLine(ex.Message);
            }
        }
        public void StartListening()
        {
            lock (lockobj) {
                ResetStats();

                hasData = true;

                if (socket == null)
                {
                    receiveEndpoint = new IPEndPoint(IPAddress.Any, 0);

                    socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                    socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                    socket.Bind(new IPEndPoint(IPAddress.Any, this.endpoint.Port));
                    socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(this.endpoint.Address));
                    socket.BeginReceiveMessageFrom(buf, 0, buf.Length, SocketFlags.None, ref receiveEndpoint, ReceiveCallback, socket);
                }
            }
        }
Ejemplo n.º 21
0
        private void MessageCallBack(IAsyncResult aResult)
        {
            try
            {
                byte[] receivedData = new byte[1500];
                receivedData = (byte[])aResult.AsyncState;

                ASCIIEncoding aEncoding       = new ASCIIEncoding();
                string        receivedMessage = aEncoding.GetString(receivedData);

                listMessage.Items.Add("Client: " + receivedMessage);

                buffer = new byte[1500];
                sck.BeginReceiveMessageFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
Ejemplo n.º 22
0
        public override Task <SocketReceiveMessageFromResult> ReceiveMessageFromAsync(Socket s, ArraySegment <byte> buffer, EndPoint endPoint)
        {
            var         tcs         = new TaskCompletionSource <SocketReceiveMessageFromResult>();
            SocketFlags socketFlags = SocketFlags.None;

            s.BeginReceiveMessageFrom(buffer.Array, buffer.Offset, buffer.Count, socketFlags, ref endPoint, iar =>
            {
                try
                {
                    int receivedBytes = s.EndReceiveMessageFrom(iar, ref socketFlags, ref endPoint, out IPPacketInformation ipPacketInformation);
                    var result        = new SocketReceiveMessageFromResult
                    {
                        ReceivedBytes     = receivedBytes,
                        SocketFlags       = socketFlags,
                        RemoteEndPoint    = endPoint,
                        PacketInformation = ipPacketInformation
                    };
                    tcs.TrySetResult(result);
                }
                catch (Exception e) { tcs.TrySetException(e); }
            }, null);
            return(tcs.Task);
        }
Ejemplo n.º 23
0
        public static Task <UdpReceiveMessageFromResult> ReceiveMessageFromAsync(this Socket socket, byte[] buffer, int offset, int size, SocketFlags socketFlags = SocketFlags.None)
        {
            return(Task.Factory.FromAsync(
                       delegate(AsyncCallback callback, object state)
            {
                EndPoint ep;

                if (socket.AddressFamily == AddressFamily.InterNetworkV6)
                {
                    ep = IPEndPointIPv6Any;
                }
                else
                {
                    ep = IPEndPointAny;
                }

                return socket.BeginReceiveMessageFrom(buffer, offset, size, socketFlags, ref ep, callback, state);
            },
                       delegate(IAsyncResult result)
            {
                EndPoint ep;

                if (socket.AddressFamily == AddressFamily.InterNetworkV6)
                {
                    ep = IPEndPointIPv6Any;
                }
                else
                {
                    ep = IPEndPointAny;
                }

                int bytesReceived = socket.EndReceiveMessageFrom(result, ref socketFlags, ref ep, out IPPacketInformation ipPacketInformation);
                return new UdpReceiveMessageFromResult(bytesReceived, ep, ipPacketInformation);
            },
                       null));
        }
Ejemplo n.º 24
0
        public void BeginReceiveMessageFrom_NotSupported()
        {
            using (Socket sock = new Socket(SocketType.Dgram, ProtocolType.Udp))
            {
                EndPoint ep = new IPEndPoint(IPAddress.Any, 0);
                sock.Bind(ep);

                byte[] buf = new byte[1];

                Assert.Throws<PlatformNotSupportedException>(() => sock.BeginReceiveMessageFrom(buf, 0, buf.Length, SocketFlags.None, ref ep, null, null));
            }
        }
Ejemplo n.º 25
0
        private void BeginReceiveMessageFrom_Helper(IPAddress listenOn, IPAddress connectTo, bool expectedToTimeout = false)
        {
            using (Socket serverSocket = new Socket(SocketType.Dgram, ProtocolType.Udp))
            {
                int port = serverSocket.BindToAnonymousPort(listenOn);

                EndPoint receivedFrom = new IPEndPoint(connectTo, port);
                SocketFlags socketFlags = SocketFlags.None;
                IPPacketInformation ipPacketInformation;
                IAsyncResult async = serverSocket.BeginReceiveMessageFrom(new byte[1], 0, 1, socketFlags, ref receivedFrom, null, null);

                // Behavior difference from Desktop: receivedFrom will _not_ change during the synchronous phase.

                // IPEndPoint remoteEndPoint = receivedFrom as IPEndPoint;
                // Assert.Equal(AddressFamily.InterNetworkV6, remoteEndPoint.AddressFamily);
                // Assert.Equal(connectTo.MapToIPv6(), remoteEndPoint.Address);

                SocketUdpClient client = new SocketUdpClient(_log, serverSocket, connectTo, port);
                bool success = async.AsyncWaitHandle.WaitOne(expectedToTimeout ? Configuration.FailingTestTimeout : Configuration.PassingTestTimeout);
                if (!success)
                {
                    throw new TimeoutException();
                }

                receivedFrom = new IPEndPoint(connectTo, port);
                int received = serverSocket.EndReceiveMessageFrom(async, ref socketFlags, ref receivedFrom, out ipPacketInformation);

                Assert.Equal(1, received);
                Assert.Equal<Type>(receivedFrom.GetType(), typeof(IPEndPoint));

                IPEndPoint remoteEndPoint = receivedFrom as IPEndPoint;
                Assert.Equal(AddressFamily.InterNetworkV6, remoteEndPoint.AddressFamily);
                Assert.Equal(connectTo.MapToIPv6(), remoteEndPoint.Address);

                Assert.Equal(SocketFlags.None, socketFlags);
                Assert.NotNull(ipPacketInformation);
                Assert.Equal(connectTo, ipPacketInformation.Address);

                // TODO: Move to NetworkInformation tests.
                //Assert.Equal(NetworkInterface.IPv6LoopbackInterfaceIndex, ipPacketInformation.Interface);
            }
        }
Ejemplo n.º 26
0
        // "The parameter remoteEP must not be of type DnsEndPoint."
        public void Socket_BeginReceiveMessageFromDnsEndPoint_Throws()
        {
            using (Socket socket = new Socket(SocketType.Dgram, ProtocolType.Udp))
            {
                int port = socket.BindToAnonymousPort(IPAddress.IPv6Loopback);

                EndPoint receivedFrom = new DnsEndPoint("localhost", port, AddressFamily.InterNetworkV6);
                SocketFlags socketFlags = SocketFlags.None;
                Assert.Throws<ArgumentException>(() =>
                {
                    socket.BeginReceiveMessageFrom(new byte[1], 0, 1, socketFlags, ref receivedFrom, null, null);
                });
            }
        }
Ejemplo n.º 27
0
        [Fact] // Base case
        // "The supplied EndPoint of AddressFamily InterNetwork is not valid for this Socket, use InterNetworkV6 instead."
        public void Socket_BeginReceiveMessageFromV4IPEndPointFromV4Client_Throws()
        {
            Socket socket = new Socket(SocketType.Dgram, ProtocolType.Udp);
            socket.DualMode = false;

            EndPoint receivedFrom = new IPEndPoint(IPAddress.Loopback, UnusedPort);
            SocketFlags socketFlags = SocketFlags.None;

            Assert.Throws<ArgumentException>(() =>
            {
                socket.BeginReceiveMessageFrom(new byte[1], 0, 1, socketFlags, ref receivedFrom, null, null);
            });
        }
Ejemplo n.º 28
0
        private void BeginReceiveMessageFrom_Helper(IPAddress listenOn, IPAddress connectTo)
        {
            using (Socket serverSocket = new Socket(SocketType.Dgram, ProtocolType.Udp))
            {
                int port = serverSocket.BindToAnonymousPort(listenOn);

                EndPoint receivedFrom = new IPEndPoint(connectTo, port);
                SocketFlags socketFlags = SocketFlags.None;
                IPPacketInformation ipPacketInformation;
                IAsyncResult async = serverSocket.BeginReceiveMessageFrom(new byte[1], 0, 1, socketFlags, ref receivedFrom, null, null);

                IPEndPoint remoteEndPoint = receivedFrom as IPEndPoint;
                Assert.Equal(AddressFamily.InterNetworkV6, remoteEndPoint.AddressFamily);
                Assert.Equal(connectTo.MapToIPv6(), remoteEndPoint.Address);

                SocketUdpClient client = new SocketUdpClient(serverSocket, connectTo, port);
                bool success = async.AsyncWaitHandle.WaitOne(500);
                if (!success)
                {
                    throw new TimeoutException();
                }

                receivedFrom = new IPEndPoint(connectTo, port);
                int received = serverSocket.EndReceiveMessageFrom(async, ref socketFlags, ref receivedFrom, out ipPacketInformation);

                Assert.Equal(1, received);
                Assert.Equal<Type>(receivedFrom.GetType(), typeof(IPEndPoint));

                remoteEndPoint = receivedFrom as IPEndPoint;
                Assert.Equal(AddressFamily.InterNetworkV6, remoteEndPoint.AddressFamily);
                Assert.Equal(connectTo.MapToIPv6(), remoteEndPoint.Address);

                Assert.Equal(SocketFlags.None, socketFlags);
                Assert.NotNull(ipPacketInformation);
                Assert.Equal(connectTo, ipPacketInformation.Address);

                // TODO: Move to NetworkInformation tests.
                //Assert.Equal(NetworkInterface.IPv6LoopbackInterfaceIndex, ipPacketInformation.Interface);
            }
        }