private static async Task ReaderAsync(int port, string groupAddress) { using (var client = new UdpClient(port)) { if (groupAddress != null) { client.JoinMulticastGroup(IPAddress.Parse(groupAddress)); WriteLine($"joining the multicast group {IPAddress.Parse(groupAddress)}"); } bool completed = false; do { WriteLine("starting the receiver"); UdpReceiveResult result = await client.ReceiveAsync(); byte[] datagram = result.Buffer; string received = Encoding.UTF8.GetString(datagram); WriteLine($"received {received}"); if (received == "bye") { completed = true; } } while (!completed); WriteLine("receiver closing"); if (groupAddress != null) { client.DropMulticastGroup(IPAddress.Parse(groupAddress)); } } }
public ServerContext(int port, int maxclients, ref List<string> TextStack, string OwnIP) { BeginSendUdpServerCallback = new AsyncCallback(OnBeginSendUdpServerCallbackFinished); ServerMessage = System.Text.Encoding.ASCII.GetBytes("OK:" + OwnIP); UdpServer = new UdpClient(new IPEndPoint(IPAddress.Any, 8011)); //da bei xp fehler UdpServer.JoinMulticastGroup(BroadcastServer.Address); UdpServer.BeginSend(ServerMessage, ServerMessage.Length, BroadcastServer, BeginSendUdpServerCallback, null); MaxClients = maxclients; Ip = IPAddress.Any; this.Port = port; listener = new TcpListener(Ip, Port); Clients = new List<ClientContext>(MaxClients); listener.Start(); BeginAcceptSocketCallback = new AsyncCallback(OnClientConnected); this.TextStack = TextStack; }
/// <summary> /// Start the connection /// </summary> public override void Connect() { try { IEnumerable<IPAddress> ipv4Addresses = Dns .GetHostAddresses(Dns.GetHostName()) .Where(i => i.AddressFamily == AddressFamily.InterNetwork); foreach (IPAddress localIp in ipv4Addresses) { var client = new UdpClient(new IPEndPoint(localIp, _localEndpoint.Port)); _udpClients.Add(client); client.JoinMulticastGroup(ConnectionConfiguration.IpAddress, localIp); } } catch (SocketException ex) { throw new ConnectionErrorException(ConnectionConfiguration, ex); } // TODO: Maybe if we have a base Connect helper which takes in a KnxReceiver and KnxSender, // we can make the property setters more restricted KnxReceiver = new KnxReceiverRouting(this, _udpClients); KnxReceiver.Start(); KnxSender = new KnxSenderRouting(this, _udpClients, RemoteEndpoint); Connected(); }
public void Initialize() { tcpServer = new TcpListener(IPAddress.Any, 1901); tcpServer.BeginAcceptTcpClient() sender = new UdpClient(); sender.DontFragment = true; sender.JoinMulticastGroup(remoteEndPoint.Address); listener = new UdpClient(); listener.ExclusiveAddressUse = false; listener.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); listener.ExclusiveAddressUse = false; listener.Client.Bind(anyEndPoint); listener.DontFragment = true; listener.JoinMulticastGroup(remoteEndPoint.Address); listener.BeginReceive(ReceiveCallback, null); }
private void HandleBroadcasts() { var localIP = new IPEndPoint(IPAddress.Any, 50001); var udpClient = new UdpClient(); udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); udpClient.ExclusiveAddressUse = false; udpClient.Client.Bind(localIP); var multicastingIP = IPAddress.Parse("228.5.6.7"); udpClient.JoinMulticastGroup(multicastingIP); running = true; while (running) { var bytes = udpClient.Receive(ref localIP); var message = Encoding.UTF8.GetString(bytes); Dispatcher.Invoke(() => { lblResponse.Content = message; }); } udpClient.DropMulticastGroup(multicastingIP); udpClient.Close(); }
public SearchSniffer() { IPAddress[] LocalAddresses = Dns.GetHostEntry(Dns.GetHostName()).AddressList; ArrayList temp = new ArrayList(); foreach (IPAddress i in LocalAddresses) temp.Add(i); temp.Add(IPAddress.Loopback); LocalAddresses = (IPAddress[])temp.ToArray(typeof(IPAddress)); for (int id = 0; id < LocalAddresses.Length; ++id) { try { var localEndPoint = new IPEndPoint(LocalAddresses[id], 1900); UdpClient ssdpSession = new UdpClient(localEndPoint); ssdpSession.MulticastLoopback = false; ssdpSession.EnableBroadcast = true; if (localEndPoint.AddressFamily == AddressFamily.InterNetwork) { ssdpSession.JoinMulticastGroup(UpnpMulticastV4Addr, LocalAddresses[id]); } uint IOC_IN = 0x80000000; uint IOC_VENDOR = 0x18000000; uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12; ssdpSession.Client.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null); ssdpSession.BeginReceive(new AsyncCallback(OnReceiveSink), new object[] { ssdpSession, localEndPoint }); SSDPSessions[ssdpSession] = ssdpSession; } catch (Exception) { } } }
public void Start() { var version = ServiceType.Assembly.GetName().Version; var versionStr = version.Major + "." + version.Minor; var ssdpMsg = Encoding.UTF8.GetBytes(string.Format(SSDP_FORMAT, ServiceType.Name, versionStr, ServerName, Port)); UdpClient udp = new UdpClient(); udp.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); udp.Client.Bind(new IPEndPoint(IPAddress.Any, Port)); udp.JoinMulticastGroup(SSDP_ENDPOINT.Address); IsStopped = false; var thread = new Thread(() => { try { while (!IsStopped) { udp.Send(ssdpMsg, ssdpMsg.Length, SSDP_ENDPOINT); Thread.Sleep(Interval); } } catch { } finally { try { udp.Close(); } catch { } } }); thread.IsBackground = true; thread.Start(); }
public ProsthesisTelemetryReceiver(Logger logger) { mLogger = logger; mUDPReceiver = new UdpClient(ProsthesisCore.ProsthesisConstants.kTelemetryPort); mUDPReceiver.JoinMulticastGroup(IPAddress.Parse(ProsthesisCore.ProsthesisConstants.kMulticastGroupAddress)); mTelemetryReceiver = new System.Threading.Thread(RunThread); }
public Chat() { _multicastAddress = IPAddress.Parse("239.0.0.222"); _udpClient = new UdpClient(); _udpClient.JoinMulticastGroup(_multicastAddress); _remoteEp = new IPEndPoint(_multicastAddress, 2222); }
private void BackgroundListener() { IPEndPoint bindingEndpoint = new IPEndPoint(IPAddress.Any, _endPoint.Port); using (UdpClient client = new UdpClient()) { client.ExclusiveAddressUse = false; client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); client.Client.Bind(bindingEndpoint); client.JoinMulticastGroup(_endPoint.Address); bool keepRunning = true; while (keepRunning) { try { IPEndPoint remote = new IPEndPoint(IPAddress.Any, _endPoint.Port); byte[] buffer = client.Receive(ref remote); lock (this) { DataReceived(this, new MulticastDataReceivedEventArgs(remote, buffer)); } } catch (ThreadAbortException) { keepRunning = false; Thread.ResetAbort(); } } client.DropMulticastGroup(_endPoint.Address); } }
/* Methods */ /// <summary> /// UDP multicast provider constructor /// </summary> /// <param name="lcm">LCM object</param> /// <param name="up">URL parser object</param> public UDPMulticastProvider(LCM lcm, URLParser up) { this.lcm = lcm; string[] addrport = up.Get("network", DEFAULT_NETWORK).Split(':'); inetAddr = Dns.GetHostEntry(addrport[0]).AddressList[0]; inetPort = Int32.Parse(addrport[1]); inetEP = new IPEndPoint(inetAddr, inetPort); sock = new UdpClient(); sock.MulticastLoopback = true; sock.ExclusiveAddressUse = false; sock.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1); sock.Client.Bind(new IPEndPoint(IPAddress.Any, inetPort)); int ttl = up.Get("ttl", DEFAULT_TTL); if (ttl == 0) { Console.Error.WriteLine("LCM: TTL set to zero, traffic will not leave localhost."); } else if (ttl > 1) { Console.Error.WriteLine("LCM: TTL set to > 1... That's almost never correct!"); } else { Console.Error.WriteLine("LCM: TTL set to 1."); } sock.Ttl = (short) ttl; sock.JoinMulticastGroup(inetAddr); }
public bool Start() { try { //_logger.Debug(String.Format("Joining multicast group {0}:{1}", _multicastAddress, _port)); _udpClient = new UdpClient(); _udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); _udpClient.ExclusiveAddressUse = false; _endPoint = new IPEndPoint(IPAddress.Any, _port); _udpClient.Client.Bind(_endPoint); _udpClient.JoinMulticastGroup(IPAddress.Parse(_multicastAddress), IPAddress.Parse(_localAddress)); //_logger.Debug(String.Format("\tJoined multicast group {0}:{1} successfully", _multicastAddress, _port)); _isRunning = true; Receive(); } catch (Exception ex) { //_logger.Error(String.Format("\tFailed to join multicast group {0}:{1}", _multicastAddress, _port), ex); } return _isRunning; }
public void MulticastListen() { Console.WriteLine("Reciever Start"); UdpClient receiveUdp = new UdpClient(this.port); try { receiveUdp.JoinMulticastGroup(this.multicastIP, 10); } catch (SocketException e) { Console.WriteLine(e.Message.ToString()); } IPEndPoint remoteHost = null; while (true) { try { byte[] bytes = receiveUdp.Receive(ref remoteHost); string str = Encoding.UTF8.GetString(bytes, 0, bytes.Length); Console.WriteLine(str); } catch { Console.WriteLine("Reciever Close"); break; } } }
public Networking_UDPMultiOut(int port) { client = new UdpClient(); IPAddress multicastaddress = IPAddress.Parse("238.0.0.222"); client.JoinMulticastGroup(multicastaddress); remoteep = new IPEndPoint(multicastaddress, port); }
public static UpnpService Start( params IUpnpHandler[] handlers ) { UdpClient udp = new UdpClient(UPNP_PORT); udp.JoinMulticastGroup(UPNP_ADDR); UpnpService service = new UpnpService(udp, handlers); service.Accept(); return service; }
public CommunicationHandler() { _client = new UdpClient(3007); _client.EnableBroadcast = true; _client.JoinMulticastGroup(IPAddress.Parse("224.109.108.107")); _client.BeginReceive(HandleClientPacketReceived, _client); CommsCallback = null; }
public void Start() { IPEndPoint bindingEndpoint = new IPEndPoint(IPAddress.Any, _endPoint.Port); _udpClient = new UdpClient {ExclusiveAddressUse = false}; _udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); _udpClient.Client.Bind(bindingEndpoint); _udpClient.JoinMulticastGroup(_endPoint.Address, _timeToLive); }
public void Start() { udpClient = new UdpClient(portClient); udpClient.JoinMulticastGroup(multcastAddress); ipEndPoint = new IPEndPoint(multcastAddress, portServer); thread = new Thread(Send); thread.IsBackground = true; thread.Start(); }
//Todo: should probably be removed: /* public MulticastReceiver(IIpConfig IpConf, IUPnPConfig upnpconf) { /* _UUID = IpConf.GUID; _cacheexpire = upnpconf.cacheExpire; _localip = IpConf.IP; _tcpport = IpConf.TCPPort; SetupMulticastReceiver(); }*/ private static void SetupMulticastReceiver() { recClient = new UdpClient(); recIPep = new IPEndPoint(IPAddress.Any, multicastPort); recClient.Client.Bind(recIPep); recClient.JoinMulticastGroup(multicastIp); }
public Server(ServerForm serverForm) { this.serverForm = serverForm; client = new UdpClient(port); multicastAddress = IPAddress.Parse("239.0.0.222"); ipEndPoint = new IPEndPoint(multicastAddress, 2222); client.JoinMulticastGroup(multicastAddress); }
public UdpClientContext() { BeginReceiveUPDserver = new AsyncCallback(OnBeginReceiveUPDserverFinished); UdpServerSearcher = new UdpClient(BroadcastServer.Port, AddressFamily.InterNetwork); UdpServerSearcher.JoinMulticastGroup(BroadcastServer.Address, 1); //1 router hops for just local network UdpServerSearcher.BeginReceive(BeginReceiveUPDserver, null); }
public DiscoveryServer(ILog log, string host, int port) { this.log = log; subscriber = new UdpClient(port); IPAddress addr = IPAddress.Parse(host); subscriber.JoinMulticastGroup(addr); subscriber.BeginReceive(ReceiveCallback, subscriber); log.Log(LogLevel.Info, "Starting Discovery Server"); }
public void ConnectTo(string address, int port) { this.address = address; this.port = port; multicastIP = IPAddress.Parse(address); udpClient = new UdpClient(); udpClient.JoinMulticastGroup(multicastIP); endPoint = new IPEndPoint(multicastIP, port); }
public RealTimeDataAccess(string multicastAddress, int dataPort) { _multicastAddr = multicastAddress; _udpClient = new UdpClient(); _udpIpEndPoint = new IPEndPoint(IPAddress.Any, dataPort); _udpClient.Client.Bind(_udpIpEndPoint); _udpClient.JoinMulticastGroup(IPAddress.Parse(multicastAddress)); }
public DetectorPlotDataAccess(string multicastAddress, int dataPort) { _multicastAddress = multicastAddress; _ipEndPoint = new IPEndPoint(IPAddress.Any, dataPort); _udpClient = new UdpClient(); _udpClient.Client.Bind(_ipEndPoint); _udpClient.JoinMulticastGroup(IPAddress.Parse(multicastAddress)); }
static Helper() { Client = new UdpClient {ExclusiveAddressUse = false}; Client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); Client.ExclusiveAddressUse = false; Client.Client.Bind(new IPEndPoint(IPAddress.Any, 10020)); Client.JoinMulticastGroup(IPAddress.Parse("224.5.23.2")); Spinner = true; InitializeData(); }
public void SetConnect() { udpClient = new UdpClient(portServer); udpClient.JoinMulticastGroup(multcastAddress); ipEndPoint = new IPEndPoint(IPAddress.Any, 0); thread = new Thread(Receive); thread.IsBackground = true; thread.Start(); }
/// <summary> /// listen to the group /// </summary> /// <param name="owner">"this" in most case</param> /// <param name="dgGetMsg">handles message arriving</param> public void StartListen(System.Windows.Forms.Control owner, Action <string> dgGetMsg) { Owner = owner; DgGetMsg = dgGetMsg; IsListening = true; UdpClient = new System.Net.Sockets.UdpClient(UDPPort); UdpClient.JoinMulticastGroup(GroupIP); thUDPListener = new System.Threading.Thread(ListenHandler); thUDPListener.Start(); }
public DiscoveryManager() { ActivityServices = new List<ServiceInfo>(); DiscoveryType = DiscoveryType.WSDiscovery; #if ANDROID _messageId = Guid.NewGuid().ToString(); _udpClient = new UdpClient(WsDiscoveryPort); _udpClient.JoinMulticastGroup(IPAddress.Parse(WsDiscoveryIPAddress)); _udpClient.BeginReceive(HandleRequest, _udpClient); #endif }
protected override void DoInitilize() { remoteEndPoint = new IPEndPoint(IPAddress.Any, 0); udpClient = IpV6 ? new UdpClient(Port, AddressFamily.InterNetworkV6) : new UdpClient(Port); udpClient.Client.ReceiveBufferSize = BufferSize; if (!String.IsNullOrEmpty(Address)) { udpClient.JoinMulticastGroup(IPAddress.Parse(Address)); } Task.Factory.StartNew(Start); }
public FeiQIM(int Port) { msgdt.Columns.Add(new DataColumn("ip", System.Type.GetType("System.String"))); msgdt.Columns.Add(new DataColumn("msg", System.Type.GetType("System.String"))); msgdt.Columns.Add(new DataColumn("msgid", System.Type.GetType("System.String"))); if (!FunctionUtils.checkPort(Port.ToString())) { throw new Exception("端口被占用"); } else { UdpClient = new System.Net.Sockets.UdpClient(Port); UdpClient.JoinMulticastGroup(GroupIP); //BroadcastOnLine(); } }
protected override EventResult OnConnectBusy() { /* 処理中のオブジェクトを全て開放する */ if (udp_client_ != null) { udp_client_.Close(); udp_client_ = null; } var addr_family = (devp_.AddressFamily.Value == AddressFamilyType.IPv6) ? (AddressFamily.InterNetworkV6) : (AddressFamily.InterNetwork); /* === Local Setting === */ try { switch (devp_.LocalBindMode.Value) { case BindModeType.NotBind: local_ep_ = null; local_ep_text_ = ""; udp_client_ = new System.Net.Sockets.UdpClient(addr_family); break; case BindModeType.INADDR_ANY: local_ep_ = new IPEndPoint((addr_family == AddressFamily.InterNetworkV6) ? (IPAddress.IPv6Any) : (IPAddress.Any), (ushort)devp_.LocalPortNo.Value); local_ep_text_ = string.Format("INADDR_ANY:{0:G}", devp_.LocalPortNo.Value.ToString()); udp_client_ = new System.Net.Sockets.UdpClient(local_ep_); break; case BindModeType.SelectAddress: local_ep_ = new IPEndPoint(devp_.LocalIpAddress.Value, (int)devp_.LocalPortNo.Value); local_ep_text_ = string.Format("{0:G}:{1:G}", local_ep_.Address.ToString(), local_ep_.Port.ToString()); udp_client_ = new System.Net.Sockets.UdpClient(local_ep_); break; default: return(EventResult.Error); } /* 生成したエンドポイントが設定しているアドレスファミリーと異なる場合はエラー */ if ((local_ep_ != null) && (local_ep_.AddressFamily != addr_family)) { return(EventResult.Error); } } catch { return(EventResult.Error); } /* === Remote Setting === */ try { switch (devp_.RemoteAddressType.Value) { case AddressType.Unicast: remote_ep_ = new IPEndPoint(devp_.RemoteIpAddress.Value, (int)devp_.RemotePortNo.Value); break; case AddressType.Broadcast: udp_client_.EnableBroadcast = true; remote_ep_ = new IPEndPoint(IPAddress.Broadcast, (int)devp_.RemotePortNo.Value); break; case AddressType.Multicast: remote_ep_ = new IPEndPoint(devp_.RemoteIpAddress.Value, (int)devp_.RemotePortNo.Value); break; default: return(EventResult.Error); } remote_ep_text_ = string.Format("{0:G}:{1:G}", remote_ep_.Address.ToString(), remote_ep_.Port.ToString()); /* 生成したエンドポイントが設定しているアドレスファミリーと異なる場合はエラー */ if ((remote_ep_ != null) && (remote_ep_.AddressFamily != addr_family)) { return(EventResult.Error); } } catch { return(EventResult.Error); } /* Unicast - TTL */ if (devp_.Unicast_TTL.Value) { udp_client_.Ttl = (byte)devp_.Unicast_TTL_Value.Value; } /* Multicast - TTL */ if (devp_.Multicast_TTL.Value) { if (devp_.AddressFamily.Value == AddressFamilyType.IPv6) { udp_client_.Client.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.MulticastTimeToLive, (byte)devp_.Multicast_TTL_Value.Value); } else { udp_client_.Client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, (byte)devp_.Multicast_TTL_Value.Value); } } /* Multicast - Loopback */ if (devp_.Multicast_Loopback.Value) { udp_client_.MulticastLoopback = devp_.Multicast_Loopback.Value; } /* Multicast Interface */ var nic_index = -1; if (devp_.Multicast_Interface.Value) { var nics = NetworkInterface.GetAllNetworkInterfaces(); if ((nics != null) && (nics.Length > 0)) { for (var nic_index_temp = 0; nic_index_temp < nics.Length; nic_index_temp++) { if (nics[nic_index_temp].Id == devp_.Multicast_Interface_Value.Value) { nic_index = nic_index_temp; break; } } } } /* Multicast - Group */ if (devp_.Multicast_GroupAddress.Value) { IPAddress ipaddr; foreach (var ipaddr_text in devp_.Multicast_GroupAddressList.Value) { if ((IPAddress.TryParse(ipaddr_text, out ipaddr)) && (ipaddr.AddressFamily == addr_family)) { if (nic_index >= 0) { udp_client_.JoinMulticastGroup(nic_index, ipaddr); } else { udp_client_.JoinMulticastGroup(ipaddr); } } } } return(EventResult.Success); }
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."); } } }
public async Task BeginListeningAsync (CancellationToken token) { var client = new UdpClient (BroadcastEndpoint); client.JoinMulticastGroup (BroadcastEndpoint.Address); token.Register (() => client.Close ()); while (true) { token.ThrowIfCancellationRequested (); try { var result = await client.ReceiveAsync (); var data = Encoding.UTF8.GetString (result.Buffer); if (data.StartsWith (Header, StringComparison.Ordinal)) { if (ServerFound != null) { var details = new ServerDetails { Hostname = result.RemoteEndPoint.Address.ToString (), Port = int.Parse (data.Substring (Header.Length)) }; LoggingService.LogInfo ("Found TunezServer at {0}", details.FullAddress); ServerFound (this, details); } } } catch (ObjectDisposedException) { token.ThrowIfCancellationRequested (); throw; } catch (SocketException) { token.ThrowIfCancellationRequested (); // Ignore this } catch (Exception ex) { token.ThrowIfCancellationRequested (); LoggingService.LogInfo ("Ignoring bad UDP {0}", ex); } } }