void Bvlc_MessageReceived(System.Net.IPEndPoint sender, BacnetBvlcFunctions function, BacnetBvlcResults result, object data) { if (!sender.Equals(BBMDep)) { return; // don't care } if (InvokeRequired) // GUI call back { BeginInvoke(new Action <System.Net.IPEndPoint, BacnetBvlcFunctions, BacnetBvlcResults, object>(Bvlc_MessageReceived), new object[] { sender, function, result, data }); return; } if (function == BacnetBvlcFunctions.BVLC_READ_BROADCAST_DIST_TABLE_ACK) // an table (could be empty) { List <Tuple <IPEndPoint, IPAddress> > Entries = (List <Tuple <IPEndPoint, IPAddress> >)data; BBMDTable.Rows.Clear(); foreach (Tuple <IPEndPoint, IPAddress> tpl in Entries) { BBMDTable.Rows.Add(new object[] { tpl.Item1.Address.ToString(), tpl.Item1.Port, tpl.Item2.ToString() }); } lbBBMDlInfo.Visible = false; } if (function == BacnetBvlcFunctions.BVLC_READ_FOREIGN_DEVICE_TABLE_ACK) { List <Tuple <IPEndPoint, ushort, ushort> > Entries = (List <Tuple <IPEndPoint, ushort, ushort> >)data; FDRTable.Rows.Clear(); foreach (Tuple <IPEndPoint, ushort, ushort> tpl in Entries) { FDRTable.Rows.Add(new object[] { tpl.Item1.ToString(), tpl.Item2.ToString(), tpl.Item3.ToString() }); } lbFDRInfo.Visible = false; } if ((function == BacnetBvlcFunctions.BVLC_RESULT) && (result == BacnetBvlcResults.BVLC_RESULT_SUCCESSFUL_COMPLETION) && (WriteInOperation)) { WriteInOperation = false; transport.Bvlc.SendReadBroadCastTable(BBMDep); } if ((function == BacnetBvlcFunctions.BVLC_RESULT) && (result == BacnetBvlcResults.BVLC_RESULT_READ_BROADCAST_DISTRIBUTION_TABLE_NAK)) { lbBBMDlInfo.Visible = true; lbBBMDlInfo.Text = "Read Broadcast Table Rejected"; } if ((function == BacnetBvlcFunctions.BVLC_RESULT) && (result == BacnetBvlcResults.BVLC_RESULT_WRITE_BROADCAST_DISTRIBUTION_TABLE_NAK) && (WriteInOperation)) { lbBBMDlInfo.Visible = true; WriteInOperation = false; lbBBMDlInfo.Text = "Write Broadcast Table Rejected"; } if ((function == BacnetBvlcFunctions.BVLC_RESULT) && (result == BacnetBvlcResults.BVLC_RESULT_READ_FOREIGN_DEVICE_TABLE_NAK)) { lbFDRInfo.Visible = true; lbFDRInfo.Text = "Read FDR Table Rejected"; } }
public void SetEP(IPEndPoint ep) { if (ep.Equals(_listen.EP)) { return; } else { _listen.EP = ep; _listen.Stop(); } }
void test_ipendpoint_endpoint_equal() { System.Net.IPEndPoint ipep = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("127.0.0.1"), 1912); System.Net.EndPoint ep = (System.Net.IPEndPoint)ipep; print(ipep.ToString()); print(ep.ToString()); print(ipep.Equals(ep)); //System.Net.IPEndPoint ipep2 = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0); //System.Net.EndPoint sender = (System.Net.EndPoint)ipep; //sender = new }
public void Ctor_LongInt () { IPEndPoint ep = new IPEndPoint (0, 80); Assert.AreEqual (new IPAddress (0), ep.Address, "Address"); Assert.AreEqual (AddressFamily.InterNetwork, ep.AddressFamily, "AddressFamily"); Assert.AreEqual (80, ep.Port, "Port"); Assert.Throws<ArgumentNullException> (delegate { ep.Create (null); }, "Create(null)"); // note: documented as ArgumentException Assert.Throws<ArgumentOutOfRangeException> (delegate { SocketAddress sa = new SocketAddress (AddressFamily.InterNetwork, 1); Assert.IsTrue (sa.Size < 8, "Size"); ep.Create (sa); }, "Create(bad-size)"); Assert.Throws<ArgumentException> (delegate { SocketAddress sa = new SocketAddress (AddressFamily.InterNetworkV6); Assert.IsTrue (sa.Size >= 8, "SizeV6"); ep.Create (sa); }, "Create(InterNetworkV6)"); Assert.Throws<ArgumentException> (delegate { SocketAddress sa = new SocketAddress (AddressFamily.Unknown); ep.Create (sa); }, "Create(Unknown)"); Assert.Throws<ArgumentException> (delegate { SocketAddress sa = new SocketAddress (AddressFamily.Unspecified); ep.Create (sa); }, "Create(Unspecified)"); EndPoint ep2 = ep.Create (new SocketAddress (AddressFamily.InterNetwork)); Assert.IsFalse (ep.Equals (null), "Equals(null)"); Assert.IsTrue (ep.Equals (ep), "Equals(self)"); Assert.IsFalse (ep.Equals (ep2), "Equals(Create)"); Assert.AreEqual ("InterNetwork:16:{0,80,0,0,0,0,0,0,0,0,0,0,0,0}", ep.Serialize ().ToString (), "Serialize"); Assert.AreEqual ("0.0.0.0:80", ep.ToString (), "ToString"); }
public void EqualsIgnoreScopeId_Test( string sip1, int port1, string sip2, int port2, bool equalsOriginal, bool equalsIgnore ) { IPAddress ip1; IPAddress.TryParse(sip1, out ip1); var ipep1 = new IPEndPoint(ip1, port1); IPAddress ip2; IPAddress.TryParse(sip2, out ip2); var ipep2 = new IPEndPoint(ip2, port2); Assert.AreEqual(equalsOriginal, ipep1.Equals(ipep2), "Equals()"); Assert.AreEqual(equalsIgnore, ipep1.EqualsIgnoreScopeId(ipep2), "EqualsIgnoreScopeId()"); }
// Methods ============================================================================ public override void Start(IPEndPoint ep) { // Verify IPEndPoints IPEndPoint[] globalEPs = IPGlobalProperties.GetIPGlobalProperties().GetActiveUdpListeners(); foreach (IPEndPoint globalEP in globalEPs) { if (ep.Equals(globalEP)) throw new ApplicationException(ep.ToString() + " is in listening."); } System.Threading.Thread thread = new System.Threading.Thread(() => { server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); server.Bind(ep); /// ** Report ListenerStarted event if (ListenStarted != null) ListenStarted(this, new ListenEventArgs(ep)); EndPoint epClient = new IPEndPoint(IPAddress.Any, 0); isExitThread = false; while (true) { if (server.Poll(500000, SelectMode.SelectRead)) { int bytesRead = server.ReceiveFrom(readbuffer, readbuffer.Length, SocketFlags.None, ref epClient); /// ** Report ClientReadMsg event if (ClientRecvPack != null) ClientRecvPack(this, new ClientEventArgs(ep, epClient, readbuffer.Take(bytesRead).ToArray())); } else if (isExitThread == true) { isExitThread = false; break; } } server.Close(); /// ** Report ListenerStopped event if (ListenStopped != null) ListenStopped(this, new ListenEventArgs(ep)); }); thread.IsBackground = true; thread.Start(); }
public virtual int ReceivePacket(ref byte[] data, int size) { byte[] packet = new byte[size + 4]; System.Net.IPEndPoint remoteIpEp = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0); System.Net.EndPoint remoteEp = (System.Net.EndPoint)remoteIpEp; int count = socket.Receive(ref remoteEp, packet, size + 4); if (count == 0) { return(0); } if (count <= 4) { return(0); } if (packet[0] != (byte)(protocolID >> 24) || packet[1] != (byte)((protocolID >> 16) & 0xFF) || packet[2] != (byte)((protocolID >> 8) & 0xFF) || packet[3] != (byte)(protocolID & 0xFF)) { return(0); } if (mode == Mode.Server && !IsConnected()) { Debug.Log("server accepts connection from client "); state = State.Connected; address = remoteIpEp; OnConnect(); } // TODO if (address.Equals(remoteIpEp)) { if (state == State.Connecting) { state = State.Connected; OnConnect(); } timeoutAccumulator = 0.0f; System.Buffer.BlockCopy(packet, 4, data, 0, count - 4); return(count - 4); } return(0); }
public IEnumerable<IPEndPoint> GetServers(Region region, string filter = null) { using (var client = new UdpClient()) { int serverCount; var anyEndpoint = new IPEndPoint(IPAddress.Any, 0); var lastEndpoint = anyEndpoint; do { serverCount = 0; var query = new List<byte> { 0x31, (byte)region }; query.AddRange(Encoding.ASCII.GetBytes(lastEndpoint.ToString())); query.Add(0); // ip termination if (!String.IsNullOrWhiteSpace(filter)) query.AddRange(Encoding.ASCII.GetBytes(filter)); query.Add(0); // filter termination client.Send(query.ToArray(), query.Count, _endpoint); var serverData = client.Receive(ref AnyIpEndPoint); using (var br = new BinaryReader(new MemoryStream(serverData))) { if (br.ReadInt32() != -1 || br.ReadInt16() != 0x0A66) yield break; while (br.BaseStream.Position < br.BaseStream.Length) { var ipBytes = br.ReadBytes(4); var port = (ushort)IPAddress.NetworkToHostOrder(br.ReadInt16()); var server = new IPEndPoint(new IPAddress(ipBytes), port); if (server.Equals(anyEndpoint)) yield break; yield return server; lastEndpoint = server; serverCount++; } } } while (serverCount > 0); } }
public async Task ConnectToPeerAsync(IPEndPoint remoteEndpoint) { if (remoteEndpoint.Equals(LocalEndpoint)) return; RemoteNode remoteNode; lock (unconnectedPeers) { unconnectedPeers.Remove(remoteEndpoint); } lock (pendingPeers) { lock (connectedPeers) { if (pendingPeers.Any(p => p.RemoteEndpoint == remoteEndpoint) || connectedPeers.ContainsKey(remoteEndpoint)) return; } remoteNode = new RemoteNode(this, remoteEndpoint); pendingPeers.Add(remoteNode); remoteNode.Disconnected += RemoteNode_Disconnected; remoteNode.PeersReceived += RemoteNode_PeersReceived; remoteNode.BlockReceived += RemoteNode_BlockReceived; remoteNode.TransactionReceived += RemoteNode_TransactionReceived; } await remoteNode.ConnectAsync(); }
//throws InterruptedException public void brainsplit(Message msg) { lock (this) { // current transaction can timeout if (msg is CanCommitMessage) { // forbid new transactions Logger.getInstance().log( "Sending message to blocked cohort: " + msg.toString(), LOGGING_NAME, Logger.Level.INFO); blockedCohort.putMessage(msg); } else if (msg is TransactionMessage) { // forbid new transactions Logger.getInstance().log( "Sending message to blocked coordinator: " + msg.toString(), LOGGING_NAME, Logger.Level.INFO); blockedCoordinator.putMessage(msg); } else if (msg is RestoreIncentive) { // forbid new restoration Logger.getInstance().log( "Sending message to blocked restore coordinator: " + msg.toString(), LOGGING_NAME, Logger.Level.INFO); blockedRestoreCoordinator.putMessage(msg); } else if (msg is HelloMessage) { HelloMessage hm = (HelloMessage)msg; IPEndPoint node = new IPEndPoint( hm.getSender().Address, hm.ListeningPort ); if (node.Equals(me)) return; // try to add new node TcpSender.getInstance().AddServerNode(node, queue); } else { Logger.getInstance().log( "Undelivered message due to brainsplit: " + msg.toString(), LOGGING_NAME, Logger.Level.WARNING); } } }
public void processHelloMessage(HelloMessage msg) { IPEndPoint node = new IPEndPoint( msg.getSender().Address, msg.ListeningPort ); if (node.Equals(me)) return; Logger.getInstance().log( "Processing hello from - " + node.ToString() + " : " + msg.toString(), LOGGING_NAME, Logger.Level.INFO); TcpSender.getInstance().AddServerNode(node, queue); updateNodeSyncInfo(node, msg.Tables); }
private void ReceiveVoiceAsync(CancellationToken cancelToken) { try { byte[] packet, decodingBuffer = null, nonce = null, result; int packetLength, resultOffset, resultLength; IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, 0); if ((_client.Config.VoiceMode & DiscordVoiceMode.Incoming) != 0) { decodingBuffer = new byte[MaxOpusSize]; nonce = new byte[24]; } while (!cancelToken.IsCancellationRequested) { Thread.Sleep(1); if (_udp.Available > 0) { packet = _udp.Receive(ref endpoint); packetLength = packet.Length; if (packetLength > 0 && endpoint.Equals(_endpoint)) { if (_state != (int)WebSocketState.Connected) { if (packetLength != 70) return; int port = packet[68] | packet[69] << 8; string ip = Encoding.ASCII.GetString(packet, 4, 70 - 6).TrimEnd('\0'); var login2 = new VoiceLogin2Command(); login2.Payload.Protocol = "udp"; login2.Payload.SocketData.Address = ip; login2.Payload.SocketData.Mode = _encryptionMode; login2.Payload.SocketData.Port = port; QueueMessage(login2); if ((_client.Config.VoiceMode & DiscordVoiceMode.Incoming) == 0) return; } else { //Parse RTP Data if (packetLength < 12) return; byte flags = packet[0]; if (flags != 0x80) return; byte payloadType = packet[1]; if (payloadType != 0x78) return; ushort sequenceNumber = (ushort)((packet[2] << 8) | packet[3] << 0); uint timestamp = (uint)((packet[4] << 24) | (packet[5] << 16) | (packet[6] << 8) | (packet[7] << 0)); uint ssrc = (uint)((packet[8] << 24) | (packet[9] << 16) | (packet[10] << 8) | (packet[11] << 0)); //Decrypt if (_isEncrypted) { if (packetLength < 28) //12 + 16 (RTP + Poly1305 MAC) return; Buffer.BlockCopy(packet, 0, nonce, 0, 12); int ret = Sodium.Decrypt(packet, 12, packetLength - 12, decodingBuffer, nonce, _secretKey); if (ret != 0) continue; result = decodingBuffer; resultOffset = 0; resultLength = packetLength - 28; } else //Plain { result = packet; resultOffset = 12; resultLength = packetLength - 12; } /*if (_logLevel >= LogMessageSeverity.Debug) RaiseOnLog(LogMessageSeverity.Debug, $"Received {buffer.Length - 12} bytes.");*/ string userId; if (_ssrcMapping.TryGetValue(ssrc, out userId)) RaiseOnPacket(userId, _channelId, result, resultOffset, resultLength); } } } } } catch (OperationCanceledException) { } catch (InvalidOperationException) { } //Includes ObjectDisposedException }
private async Task ReceiveVoiceAsync(CancellationToken cancelToken) { var closeTask = cancelToken.Wait(); try { byte[] packet, decodingBuffer = null, nonce = null, result; int packetLength, resultOffset, resultLength; IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, 0); if ((_config.Mode & AudioMode.Incoming) != 0) { decodingBuffer = new byte[MaxOpusSize]; nonce = new byte[24]; } while (!cancelToken.IsCancellationRequested) { await Task.Delay(1); if (_udp.Available > 0) { #if !DOTNET5_4 packet = _udp.Receive(ref endpoint); #else //TODO: Is this really the only way to end a Receive call in DOTNET5_4? var receiveTask = _udp.ReceiveAsync(); var task = Task.WhenAny(closeTask, receiveTask).Result; if (task == closeTask) break; var udpPacket = receiveTask.Result; packet = udpPacket.Buffer; endpoint = udpPacket.RemoteEndPoint; #endif packetLength = packet.Length; if (packetLength > 0 && endpoint.Equals(_endpoint)) { if (State != ConnectionState.Connected) { if (packetLength != 70) return; string ip = Encoding.UTF8.GetString(packet, 4, 70 - 6).TrimEnd('\0'); int port = packet[68] | packet[69] << 8; SendSelectProtocol(ip, port); if ((_config.Mode & AudioMode.Incoming) == 0) return; //We dont need this thread anymore } else { //Parse RTP Data if (packetLength < 12) return; if (packet[0] != 0x80) return; //Flags if (packet[1] != 0x78) return; //Payload Type ushort sequenceNumber = (ushort)((packet[2] << 8) | packet[3] << 0); uint timestamp = (uint)((packet[4] << 24) | (packet[5] << 16) | (packet[6] << 8) | (packet[7] << 0)); uint ssrc = (uint)((packet[8] << 24) | (packet[9] << 16) | (packet[10] << 8) | (packet[11] << 0)); //Decrypt if (_isEncrypted) { if (packetLength < 28) //12 + 16 (RTP + Poly1305 MAC) return; Buffer.BlockCopy(packet, 0, nonce, 0, 12); int ret = SecretBox.Decrypt(packet, 12, packetLength - 12, decodingBuffer, nonce, _secretKey); if (ret != 0) continue; result = decodingBuffer; resultOffset = 0; resultLength = packetLength - 28; } else //Plain { result = packet; resultOffset = 12; resultLength = packetLength - 12; } /*if (_logLevel >= LogMessageSeverity.Debug) RaiseOnLog(LogMessageSeverity.Debug, $"Received {buffer.Length - 12} bytes.");*/ ulong userId; if (_ssrcMapping.TryGetValue(ssrc, out userId)) OnFrameReceived(userId, Channel.Id, result, resultOffset, resultLength); } } } } } catch (OperationCanceledException) { } catch (InvalidOperationException) { } //Includes ObjectDisposedException }
// Methods ============================================================================ /// <summary> /// Start TcpServer /// </summary> /// <param name="ep"></param> public override void Start(IPEndPoint ep) { // Verify IPEndPoints IPEndPoint[] globalEPs = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners(); foreach (IPEndPoint globalEP in globalEPs) { if (ep.Equals(globalEP)) throw new ApplicationException(ep.ToString() + " is in listening."); } // Initialize the listenEP field of ListenerState server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); server.Bind(ep); server.Listen(100); socketTable.Add(server); Thread thread = new Thread(() => { /// ** Report ListenerStarted event if (ListenStarted != null) ListenStarted(this, new ListenEventArgs(ep)); while (true) { lock (socketLocker) { if (socketRemoving.Count != 0) { foreach (var item in socketRemoving) { if (socketTable.Contains(item)) { socketTable.Remove(item); if (item == server) { /// ** Report ListenerStopped event if (ListenStopped != null) ListenStopped(this, new ListenEventArgs(item.LocalEndPoint)); item.Close(); } else { /// ** Report ClientConnect event if (ClientDisconn != null) ClientDisconn(this, new ClientEventArgs(item.LocalEndPoint, item.RemoteEndPoint, null)); item.Close(); } } } socketRemoving.Clear(); } } if (socketTable.Count == 0) break; // 只有主线程可以写 socketTable, 所以主线程的 socketTable 读取,在主线程内无需加锁 ArrayList list = new ArrayList(socketTable); Socket.Select(list, null, null, 500); HandleSelect(list); } }); thread.IsBackground = true; thread.Start(); }
/* * Commands are received asynchronously. OnReceive is the handler for them. */ private void OnReceive(IAsyncResult ar) { try { EndPoint receivedFromEP = new IPEndPoint(IPAddress.Any, 0); //Get the IP from where we got a message. clientSocket.EndReceiveFrom(ar, ref receivedFromEP); //Convert the bytes received into an object of type Data. Data msgReceived = new Data(byteData); //Act according to the received message. switch (msgReceived.cmdCommand) { //We have an incoming call. case Command.Invite: { if (bIsCallActive == false) { //We have no active call. //Ask the user to accept the call or not. if (MessageBox.Show("Call coming from " + msgReceived.strName + ".\r\n\r\nAccept it?", "VoiceChat", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { SendMessage(Command.OK, receivedFromEP); vocoder = msgReceived.vocoder; otherPartyEP = receivedFromEP; otherPartyIP = (IPEndPoint)receivedFromEP; InitializeCall(); } else { //The call is declined. Send a busy response. SendMessage(Command.Busy, receivedFromEP); } } else { //We already have an existing call. Send a busy response. SendMessage(Command.Busy, receivedFromEP); } break; } //OK is received in response to an Invite. case Command.OK: { //Start a call. InitializeCall(); break; } //Remote party is busy. case Command.Busy: { MessageBox.Show("User busy.", "VoiceChat", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); break; } case Command.Bye: { //Check if the Bye command has indeed come from the user/IP with which we have //a call established. This is used to prevent other users from sending a Bye, which //would otherwise end the call. if (receivedFromEP.Equals (otherPartyEP) == true) { //End the call. UninitializeCall(); } break; } } byteData = new byte[1024]; //Get ready to receive more commands. clientSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref receivedFromEP, new AsyncCallback(OnReceive), null); } catch (Exception ex) { MessageBox.Show(ex.Message, "VoiceChat-OnReceive ()", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
/// <summary> /// Gets or creates source. This method also does RFC 3550 8.2 "Collision Resolution and Loop Detection". /// </summary> /// <param name="rtcp_rtp">If true <b>src</b> is RTCP identifier, otherwise RTP identifier.</param> /// <param name="src">Source SSRC or CSRC identifier.</param> /// <param name="cname">RTCP SDES chunk CNAME. Must be passed only if <b>src</b> if from RTCP SDES chunk.</param> /// <param name="packetEP">Packet sender end point.</param> /// <returns>Returns specified source. Returns null if source has "collision or loop".</returns> /// <exception cref="ArgumentNullException">Is raised when <b>packetEP</b> is null reference.</exception> private RTP_Source_Remote GetOrCreateSource(bool rtcp_rtp,uint src,string cname,IPEndPoint packetEP) { if(packetEP == null){ throw new ArgumentNullException("packetEP"); } /* RFC 3550 8.2. if(SSRC or CSRC identifier is not found in the source identifier table){ create a new entry storing the data or control source transport address, the SSRC or CSRC and other state; } else if(table entry was created on receipt of a control packet and this is the first data packet or vice versa){ store the source transport address from this packet; } else if(source transport address from the packet does not match the one saved in the table entry for this identifier){ // An identifier collision or a loop is indicated if(source identifier is not the participant's own){ // OPTIONAL error counter step if(source identifier is from an RTCP SDES chunk containing a CNAME item that differs from the CNAME in the table entry){ count a third-party collision; } else{ count a third-party loop; } abort processing of data packet or control element; // MAY choose a different policy to keep new source } // A collision or loop of the participant's own packets else if(source transport address is found in the list of conflicting data or control source transport addresses){ // OPTIONAL error counter step if(source identifier is not from an RTCP SDES chunk containing a CNAME item or CNAME is the participant's own){ count occurrence of own traffic looped; } mark current time in conflicting address list entry; abort processing of data packet or control element; } // New collision, change SSRC identifier else{ log occurrence of a collision; create a new entry in the conflicting data or control source transport address list and mark current time; send an RTCP BYE packet with the old SSRC identifier; choose a new SSRC identifier; create a new entry in the source identifier table with the old SSRC plus the source transport address from the data or control packet being processed; } } */ RTP_Source source = null; lock(m_pMembers){ m_pMembers.TryGetValue(src,out source); // SSRC or CSRC identifier is not found in the source identifier table. if(source == null){ source = new RTP_Source_Remote(this,src); if(rtcp_rtp){ source.SetRtcpEP(packetEP); } else{ source.SetRtpEP(packetEP); } m_pMembers.Add(src,source); } // Table entry was created on receipt of a control packet and this is the first data packet or vice versa. else if((rtcp_rtp ? source.RtcpEP : source.RtpEP) == null){ if(rtcp_rtp){ source.SetRtcpEP(packetEP); } else{ source.SetRtpEP(packetEP); } } // Source transport address from the packet does not match the one saved in the table entry for this identifier. else if(!packetEP.Equals((rtcp_rtp ? source.RtcpEP : source.RtpEP))){ // Source identifier is not the participant's own. if(!source.IsLocal){ if(cname != null && cname != source.CName){ m_RemoteCollisions++; } else{ m_RemotePacketsLooped++; } return null; } // A collision or loop of the participant's own packets. else if(m_pConflictingEPs.ContainsKey(packetEP.ToString())){ if(cname == null || cname == source.CName){ m_LocalPacketsLooped++; } m_pConflictingEPs[packetEP.ToString()] = DateTime.Now; return null; } // New collision, change SSRC identifier. else{ m_LocalCollisions++; m_pConflictingEPs.Add(packetEP.ToString(),DateTime.Now); // Remove SSRC from members,senders. Choose new SSRC, CNAME new and BYE old. m_pMembers.Remove(source.SSRC); m_pSenders.Remove(source.SSRC); uint oldSSRC = source.SSRC; source.GenerateNewSSRC(); // Ensure that new SSRC is not in use, if so repaeat while not conflicting SSRC. while(m_pMembers.ContainsKey(source.SSRC)){ source.GenerateNewSSRC(); } m_pMembers.Add(source.SSRC,source); RTCP_CompoundPacket compoundPacket = new RTCP_CompoundPacket(); RTCP_Packet_RR rr = new RTCP_Packet_RR(); rr.SSRC = m_pRtcpSource.SSRC; compoundPacket.Packets.Add(rr); RTCP_Packet_SDES sdes = new RTCP_Packet_SDES(); RTCP_Packet_SDES_Chunk sdes_chunk = new RTCP_Packet_SDES_Chunk(source.SSRC,m_pSession.LocalParticipant.CNAME); sdes.Chunks.Add(sdes_chunk); compoundPacket.Packets.Add(sdes); RTCP_Packet_BYE bye = new RTCP_Packet_BYE(); bye.Sources = new uint[]{oldSSRC}; bye.LeavingReason = "Collision, changing SSRC."; compoundPacket.Packets.Add(bye); SendRtcpPacket(compoundPacket); //---------------------------------------------------------------------- // Add new source to members, it's not conflicting any more, we changed SSRC. source = new RTP_Source_Remote(this,src); if(rtcp_rtp){ source.SetRtcpEP(packetEP); } else{ source.SetRtpEP(packetEP); } m_pMembers.Add(src,source); } } } return (RTP_Source_Remote)source; }
public void OnLatencyConnectClosed(IPEndPoint endPoint) { if (endPoint.Equals(this.remoteEndPointTcp)) { this.fiber.Schedule(this.StartTcpLatencyMonitor, 1000); } else if (endPoint.Equals(this.remoteEndPointUdp)) { this.fiber.Schedule(this.StartUdpLatencyMonitor, 1000); } }
/// <summary> /// compare the endpoint.<para/> /// if endpoint address is null, compare the port.<para/> /// then, compare the address and port. /// </summary> /// <param name="ep"> /// an IPEndPoint object to compare. /// </param> /// <returns> /// if equal, return true; otherwise, false. /// </returns> private bool CompareUdpPacketOrBytes(IPEndPoint ep) { IPEndPoint localEP = this.endpoint as IPEndPoint; // if the address is null, compare the port. if (localEP.Address == null && ep != null) { if (ep != null && ep.Port == localEP.Port) { return true; } } // compare the endpoint. if (ep == null || !ep.Equals(this.endpoint)) { return false; } return true; }
/// <summary> /// Set information needed to send and receive a DTLS connection /// </summary> /// <param name="ssl">structure to set information in</param> /// <param name="udp">UDP object to send and receive</param> /// <param name="ep">End point of connection</param> /// <returns>1 on success</returns> public static int set_dtls_fd(IntPtr ssl, UdpClient udp, IPEndPoint ep) { /* sanity check on inputs */ if (ssl == IntPtr.Zero) { return FAILURE; } try { if (!udp.Equals(null) && !ep.Equals(null)) { IntPtr ptr; DTLS_con con; GCHandle gch = GCHandle.FromIntPtr(ssl); ctx_handles handles = (ctx_handles)gch.Target; GCHandle fd_pin; con = new DTLS_con(); con.udp = udp; con.ep = ep; fd_pin = GCHandle.Alloc(con); handles.set_fd(fd_pin); ptr = GCHandle.ToIntPtr(fd_pin); wolfSSL_SetIOWriteCtx(handles.get_ctx(), ptr); //pass along the socket for writing to wolfSSL_SetIOReadCtx(handles.get_ctx(), ptr); //pass along the socket for reading from return SUCCESS; } return FAILURE; } catch (Exception e) { log(ERROR_LOG, "Error setting up fd!! " + e.ToString()); return FAILURE; } }
/// <summary> /// Sends specified UDP packet to the specified remote end point. /// </summary> /// <param name="localEP">Local end point to use for sending.</param> /// <param name="packet">UDP packet to send.</param> /// <param name="offset">Offset in the buffer.</param> /// <param name="count">Number of bytes to send.</param> /// <param name="remoteEP">Remote end point.</param> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="InvalidOperationException">Is raised whan UDP server is not running and this method is accessed.</exception> /// <exception cref="ArgumentNullException">Is raised when any of the arumnets is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public void SendPacket(IPEndPoint localEP,byte[] packet,int offset,int count,IPEndPoint remoteEP) { if(m_IsDisposed){ throw new ObjectDisposedException("UdpServer"); } if(!m_IsRunning){ throw new InvalidOperationException("UDP server is not running."); } if(packet == null){ throw new ArgumentNullException("packet"); } if(localEP == null){ throw new ArgumentNullException("localEP"); } if(remoteEP == null){ throw new ArgumentNullException("remoteEP"); } if(localEP.AddressFamily != remoteEP.AddressFamily){ throw new ArgumentException("Argumnet localEP and remoteEP AddressFamily won't match."); } // Search specified local end point socket. Socket socket = null; if(localEP.AddressFamily == AddressFamily.InterNetwork){ foreach(Socket s in m_pSendSocketsIPv4.ToArray()){ if(localEP.Equals((IPEndPoint)s.LocalEndPoint)){ socket = s; break; } } } else if(localEP.AddressFamily == AddressFamily.InterNetworkV6){ foreach(Socket s in m_pSendSocketsIPv6.ToArray()){ if(localEP.Equals((IPEndPoint)s.LocalEndPoint)){ socket = s; break; } } } else{ throw new ArgumentException("Argument 'localEP' has unknown AddressFamily."); } // We don't have specified local end point. if(socket == null){ throw new ArgumentException("Specified local end point '" + localEP + "' doesn't exist."); } IPEndPoint lEP = null; SendPacket(socket,packet,offset,count,remoteEP,out lEP); }
/// <summary> /// Static method to get/create a PhysicalSocket /// </summary> /// <param name="endPoint">The binded end point</param> internal static PhysicalSocket GetInstance(IPEndPoint endPoint) { lock (_physicals) { PhysicalSocket physical; bool isAnyEndPoint = endPoint.Equals(new IPEndPoint(IPAddress.Any, 0)); // Check if there is already an existing instance if (!isAnyEndPoint) { if (_physicals.TryGetValue(endPoint, out physical)) return physical; // In case no instance exists, create one physical = new PhysicalSocket(); physical.Bind(endPoint); RegisterPhysicalSocket(physical); _physicals.Add(endPoint, physical); } else { physical = new PhysicalSocket(); while (true) { int port = new Random().Next(Int16.MaxValue); IPAddress localAddress = LocalIPAddress(ProtocolType.IPv4); endPoint = new IPEndPoint(localAddress, port); // In case no instance exists, create one try { physical.Bind(endPoint); break; } catch { } } RegisterPhysicalSocket(physical); _physicals.Add(endPoint, physical); } return physical; } }
public Property HeliosTransport_should_map_valid_IPEndpoints_to_Address(IPEndPoint endpoint) { var addr = HeliosTransport.MapSocketToAddress(endpoint, "akka.tcp", "foo"); var parsedEp = (IPEndPoint)HeliosTransport.AddressToSocketAddress(addr); return endpoint.Equals(parsedEp).Label("Should be able to parse endpoint to address and back"); }
static bool IsLocalAddress(IPEndPoint a_localAddr, IPEndPoint a_cmpAddr) { if (a_localAddr.Equals(a_cmpAddr)) return true; if (a_localAddr.Port != a_cmpAddr.Port) return false; if (a_localAddr.Address.Equals(IPAddress.Any)) { IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName()); foreach (IPAddress addr in host.AddressList) { if (addr.AddressFamily == AddressFamily.InterNetwork) { if (addr.Equals(a_cmpAddr.Address)) return true; } } } return false; }
public MFTestResults NetTest5_IPEndPointBasic() { /// <summary> /// 1. Creates 30 Random IPs between 0.0.0.0 and 255.255.255.127 /// 2. Verifies that they can be constructed as IPEndPoints with both ctors /// 3. Verifies that their data, ToString and GetHashCode funcs return normally /// 4. Clones one with Create and verifies the above funcs again /// </summary> /// bool testResult = true; try { Random random = new Random(); for (int i = 0; i <= 30; i++) { int[] IPInts = { random.Next(256), random.Next(256), random.Next(256), random.Next(128) }; int portInt = random.Next(65535) + 1; long addressLong = (long)( IPInts[0] + IPInts[1] * 256 + IPInts[2] * 256 * 256 + IPInts[3] * 256 * 256 * 256); Log.Comment("Random IP " + IPInts[0] + "." + IPInts[1] + "." + IPInts[2] + "." + IPInts[3] + ":" + portInt); IPAddress address = new IPAddress(addressLong); Log.Comment("EndPoint1 created with IPAddress and int"); IPEndPoint endPoint1 = new IPEndPoint(address,portInt); Log.Comment("EndPoint2 created with long and int"); IPEndPoint endPoint2 = new IPEndPoint(addressLong, portInt); if (endPoint1 == null) throw new Exception("EndPoint1 is null"); if (endPoint2 == null) throw new Exception("EndPoint2 is null"); Type typeOfEndPoint = endPoint1.GetType(); if (typeOfEndPoint != Type.GetType("System.Net.IPEndPoint")) throw new Exception("EndPoint1 Type is incorrect"); typeOfEndPoint = endPoint2.GetType(); if (typeOfEndPoint != Type.GetType("System.Net.IPEndPoint")) throw new Exception("EndPoint2 Type is incorrect"); if (endPoint1.ToString() != endPoint2.ToString()) throw new Exception("ToString returns differently for same data"); if (!endPoint1.Equals(endPoint2)) { throw new Exception("Equals returns false for same data"); } int hashCode1 = endPoint1.GetHashCode(); int hashCode2 = endPoint2.GetHashCode(); if (hashCode1 != hashCode2) throw new Exception("GetHasCode returns differently for same data"); if (endPoint1.Address.ToString() != endPoint2.Address.ToString() || endPoint1.Address.ToString() != address.ToString() || endPoint2.Address.ToString() != address.ToString()) throw new Exception("Address returns wrong data"); if (endPoint1.Port != endPoint2.Port || endPoint1.Port != portInt || endPoint2.Port != portInt) throw new Exception("Port returns wrong data"); Log.Comment("Cloning Enpoint1 into EndPoint2"); endPoint2 = (IPEndPoint)endPoint2.Create(endPoint1.Serialize()); typeOfEndPoint = endPoint2.GetType(); if (typeOfEndPoint != Type.GetType("System.Net.IPEndPoint")) throw new Exception("EndPoint2 Type is incorrect after clone"); if (endPoint1.ToString() != endPoint2.ToString()) throw new Exception("ToString returns differently for cloned data"); //21295 GetHashCode returns differently for cloned data if (endPoint1.GetHashCode() != endPoint2.GetHashCode()) throw new Exception("GetHashCode returns differently for cloned data"); if (endPoint1.Address.ToString() != endPoint2.Address.ToString() || endPoint1.Address.ToString() != address.ToString() || endPoint2.Address.ToString() != address.ToString()) throw new Exception("Address returns wrong data after clone"); if (endPoint1.Port != endPoint2.Port || endPoint1.Port != portInt || endPoint2.Port != portInt) throw new Exception("Port returns wrong data after clone"); Log.Comment("Recreating EndPoint2 with new data"); int portInt2 = portInt % 2 + 1; long addressLong2 = (long)( (IPInts[0] % 2 + 1) + (IPInts[1] % 2 + 1 )* 256 + (IPInts[2] % 2 + 1 )* 256 * 256 + (IPInts[3] % 2 + 1 )* 256 * 256 * 256); endPoint2 = new IPEndPoint(addressLong2, portInt2); if (endPoint1.GetHashCode() == endPoint2.GetHashCode()) throw new Exception("GetHashCode returns same for " + endPoint1.ToString() + " as " + endPoint2.ToString()); if (endPoint1.Address == endPoint2.Address || endPoint2.Address == address) throw new Exception("Address returns wrong data after change"); if (endPoint1.Port == endPoint2.Port || endPoint2.Port == portInt) throw new Exception("Port returns wrong data after change"); } } catch (Exception e) { Log.Comment("Caught exception: " + e.Message); testResult = false; } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); }
public override bool Equals(object obj) { return(mIPEndPoint.Equals(((MyEndPoint)obj).IpEndPoint)); }
public void Start(UInt16 port, IEnumerable<IHttpProcessor> processors) { Trace.TraceInformation("Starting"); lock (sync) { if (disposed) throw new ObjectDisposedException(Texts.ServerWasDisposed); if (processors != null) this.processors = processors.ToArray(); var endPoint = new IPEndPoint(IPAddress.Any, port); Trace.TraceInformation("\tEndpoint: {0}", endPoint); if (Status == HttpServerStatus.Started) { var current = (IPEndPoint) socket.LocalEndPoint; if (endPoint.Equals(current)) return; throw AtlasException.ServerAlreadyRunning(current); } socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Bind(endPoint); socket.Listen(0); continueRunning = true; threadLoop = new Thread(ProcessSocketConnections); threadLoop.Start(); Status = HttpServerStatus.Started; Trace.TraceInformation("\tStarted"); } }
private void HandleDisconnect(string msg, IPEndPoint source) { if (source.Equals(masterEP)) { Logger.Info("Slave disconnected. Master at " + masterEP + " signalled disconnect."); connected = false; if (OnDisconnected != null) OnDisconnected(this, null); } }
public void update() { try { while (socket.Available > 0) { IPEndPoint observedEndpoint = new IPEndPoint(IPAddress.Any, 0); byte[] bytes = null; try { bytes = socket.Receive(ref observedEndpoint); } catch (System.Net.Sockets.SocketException except) { _debug("[CS] Receive threw an exception. Socket Error : " + except.SocketErrorCode); onLostConnection(); continue; } _debug("[CS] Incoming message of length " + bytes.Length.ToString() + " : " + BitConverter.ToString(bytes)); _debug("[CS] It appears to have come from " + observedEndpoint.ToString()); if (!observedEndpoint.Equals(serverAddress)) { _debug("[CS] I don't know who this message is from."); continue; } var datagram = new ReadOnlyDatagram(bytes); uint messageType = 0; uint ackID = 0; if (!datagram.ReadUInt(out messageType, 8)) goto OnBadMessage; if (!datagram.ReadUInt(out ackID, 32)) goto OnBadMessage; if (ackID != 0) _sendAckMessage(ackID); if (messageType != (uint)ServerToClientMessage.Acknowledge && ackID != 0 && duplicateDatagramDetector.newDatagramReceived(ackID) == RemotePeer.DatagramResponse.Ignore) continue; switch ((ServerToClientMessage)messageType) { case ServerToClientMessage.Acknowledge: _removeCriticalDatagram(ackID); break; case ServerToClientMessage.Keepalive: { //Ack response already handled } break; case ServerToClientMessage.PeerJoined: { var guidBytes = new byte[16]; if (!datagram.ReadBytes(guidBytes, 16)) goto OnBadMessage; var peerGuid = new Guid(guidBytes); var newPeer = new Peer { Guid = peerGuid }; if (onPeerJoined != null) onPeerJoined(newPeer); peers.Add(newPeer); } break; case ServerToClientMessage.PeerLeft: { var guidBytes = new byte[16]; if (!datagram.ReadBytes(guidBytes, 16)) goto OnBadMessage; var peerGuid = new Guid(guidBytes); var peer = findPeer(peerGuid); if (onPeerLeft != null) onPeerLeft(peer); peers.Remove(peer); } break; case ServerToClientMessage.Datagram: { _debug("[CS] I received a datagram from the server. It was " + (bytes.Length - 5).ToString() + " bytes long."); if (bytes.Length - 5 <= 0) goto OnBadMessage; byte[] data = new byte[bytes.Length - 5]; if (!datagram.ReadBytes(data, (uint)(bytes.Length - 5))) goto OnBadMessage; if (onDatagramReceived != null) { try { onDatagramReceived(data); } catch (Exception) { } } break; } } continue; OnBadMessage: { _debug("[CS] I received a bad message."); } } var now = DateTime.Now; for (int i = 0; i < criticalDatagrams.Count; ) { var criticalDatagram = criticalDatagrams[i]; var timeDelta = now - criticalDatagram.lastSendAttempt; if (timeDelta.TotalMilliseconds > millisecondsBeforeRetry) { if (criticalDatagram.sendAttempts >= retryAttempts) { _debug("[CS] I was not able to deliver critical packet " + criticalDatagram.ackID + "."); criticalDatagrams.RemoveAt(i); _onLostConnection(); continue; } criticalDatagram.sendAttempts += 1; _debug("[CS] I am trying to send critical packet " + criticalDatagram.ackID + ". [" + criticalDatagram.sendAttempts + " attempts]"); criticalDatagram.lastSendAttempt = now; _send(criticalDatagram.data); } ++i; } } catch (Exception e) { _debug("[CS] " + e.Message + "\n" + e.StackTrace); } }
public void FinishAccept(byte[] buffer, int offset, int length, IPEndPoint remoteEndPoint, IPEndPoint localEndPoint) { ResetForNextRequest(); ReceiveBufferPos = 0; _remoteEndPoint = remoteEndPoint; _knownIsLocal = false; _remoteIpAddress = null; _remotePort = null; if (!localEndPoint.Equals(_localEndPoint)) { _localEndPoint = localEndPoint; _localIpAddress = null; _localPort = null; } _receiveBufferFullness = StartBufferOffset; _receiving = true; FinishReceive(buffer, offset, length); }
public void Ctor_IPAddressInt () { Assert.Throws<ArgumentNullException> (delegate { new IPEndPoint (null, 80); }, "IPEndPoint(null,int)"); IPAddress a = new IPAddress (new byte [16]); Assert.AreEqual (AddressFamily.InterNetworkV6, a.AddressFamily, "IPAddress.AddressFamily"); IPEndPoint ep = new IPEndPoint (a, 0); Assert.IsTrue (Object.ReferenceEquals (a, ep.Address), "Address"); Assert.AreEqual (AddressFamily.InterNetworkV6, ep.AddressFamily, "AddressFamily"); Assert.AreEqual (0, ep.Port, "Port"); Assert.Throws<ArgumentException> (delegate { SocketAddress sa = new SocketAddress (AddressFamily.InterNetwork); ep.Create (sa); }, "Create(InterNetwork)"); Assert.Throws<ArgumentException> (delegate { SocketAddress sa = new SocketAddress (AddressFamily.Unknown); ep.Create (sa); }, "Create(Unknown)"); Assert.Throws<ArgumentException> (delegate { SocketAddress sa = new SocketAddress (AddressFamily.Unspecified); ep.Create (sa); }, "Create(Unspecified)"); EndPoint ep2 = ep.Create (new SocketAddress (AddressFamily.InterNetworkV6)); Assert.IsFalse (ep.Equals (null), "Equals(null)"); Assert.IsTrue (ep.Equals (ep), "Equals(self)"); Assert.IsTrue (ep.Equals (ep2), "Equals(Create)"); Assert.AreEqual ("InterNetworkV6:28:{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}", ep.Serialize ().ToString (), "Serialize"); // Assert.AreEqual ("0000:0000:0000:0000:0000:0000:0.0.0.0:0", ep.ToString (), "ToString"); }
public void OnLatencyMonitorConnectFailed(IPEndPoint endPoint, int errorCode, string errorMessage) { log.ErrorFormat("Latency monitor connection to {0} failed with err {1}: {2}, serverId={3}", endPoint, errorCode, errorMessage, GameApplication.ServerId); if (endPoint.Equals(this.remoteEndPointTcp)) { this.fiber.Schedule(this.StartTcpLatencyMonitor, 1000); } else if (endPoint.Equals(this.remoteEndPointUdp)) { this.fiber.Schedule(this.StartUdpLatencyMonitor, 1000); } }
public void CreateAndSerialize() { SocketAddress addr = endPoint1.Serialize (); EndPoint endPoint3 = endPoint2.Create (addr); Assert.IsTrue (endPoint1.Equals (endPoint3), "#1"); IPAddress ipAddress = IPAddress.Parse ("255.255.255.255"); IPEndPoint endPoint4 = new IPEndPoint (ipAddress, MyMaxPort); addr = endPoint4.Serialize (); EndPoint endPoint5 = endPoint2.Create(addr); Assert.IsTrue (endPoint4.Equals (endPoint5), "#2"); Assert.AreEqual (endPoint5.ToString (), "255.255.255.255:" + MyMaxPort, "#3"); }
/* * Commands are received asynchronously. OnReceive is the handler for them. */ private void OnReceive(IAsyncResult ar) { //TODO: Switch Receive Commands try { EndPoint receivedFromEP = new IPEndPoint(IPAddress.Any, 0); //Get the IP from where we got a message. clientSocket.EndReceiveFrom(ar, ref receivedFromEP); //Convert the bytes received into an object of type Data. Data msgReceived = new Data(byteData); //Act according to the received message. switch (msgReceived.cmdCommand) { case Command.ChangeVocoderALaw: if (IsServiceStarted && eMode == Mode.Client && receivedFromEP.Equals(serverEP)) { cGlobalVars.AddLogChat("El servidor cambio el modo a ALaw"); //Cambiamos el combo box SetCodecCombo(1); } break; case Command.ChangeVocoderNone: if (IsServiceStarted && eMode == Mode.Client && receivedFromEP.Equals(serverEP)) { cGlobalVars.AddLogChat("El servidor cambio el modo a None"); //cmbCodecs.SelectedIndex = 0; SetCodecCombo(0); } break; case Command.ChangeVocoderuLaw: if (IsServiceStarted && eMode == Mode.Client && receivedFromEP.Equals(serverEP)) { cGlobalVars.AddLogChat("El servidor cambio el modo a uLaw"); SetCodecCombo(2); } break; //MODO SERVER: recepción de invitación por parte de cliente. case Command.Invite: { if (IsServiceStarted && eMode == Mode.Server) { cGlobalVars.AddLogChat("Se ha conectado: " + receivedFromEP.ToString()); vocoder = msgReceived.vocoder; lock (clientIPs) { if (!ExistsIp((IPEndPoint)receivedFromEP)) clientIPs.Add((IPEndPoint)receivedFromEP); } SendMessage(Command.OK, receivedFromEP); } break; } //CLIENTE: Respuesta del servidor de nuestra petición de conexión case Command.OK: { if (eMode == Mode.PreClient && receivedFromEP.Equals(serverEP)) { eMode = Mode.Client; } break; } //Remote party is busy. case Command.Bye: { //Check if the Bye command has indeed come from the user/IP with which we have //a call established. This is used to prevent other users from sending a Bye, which //would otherwise end the call. if (IsServiceStarted && eMode == Mode.Client && receivedFromEP.Equals(serverEP)) { bStop = true; cGlobalVars.AddLogChat("Received by from server: Disconnecting"); //End the call. UninitializeCall(); } break; } } byteData = new byte[1024]; //Get ready to receive more commands. if (!bStop) clientSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref receivedFromEP, new AsyncCallback(OnReceive), null); } catch (Exception ex) { //MessageBox.Show(ex.Message, "VoiceChat-OnReceive ()", MessageBoxButtons.OK, MessageBoxIcon.Error); cGlobalVars.AddLogChat("VoiceChat-OnReceive () > " + ex.Message); } }
public void SetEp(IPEndPoint ep) { if (ep.Equals(_ep)) { return; } Stop(null); _ep = ep; }