public UdpFactory(int port) { ListenPort = port; udpClient = new UdpClient(port); udpClient.DontFragment = false; udpClient.AllowNatTraversal(true); }
/// <summary> /// UDP接收器 /// </summary> /// <param name="listenPort">监听的端口</param> public UdpReceiver(int listenPort) { this.Encoding = Encoding.Default; this.ListenPort = listenPort; udpClient = new UdpClient(listenPort); udpClient.AllowNatTraversal(true); }
protected override void OnConnect() { _udp = new UdpClient(new IPEndPoint(IPAddress.Any, 0)); _udp.AllowNatTraversal(true); _isReady = false; _isClearing = false; }
public UDPProtocol(int localPort) { this.localPort = localPort; udpClient = new System.Net.Sockets.UdpClient(localPort); udpClient.AllowNatTraversal(true); this.serverIPEndPoint = new IPEndPoint(IPAddress.Parse(serverIP), serverPort); }
public UdpStreamSender() { _queue = new ConcurrentQueue<StreamPacket>(); _waiter = new ManualResetEvent(false); _udpClient = new UdpClient(); _udpClient.AllowNatTraversal(true); _senderThread = new Thread(new ThreadStart(WorkThread)); }
public ReceiveOperation(int opId, List<short> tOrder, ushort port) { client = new UdpClient(AddressFamily.InterNetworkV6); client.Client.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false); client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); client.AllowNatTraversal(true); client.Client.Bind(new IPEndPoint(IPAddress.IPv6Any, port)); totalCount = tOrder.Count; order = tOrder; operationID = opId; }
/// <summary> /// Instantiates an instances of the UdpServerHandler class using the specified SocketBinder and parameters. /// </summary> /// <param name="binder">SocketBinder to bind a new socket too.</param> /// <param name="port">Port used for receiving.</param> /// <param name="alignment">Default alignment in bytes for buffers.</param> /// <param name="packetHeader">Collection of bytes used for packet verification.</param> public UdpServerHandler( SocketBinder binder, int port, int alignment ) : base(binder) { Port = port; Alignment = ( alignment > 0 ) ? alignment : 1; running = false; Listener = new UdpClient( port ); Listener.EnableBroadcast = true; Listener.AllowNatTraversal( true ); }
public SendOperation(IPEndPoint dest, Packet[] data, int opId) { destination = dest; table = new Dictionary<short, byte[]>(); foreach (Packet p in data) table.Add(p.HandshakeID, p._data); operationID = opId; client = new UdpClient(AddressFamily.InterNetworkV6); client.Client.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false); client.AllowNatTraversal(true); client.Connect(dest); }
public void Initialize(int port) { Log.Debug("UDP Service Initializing on port..." + port); _base = new UdpClient(AddressFamily.InterNetworkV6); _base.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); _base.Client.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false); // Maybe change this to true to extend security ? _base.AllowNatTraversal(true); _base.Client.Bind(new IPEndPoint(IPAddress.IPv6Any, port)); _base.Client.SendBufferSize = 3 * 1024; _base.Client.ReceiveBufferSize = 3 * 1024; new Thread(xrun).Start(); }
public void retrieveHostEntries() { string hostName = Dns.GetHostName(); foreach (IPAddress interfaceIP in (from ip in Dns.GetHostEntry(hostName).AddressList where ip.AddressFamily == AddressFamily.InterNetwork select ip)) { UdpClient client = new UdpClient(); client.AllowNatTraversal(true); client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); client.Client.Bind(new IPEndPoint(interfaceIP, multicastGroup.Port)); client.JoinMulticastGroup(this.multicastGroup.Address); this.hostEntries.Add(client); } }
public void Listen() { foreach (var IP in (from ip in Dns.GetHostEntry(Dns.GetHostName()).AddressList where ip.AddressFamily == AddressFamily.InterNetwork select ip.ToString()).ToList()) { UdpClient UdpClient = new UdpClient(); UdpClient.AllowNatTraversal(true); LocalEntryPoint = new IPEndPoint(IPAddress.Parse(IP), MulticastAddress.Port); UdpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); UdpClient.Client.Bind(LocalEntryPoint); UdpClient.JoinMulticastGroup(MulticastAddress.Address, IPAddress.Parse(IP)); UdpClient.BeginReceive(ReceiveCallBack, new object[] { UdpClient, new IPEndPoint(IPAddress.Parse(IP), ((IPEndPoint)UdpClient.Client.LocalEndPoint).Port) }); } }
public static void Initialize(short port, Action<Packet> rcvHandler) { client = new UdpClient(AddressFamily.InterNetworkV6); client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); client.Client.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false); client.AllowNatTraversal(true); client.Client.Bind(new IPEndPoint(IPAddress.IPv6Any, port)); Log.Debug("Initialized UDP Router"); handler = rcvHandler; client.BeginReceive(endReceive, null); Thread t = new Thread(clear_pending); t.IsBackground = true; t.Start(); }
/// <summary> /// UDP发送器 /// </summary> /// <param name="sentToAddress">发送目的地址</param> /// <param name="sentToPort">发送目的端口</param> public UdpSender(string sentToAddress, int sentToPort) { Address = sentToAddress; Port = sentToPort; this.Encoding = Encoding.Default; queue = new ConcurrentQueue<byte[]>(); waiter = new ManualResetEvent(false); udpClient = new UdpClient(); udpClient.AllowNatTraversal(true); senderThread = new Thread(new ThreadStart(WorkThread)); }
public void Cast() { UdpClients = new List<UdpClient>(); string HostName = Dns.GetHostName(); foreach (var IP in (from ip in Dns.GetHostEntry(HostName).AddressList where ip.AddressFamily == AddressFamily.InterNetwork select ip.ToString()).ToList()) { UdpClient UdpClient = new UdpClient(new IPEndPoint(IPAddress.Parse(IP), 0)); UdpClient.AllowNatTraversal(true); UdpClient.JoinMulticastGroup(MulticastGroup.Address); UdpClients.Add(UdpClient); } string Message = "iam:" + HostName; byte[] Data = Encoding.ASCII.GetBytes(Message.ToCharArray()); while (true) { foreach (UdpClient client in UdpClients) { client.BeginSend(Data, Data.Length, MulticastGroup, null, null); } Thread.Sleep(CastDelay); } }
private void StartListeningForDiscoveryBroadcasts() { IPAddress addr = IPAddress.Parse("230.0.0.1"); IPEndPoint ep = new IPEndPoint(IPAddress.Any, 22003); client = new UdpClient(ep); client.EnableBroadcast = true; client.MulticastLoopback = true; client.AllowNatTraversal(true); client.JoinMulticastGroup(addr); UdpState s = new UdpState(); s.e = ep; s.u = client; client.BeginReceive(ReceiveCallback, s); }
/// <summary> /// Closes, resets and restarts the UDP server. /// </summary> public void Restart() { Close(); Listener = new UdpClient( Port ); Listener.EnableBroadcast = true; Listener.AllowNatTraversal( true ); Status = false; running = false; Start(); }
public void Cast(dynamic msg) { List<UdpClient> UdpClients = new List<UdpClient>(); string HostName = Dns.GetHostName(); foreach (var IP in (from ip in Dns.GetHostEntry(HostName).AddressList where ip.AddressFamily == AddressFamily.InterNetwork select ip.ToString()).ToList()) { UdpClient UdpClient = new UdpClient(new IPEndPoint(IPAddress.Parse(IP), 0)); UdpClient.AllowNatTraversal(true); UdpClient.JoinMulticastGroup(MulticastGroup.Address); UdpClients.Add(UdpClient); } if (msg.GetType() == typeof(string[])) { foreach (var m in msg) { byte[] Data = Encoding.ASCII.GetBytes(m.ToCharArray()); while (_CastTimes-- > 0) { foreach (UdpClient client in UdpClients) { client.BeginSend(Data, Data.Length, MulticastGroup, null, null); } Thread.Sleep(CastDelay); } } } else { byte[] Data = Encoding.ASCII.GetBytes(msg.ToCharArray()); while (_CastTimes-- > 0) { foreach (UdpClient client in UdpClients) { client.BeginSend(Data, Data.Length, MulticastGroup, null, null); } Thread.Sleep(CastDelay); } } }
public static SteamGameServer GetServerInfo(IPEndPoint gameServerQueryEndpoint) { byte[] startBytes = new byte[] { 0xFF, 0xFF, 0xFF, 0xFF }; byte Header = 0x54; string qryAsString = "Source Engine Query"; List <byte> qry = new List <byte>(); qry.AddRange(startBytes); qry.Add(Header); qry.AddRange(Encoding.Default.GetBytes(qryAsString)); qry.Add(0x00); ServerQueryResponse item = null; var sw = new System.Diagnostics.Stopwatch(); var buffer = new byte[2048]; using (System.Net.Sockets.UdpClient udp = new System.Net.Sockets.UdpClient()) { try { udp.Connect(gameServerQueryEndpoint); udp.AllowNatTraversal(true); udp.Client.ReceiveTimeout = 300; sw.Start(); udp.Send(qry.ToArray(), qry.Count); System.Net.Sockets.SocketError errorCode; var receivedLenght = udp.Client.Receive(buffer, 0, 2048, System.Net.Sockets.SocketFlags.None, out errorCode); sw.Stop(); if (errorCode != System.Net.Sockets.SocketError.Success) { return(null); } if (receivedLenght == buffer.Length) { throw new Exception("Buffer zu klein"); } var receivedBytes = new byte[receivedLenght]; Buffer.BlockCopy(buffer, 0, receivedBytes, 0, receivedLenght); //var receivedBytes = udp.Receive(ref endp); var enconding = System.Text.Encoding.UTF8; // System.Text.Encoding.ASCII; using (var mem = new System.IO.MemoryStream(receivedBytes)) using (var br = new System.IO.BinaryReader(mem, CharEncoding)) { br.ReadInt32(); br.ReadByte(); item = new ServerQueryResponse(); item.IpAdresse = gameServerQueryEndpoint.Address.ToString(); item.ProtocolVersion = br.ReadByte(); item.Ping = (int)sw.ElapsedMilliseconds; var count = Array.FindIndex(receivedBytes, (int)mem.Position, IsNULL) - (int)mem.Position; item.GameServerName = enconding.GetString(br.ReadBytes(count)); br.ReadByte(); // null-byte count = Array.FindIndex(receivedBytes, (int)mem.Position, IsNULL) - (int)mem.Position; item.Map = enconding.GetString(br.ReadBytes(count)); br.ReadByte(); // null-byte //item.Map = ReadStringNullTerminated(br, enconding); count = Array.FindIndex(receivedBytes, (int)mem.Position, IsNULL) - (int)mem.Position; item.Folder = enconding.GetString(br.ReadBytes(count)); br.ReadByte(); // null-byte count = Array.FindIndex(receivedBytes, (int)mem.Position, IsNULL) - (int)mem.Position; item.Game = enconding.GetString(br.ReadBytes(count)); br.ReadByte(); // null-byte item.ID = br.ReadInt16(); item.CurrentPlayerCount = br.ReadByte(); item.MaxPlayerCount = br.ReadByte(); item.CurrentBotsCount = br.ReadByte(); item.ServerType = (ServerQueryRequestType)br.ReadByte(); item.Password = br.ReadByte() == 1; item.VAC = br.ReadByte() == 1; item.Mode = br.ReadByte() == 1; count = Array.FindIndex(receivedBytes, (int)mem.Position, IsNULL) - (int)mem.Position; item.Version = enconding.GetString(br.ReadBytes(count)); br.ReadByte(); // null-byte var edfCode = br.ReadByte(); item.Data = receivedBytes; if ((edfCode & 0x80) == 0x80) { item.GamePort = br.ReadUInt16(); } if ((edfCode & 0x10) == 0x10) { item.ServerSteamId = br.ReadInt64(); } //if ((edfCode & 0x40) == 0x40) // Console.WriteLine("spectator server"); if ((edfCode & 0x20) == 0x20) { count = Array.FindIndex(receivedBytes, (int)mem.Position, IsNULL) - (int)mem.Position; item.Keywords = enconding.GetString(br.ReadBytes(count)); br.ReadByte(); // null-byte } if ((edfCode & 0x01) == 0x01) { item.GameID = br.ReadInt64(); } // https://community.bistudio.com/wiki/STEAMWORKSquery // https://developer.valvesoftware.com/wiki/Master_Server_Query_Protocol } RequestRules(item, udp); if (item.CurrentPlayerCount > 0) { udp.Client.ReceiveTimeout = Math.Max(300, Convert.ToInt32((6d * item.CurrentPlayerCount))); RequestPlayers(item, udp); } } catch { sw.Stop(); } } return(item != null ? new SteamGameServer { Host = gameServerQueryEndpoint.Address, QueryPort = gameServerQueryEndpoint.Port, Name = item.GameServerName, //Gamename = SteamGameNameFilter, Map = item.Map, Mission = item.Game, MaxPlayers = item.MaxPlayerCount, CurrentPlayerCount = item.CurrentPlayerCount, Passworded = item.Password, Port = item.GamePort, Version = item.Version, Keywords = item.Keywords, CurrentPlayers = new string[0], Ping = item.Ping, Players = item.Players?.Cast <ISteamGameServerPlayer>().ToArray(), Mods = GetValue("modNames", item.KeyValues), Modhashs = GetValue("modHashes", item.KeyValues), Signatures = GetValue("sigNames", item.KeyValues), VerifySignatures = item.Keywords.Contains(",vt,") } : null); }
private void AutoDetectServers() { // 33848 try { UdpClient client = new UdpClient(555); client.AllowNatTraversal(true); client.EnableBroadcast = true; client.Connect(IPAddress.Parse("255.255.255.255"), 33848); byte[] message = Encoding.ASCII.GetBytes("Hello"); client.Send(message, message.Length); var response = client.ReceiveAsync(); response.ContinueWith(x => { if (!x.IsFaulted) { var temp = x.Result; string data = Encoding.UTF8.GetString(temp.Buffer); var xml = XElement.Parse(data); var urlElement = xml.Elements("url").FirstOrDefault(); AddServers(new[] { (string) urlElement }); } }, TaskScheduler.FromCurrentSynchronizationContext()); } catch (Exception e) { s_logger.Error(e.Message, e); } }
protected override IEnumerable<Task> GetTasks() { _isClearing = false; _udp = new UdpClient(new IPEndPoint(IPAddress.Any, 0)); #if !DNX451 && !__MonoCS__ _udp.AllowNatTraversal(true); #endif LoginCommand msg = new LoginCommand(); msg.Payload.ServerId = _serverId; msg.Payload.SessionId = _sessionId; msg.Payload.Token = _token; msg.Payload.UserId = _userId; QueueMessage(msg); List<Task> tasks = new List<Task>(); if ((_client.Config.VoiceMode & DiscordVoiceMode.Outgoing) != 0) { #if USE_THREAD _sendThread = new Thread(new ThreadStart(() => SendVoiceAsync(_cancelToken))); _sendThread.IsBackground = true; _sendThread.Start(); #else tasks.Add(SendVoiceAsync()); #endif } #if USE_THREAD //This thread is required to establish a connection even if we're outgoing only if ((_client.Config.VoiceMode & DiscordVoiceMode.Incoming) != 0) { _receiveThread = new Thread(new ThreadStart(() => ReceiveVoiceAsync(_cancelToken))); _receiveThread.IsBackground = true; _receiveThread.Start(); } else //Dont make an OS thread if we only want to capture one packet... tasks.Add(Task.Run(() => ReceiveVoiceAsync(_cancelToken))); #else tasks.Add(ReceiveVoiceAsync()); #endif #if !DNXCORE50 tasks.Add(WatcherAsync()); #endif if (tasks.Count > 0) { // We need to combine tasks into one because receiveThread is // supposed to exit early if it's an outgoing-only client // and we dont want the main thread to think we errored var task = Task.WhenAll(tasks); tasks.Clear(); tasks.Add(task); } tasks.AddRange(base.GetTasks()); return new Task[] { Task.WhenAll(tasks.ToArray()) }; }
private static void StartSendCycle() { var data = Encoding.ASCII.GetBytes("Hello!!"); var sender = new UdpClient(AddressFamily.InterNetwork); sender.AllowNatTraversal(true); while (true) { sender.Send(data, data.Length, STUN.PublicEndPoint); Console.WriteLine("Sent " + data.Length + " bytes"); Thread.Sleep(500); } }
private void InitSocket() { udpClient = new UdpClient(7272); udpClient.Connect("172.27.7.244", 7272); udpClient.AllowNatTraversal(true); timer = new Timer(32.0f); timer.Elapsed += (_, __) => { SendData(); } ; timer.AutoReset = true; timer.Start(); }
public static void TryBegin(ref PacketReplyRequest reply, IPEndPoint client) { // Housekeeping if (MyThread != null) MyThread.Abort(); if (MyUDP != null) MyUDP.Close(); TotalUp = 0; TotalDown = 0; try { // Set our client's expected IP and Port from SOCKS5 MyClient = client; if (MyClient.Port == 0) { DebugWarn("Client's port is 0, going to have to guess source port (normal with V2/V3 viewers)."); hasClientPort = false; } // Get target's IP and ports from config (less lag) ExternalIP = (IPAddress)UDProxy.gConfiguration.Config["MyExternalIP"]; TargetIP = (IPAddress)UDProxy.gConfiguration.Config["TargetIP"]; TargetPorts = (List<ushort>)UDProxy.gConfiguration.Config["TargetPorts"]; MyUDP = new UdpClient( (ushort)UDProxy.gConfiguration.Config["ListenPort"] ); MyUDP.AllowNatTraversal(false); MyUDP.DontFragment = true; MyUDP.EnableBroadcast = true; MyThread = new Thread(new ThreadStart(StreamLoop)); } catch (SocketException e) { reply.REP = SOCKS5Protocol.REP.GENERAL_FAILURE; throw new UDProxyException("Socket failure: " + e.Message); } DebugInfo("UDP Endpoint has been set up."); MyThread.Start(); }
internal void InitializeUDPDetector() { if (NetworkManager.Instance.InternalConfiguration.NetworkPeering.UDPDetection.Enabled) { { // UDP szerver indítása List <int> listeningPorts = NetworkManager.Instance.InternalConfiguration.NetworkPeering.UDPDetection.BroadcastListeningPorts; if (listeningPorts.Count > 0) { if (NetworkManager.Instance.InternalConfiguration.NetworkPeering.UDPDetection.DetectionMode == UDPDetectionModeEnum.Multicast) { Action <AddressFamily, string> initMulticastUdpClient = ((a, ip) => { IPEndPoint broadcastEp = null; System.Net.Sockets.UdpClient udpClient = null; foreach (int port in listeningPorts) { try { if (LOGGER.IsInfoEnabled) { LOGGER.Info(string.Format("CONNECTION_MANAGER, trying to initialize broadcast detector on port {0} ({1}).", port, a.ToString())); } IPAddress multicastAddress = IPAddress.Parse(ip); // (239.0.0.222) broadcastEp = new IPEndPoint(a == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, port); udpClient = new System.Net.Sockets.UdpClient(a); udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); udpClient.ExclusiveAddressUse = false; udpClient.Client.Bind(broadcastEp); udpClient.EnableBroadcast = true; udpClient.MulticastLoopback = true; udpClient.AllowNatTraversal(true); udpClient.JoinMulticastGroup(multicastAddress); if (LOGGER.IsInfoEnabled) { LOGGER.Info(string.Format("CONNECTION_MANAGER, broadcast detector initialized on port {0} ({1}).", port, a.ToString())); } break; } catch (Exception ex) { if (LOGGER.IsErrorEnabled) { LOGGER.Error(string.Format("CONNECTION_MANAGER, failed to initialize broadcast detector on port {0} ({1}). Reason: {2}", port, a.ToString(), ex.Message), ex); } } } if (udpClient != null) { BroadcastServer server = new BroadcastServer(broadcastEp, udpClient); mBroadcastServers.Add(server); server.BeginReceive(); } }); if (!string.IsNullOrEmpty(NetworkManager.Instance.InternalConfiguration.NetworkPeering.UDPDetection.IPv4MulticastAddress)) { initMulticastUdpClient(AddressFamily.InterNetwork, NetworkManager.Instance.InternalConfiguration.NetworkPeering.UDPDetection.IPv4MulticastAddress); } if (NetworkManager.Instance.InternalConfiguration.Settings.EnableIPV6 && !string.IsNullOrEmpty(NetworkManager.Instance.InternalConfiguration.NetworkPeering.UDPDetection.IPv6MulticastAddress)) { initMulticastUdpClient(AddressFamily.InterNetworkV6, NetworkManager.Instance.InternalConfiguration.NetworkPeering.UDPDetection.IPv6MulticastAddress); } } if (NetworkManager.Instance.InternalConfiguration.NetworkPeering.UDPDetection.DetectionMode == UDPDetectionModeEnum.Broadcast) { Action <AddressFamily> initUdpClient = (a => { IPEndPoint broadcastEp = null; System.Net.Sockets.UdpClient udpClient = null; foreach (int port in listeningPorts) { try { if (LOGGER.IsInfoEnabled) { LOGGER.Info(string.Format("CONNECTION_MANAGER, trying to initialize broadcast detector on port {0} ({1}).", port, a.ToString())); } broadcastEp = new IPEndPoint(a == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, port); udpClient = new System.Net.Sockets.UdpClient(broadcastEp); udpClient.EnableBroadcast = true; udpClient.AllowNatTraversal(true); if (a == AddressFamily.InterNetwork) { udpClient.DontFragment = true; } if (LOGGER.IsInfoEnabled) { LOGGER.Info(string.Format("CONNECTION_MANAGER, broadcast detector initialized on port {0} ({1}).", port, a.ToString())); } break; } catch (Exception ex) { if (LOGGER.IsErrorEnabled) { LOGGER.Error(string.Format("CONNECTION_MANAGER, failed to initialize broadcast detector on port {0} ({1}). Reason: {2}", port, a.ToString(), ex.Message), ex); } } } if (udpClient != null) { BroadcastServer server = new BroadcastServer(broadcastEp, udpClient); mBroadcastServers.Add(server); server.BeginReceive(); } }); initUdpClient(AddressFamily.InterNetwork); if (NetworkManager.Instance.InternalConfiguration.Settings.EnableIPV6) { initUdpClient(AddressFamily.InterNetworkV6); } } } } { // UDP üzenetek szétszórása a hálózatba List <int> targetPorts = NetworkManager.Instance.InternalConfiguration.NetworkPeering.UDPDetection.BroadcastTargetPorts; if (targetPorts.Count > 0) { AddressEndPoint[] addressEps = null; AddressEndPoint[] ipEps = null; if (NetworkManager.Instance.InternalLocalhost.NATGatewayCollection.NATGateways.Count > 0) { addressEps = new AddressEndPoint[NetworkManager.Instance.InternalLocalhost.NATGatewayCollection.NATGateways.Count]; for (int i = 0; i < addressEps.Length; i++) { addressEps[i] = NetworkManager.Instance.InternalLocalhost.NATGatewayCollection.NATGateways[i].EndPoint; } } if (NetworkManager.Instance.InternalLocalhost.TCPServerCollection.TCPServers.Count > 0) { ipEps = new AddressEndPoint[NetworkManager.Instance.InternalLocalhost.TCPServerCollection.TCPServers.Count]; for (int i = 0; i < ipEps.Length; i++) { ipEps[i] = NetworkManager.Instance.InternalLocalhost.TCPServerCollection.TCPServers[i].EndPoint; } } if (addressEps != null || ipEps != null) { using (MemoryStream ms = new MemoryStream()) { { UdpBroadcastMessage message = new UdpBroadcastMessage(NetworkManager.Instance.InternalLocalhost.Id, NetworkManager.Instance.InternalLocalhost.NetworkContext.Name, addressEps, ipEps); MessageFormatter <UdpBroadcastMessage> formatter = new MessageFormatter <UdpBroadcastMessage>(); formatter.Write(ms, message); ms.Position = 0; } // multicast if (NetworkManager.Instance.InternalConfiguration.NetworkPeering.UDPDetection.DetectionMode == UDPDetectionModeEnum.Multicast) { // multicast foreach (int port in targetPorts) { Action <AddressFamily, string> sendMulticastUdpClient = ((a, ip) => { using (System.Net.Sockets.UdpClient udpClient = new System.Net.Sockets.UdpClient(a)) { udpClient.MulticastLoopback = true; udpClient.EnableBroadcast = true; udpClient.AllowNatTraversal(true); try { IPAddress multicastaddress = IPAddress.Parse(ip); udpClient.JoinMulticastGroup(multicastaddress); IPEndPoint remoteEp = new IPEndPoint(multicastaddress, port); if (LOGGER.IsInfoEnabled) { LOGGER.Info(string.Format("CONNECTION_MANAGER, sending multicast message on port {0}. ({1})", port, a.ToString())); } udpClient.Send(ms.ToArray(), Convert.ToInt32(ms.Length), remoteEp); udpClient.DropMulticastGroup(multicastaddress); } catch (Exception ex) { if (LOGGER.IsErrorEnabled) { LOGGER.Error(string.Format("CONNECTION_MANAGER, failed to send multicast message ({0}). Reason: {1}", a.ToString(), ex.Message)); } } } }); if (!string.IsNullOrEmpty(NetworkManager.Instance.InternalConfiguration.NetworkPeering.UDPDetection.IPv4MulticastAddress)) { sendMulticastUdpClient(AddressFamily.InterNetwork, NetworkManager.Instance.InternalConfiguration.NetworkPeering.UDPDetection.IPv4MulticastAddress); } if (NetworkManager.Instance.InternalConfiguration.Settings.EnableIPV6 && !string.IsNullOrEmpty(NetworkManager.Instance.InternalConfiguration.NetworkPeering.UDPDetection.IPv6MulticastAddress)) { sendMulticastUdpClient(AddressFamily.InterNetworkV6, NetworkManager.Instance.InternalConfiguration.NetworkPeering.UDPDetection.IPv6MulticastAddress); } } } else { // broadcast using (System.Net.Sockets.UdpClient udpClient = new System.Net.Sockets.UdpClient()) { udpClient.MulticastLoopback = false; udpClient.EnableBroadcast = true; udpClient.AllowNatTraversal(true); udpClient.DontFragment = true; foreach (int port in targetPorts) { try { if (LOGGER.IsInfoEnabled) { LOGGER.Info(string.Format("CONNECTION_MANAGER, sending broadcast message on port {0}.", port)); } udpClient.Send(ms.ToArray(), Convert.ToInt32(ms.Length), new IPEndPoint(IPAddress.Broadcast, port)); } catch (Exception ex) { if (LOGGER.IsErrorEnabled) { LOGGER.Error(string.Format("CONNECTION_MANAGER, failed to send broadcast message. Reason: {0}", ex.Message)); } } } } } } } else { if (LOGGER.IsInfoEnabled) { LOGGER.Info("CONNECTION_MANAGER, both of list NAT gateways and TCP servers are empties for broadcast detection."); } } } else { if (LOGGER.IsInfoEnabled) { LOGGER.Info("CONNECTION_MANAGER, no target udp port definied for broadcast detection."); } } } } else { if (LOGGER.IsInfoEnabled) { LOGGER.Info("CONNECTION_MANAGER, broadcast detection disabled."); } } }