private void SendHostInfoWork() { try { ulong sequence = 0; DateTime nextSendDateTime = DateTime.Now; MndpMessageEx msg = new MndpMessageEx { BoardName = this._hostInfo.BoardName, Identity = this._hostInfo.Identity, Platform = this._hostInfo.Platform, SoftwareId = this._hostInfo.SoftwareId, Version = this._hostInfo.Version, Ttl = 0, Type = 0, Unpack = 0, }; while (this._sendHostInfoIsRunning) { Thread.Sleep(100); if ((nextSendDateTime < DateTime.Now) || this._sendHostInfoNow) { nextSendDateTime = DateTime.Now.AddSeconds(HOST_INFO_SEND_INTERVAL); this._sendHostInfoNow = false; var interfaces = this._hostInfo.InterfaceInfos; msg.Sequence = (ushort)(sequence++); msg.Uptime = this._hostInfo.UpTime; foreach (var i in interfaces) { msg.BroadcastAddress = i.BroadcastAddress; msg.InterfaceName = i.InterfaceName; msg.MacAddress = i.MacAddress; msg.UnicastAddress = i.UnicastAddress; msg.UnicastIPv6Address = i.UnicastIPv6Address; this.Send((MndpMessageEx)msg.Clone()); } } } } catch (Exception ex) { Log.Exception(nameof(MndpSender), nameof(this.SendHostInfoWork), ex); } }
private void _receive(IAsyncResult ar) { try { if ((ar != null) && (this._udpClient != null)) { IPEndPoint ip = new IPEndPoint(IP_ADDRESS, UDP_PORT); byte[] bytes = this._udpClient.EndReceive(ar, ref ip); var msg = new MndpMessageEx { UnicastAddress = ip.Address.ToString(), ReceiveDateTime = DateTime.Now }; if (msg.Read(bytes)) { this._dictMessages[msg.MacAddress] = msg; } } } catch (Exception ex) { Log.Exception(nameof(MndpListener), nameof(this._receive), ex); } try { if (this._udpClient != null) { this._udpClient.BeginReceive(this._receive, new object()); } } catch (Exception ex) { Log.Exception(nameof(MndpListener), nameof(this._receive), ex); } }
/// <summary> /// Send message. /// </summary> /// <param name="msg">Mndp message.</param> /// <returns>Is success?.</returns> public bool Send(MndpMessageEx msg) { try { EndPoint ep; Socket s; var broadcastAddress = IP_ADDRESS; if (msg.BroadcastAddress != null) { broadcastAddress = IPAddress.Parse(msg.BroadcastAddress); } using (s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, 1); s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1); s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontRoute, true); ep = new IPEndPoint(broadcastAddress, UDP_PORT); var data = msg.Write(); s.SendTo(data, ep); return(true); } } catch (Exception ex) { Log.Exception(nameof(MndpSender), nameof(this.Send), ex); } return(false); }