Ejemplo n.º 1
0
        private void StartAdvertiser()
        {
            _logger.LogDebug($"Starting advertiser on local network");
            var neonService = new ServiceProfile("neon", "_neonhome._tcp", 5000);

            neonService.AddProperty("http", "5000");
            neonService.AddProperty("https", "5001");
            neonService.AddProperty("appVersion", AssemblyUtils.GetVersion());
            neonService.AddProperty("uuid", _uuid);

            _serviceAdvertiser.Advertise(neonService);
        }
Ejemplo n.º 2
0
        private void AdvertiseService(IPAddress ip)
        {
            var service = new ServiceProfile($"Vent-Test", "_venttest._tcp", 54321, new List <IPAddress>()
            {
                ip
            });

            service.AddProperty("vn", "1.0");
            service.AddProperty("fn", new EasClientDeviceInformation().FriendlyName);
            Debug.WriteLine("Made service profile");
            SD = new ServiceDiscovery();
            Debug.WriteLine("Made ServiceDiscovery");
            SD.Advertise(service);
            Debug.WriteLine("Advertising");
        }
Ejemplo n.º 3
0
        /// <inheritdoc />
        public Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogTrace("Going to check if is necessary register.");
            if (_option.RegistermDNS)
            {
                _logger.LogTrace("Going to register Service in mDNS.");
                Task.Run(() =>
                {
                    _logger.LogTrace("Going to wait {delay} before register.", _option.MDnsDelay.ToString("G"));
                    Task.Delay(_option.MDnsDelay, cancellationToken).GetAwaiter().GetResult();

                    var tls    = _server.Features.Get <ITlsHandshakeFeature>();
                    var hasTls = tls != null && tls.Protocol != SslProtocols.None;

                    var addresses = _server.Features.Get <IServerAddressesFeature>()?.Addresses ?? new List <string>();

                    foreach (var address in addresses)
                    {
                        var index = address.LastIndexOf(':');
                        if (index < 0 || index + 1 == address.Length)
                        {
                            _logger.LogWarning("Going to ignore {address} address, because it has a invalid format", address);
                            continue;
                        }

                        var port = ushort.Parse(address.AsSpan().Slice(index + 1));

                        var profile = new ServiceProfile("_webthing._tcp.local", _name, port);
                        profile.AddProperty("path", "/");

                        if (hasTls)
                        {
                            profile.AddProperty("tls", "1");
                        }

                        _profiles.Add(profile);

                        _logger.LogInformation("Advertising and Announcing the {serviceName} in {port} port", _name, port);
                        _discovery.Advertise(profile);
                        _discovery.Announce(profile);
                    }
                }, cancellationToken);
            }

            return(Task.CompletedTask);
        }
Ejemplo n.º 4
0
        static void Main(string[] args)
        {
            Console.WriteLine("Multicast DNS spike");

            // set logger factory
            var properties = new Common.Logging.Configuration.NameValueCollection
            {
                ["level"]        = "TRACE",
                ["showLogName"]  = "true",
                ["showDateTime"] = "true"
            };

            LogManager.Adapter = new ConsoleOutLoggerFactoryAdapter(properties);

            var mdns = new MulticastService
            {
                NetworkInterfaceDiscoveryInterval = TimeSpan.FromSeconds(1),
            };

            foreach (var a in MulticastService.GetIPAddresses())
            {
                Console.WriteLine($"IP address {a}");
            }

            mdns.QueryReceived += (s, e) =>
            {
                var names = e.Message.Questions
                            .Select(q => q.Name + " " + q.Type);
                Console.WriteLine($"got a query for {String.Join(", ", names)}");
            };
            mdns.AnswerReceived += (s, e) =>
            {
                var names = e.Message.Answers
                            .Select(q => q.Name + " " + q.Type)
                            .Distinct();
                Console.WriteLine($"got answer for {String.Join(", ", names)}");
            };
            mdns.NetworkInterfaceDiscovered += (s, e) =>
            {
                foreach (var nic in e.NetworkInterfaces)
                {
                    Console.WriteLine($"discovered NIC '{nic.Name}'");
                }
            };

            var sd = new ServiceDiscovery(mdns);

            sd.Advertise(new ServiceProfile("x1", "_xservice._tcp", 5011));
            sd.Advertise(new ServiceProfile("x2", "_xservice._tcp", 666));
            var z1 = new ServiceProfile("z1", "_zservice.udp", 5012);

            z1.AddProperty("foo", "bar");
            sd.Advertise(z1);

            mdns.Start();
            Console.ReadKey();
        }
Ejemplo n.º 5
0
        private void AdvertiseService(IApplicationBuilder app)
        {
            var mdns = new MulticastService();

            mdns.Start();

            var serverAddressesFeature = app.ServerFeatures.Get <IServerAddressesFeature>();

            foreach (var address in serverAddressesFeature.Addresses)
            {
                var    uri = new Uri(address);
                var    serviceDiscovery = new ServiceDiscovery(mdns);
                string serviceType      = "_" + uri.Scheme + "._tcp";
                var    service          = new ServiceProfile("TelekinesisServer", serviceType, (ushort)uri.Port);
                service.AddProperty("OSVersion", Environment.OSVersion.ToString());
                service.AddProperty("Platform", Environment.OSVersion.Platform.ToString());
                service.AddProperty("MachineName", Environment.MachineName);
                serviceDiscovery.Advertise(service);
            }
        }
Ejemplo n.º 6
0
        public sealed override void RefreshSystem()
        {
            var sd = DataUtil.GetSystemData();

            _devMode  = sd.DeviceMode;
            _hostName = _sd.DeviceName;
            _discovery?.Dispose();
            var address = new List <IPAddress> {
                IPAddress.Parse(IpUtil.GetLocalIpAddress())
            };
            var service = new ServiceProfile(_hostName, "_glimmr._tcp", 21324, address);

            service.AddProperty("mac", sd.DeviceId);
            _discovery = new ServiceDiscovery();
            _discovery.Advertise(service);
        }
Ejemplo n.º 7
0
        static void Main(string[] args)
        {
            // Advertise via mDNS
            Console.WriteLine("Getting IP addresses");
            string sHostName = Dns.GetHostName();

            IPAddress[] IPs = Dns.GetHostAddresses(sHostName);
            Console.WriteLine($"Got: {String.Join(", ", (IEnumerable<IPAddress>)IPs)}");
            var service = new ServiceProfile($"Cards-Uno-{Guid.NewGuid()}", "_customservice._tcp", 54321, IPs);

            service.AddProperty("service_version", "1.0");
            Console.WriteLine("Made service profile");

            var SD = new ServiceDiscovery();

            Console.WriteLine("Made ServiceDiscovery");
            SD.Advertise(service);
            Console.WriteLine("Advertising");

            Console.ReadLine();
        }
Ejemplo n.º 8
0
        public Client(string clientIp)
        {
            _clientIp = clientIp;
            mdns      = new MulticastService();
            var domainName = "_itxpt_multicast._tcp";

            servicename = "gnsslocation";
            mdns.NetworkInterfaceDiscovered += (s, e) => mdns.SendQuery(domainName);

            mdns.AnswerReceived += (s, e) =>
            {
                Console.WriteLine($"GET response from server {e.RemoteEndPoint.Address}:{e.RemoteEndPoint.Port}. Message: {e.Message.Answers.FirstOrDefault()}");
                List <ResourceRecord> answers = e.Message.Answers;
                this.ParseRecords(answers);

                Func <IPEndPoint, bool> predicate = null;
                foreach (ResourceRecord record in answers)
                {
                    if ((record is TXTRecord) && this.ForMe)
                    {
                        foreach (string str in ((TXTRecord)record).Strings)
                        {
                            char[]   separator = new char[] { '=' };
                            string[] strArray  = str.Split(separator);
                            if (strArray.Length == 2)
                            {
                                if (strArray[0] == "address")
                                {
                                    string text1 = strArray[1];
                                }
                                if (strArray[0] == "multicast")
                                {
                                    this.multicastIp = strArray[1];
                                }
                            }
                        }
                    }
                }
                answers = e.Message.AdditionalRecords;
                foreach (ResourceRecord record in answers)
                {
                    if ((record is TXTRecord) && this.ForMe)
                    {
                        foreach (string str in ((TXTRecord)record).Strings)
                        {
                            char[]   separator = new char[] { '=' };
                            string[] strArray  = str.Split(separator);
                            if (strArray.Length == 2)
                            {
                                if (strArray[0] == "address")
                                {
                                    string text1 = strArray[1];
                                }
                                if (strArray[0] == "multicast")
                                {
                                    this.multicastIp = strArray[1];
                                }
                            }
                        }
                    }
                }

                if ((this.srvRec != null) && (this.ForMe && ((this.srvRec.Port != 0) && (!string.IsNullOrEmpty(this.multicastIp) && (this.udpClient == null)))))
                {
                    if (predicate == null)
                    {
                        predicate = p => p.Port == this.srvRec.Port;
                    }
                    if (Enumerable.Any <IPEndPoint>(IPGlobalProperties.GetIPGlobalProperties().GetActiveUdpListeners(), predicate))
                    {
                        Console.WriteLine(string.Format("{0}:{1} already in use. Try again later", this.multicastIp, this.srvRec.Port));
                    }
                    else
                    {
                        Console.WriteLine("FeedbackType.Client: " + string.Format("JoinMulticastGroup {0}:{1}", this.multicastIp, this.srvRec.Port));
                        udpClient = new UdpClient(this.srvRec.Port);
                        udpClient.JoinMulticastGroup(IPAddress.Parse(this.multicastIp), 50);
                        receiveThread = new Thread(new ThreadStart(this.Receive));
                        receiveThread.Start();
                    }
                }
            };

            advertiseThread = new Thread(new ThreadStart(() =>
            {
                sd     = new ServiceDiscovery(mdns);
                var sp = new ServiceProfile(servicename, domainName, 14005);
                sp.AddProperty("host", "192.168.88.239");
                sp.AddProperty("port", "14005");
                sp.Resources.Add(new ARecord {
                    Name = "_itxpt_multicast._tcp", Address = IPAddress.Parse("192.168.88.239"), Class = DnsClass.IN
                });
                sp.Resources.Add(new SRVRecord {
                    Name = "_itxpt_multicast._tcp", Port = 14005, Priority = 0, Weight = 0, Class = DnsClass.IN
                });
                sd.Advertise(sp);
            }));

            advertiseThread.Start();

            mdns.Start();
        }
        public MDNSServicePublisher()
        {
            Task.Run(() => {
                var mdns     = new MulticastService();
                mdns.UseIpv6 = false;
                foreach (var a in MulticastService.GetIPAddresses())
                {
                    Debug.WriteLine($"IP address {a}");
                }

                mdns.QueryReceived += (s, e) =>
                {
                    var names = e.Message.Questions
                                .Select(q => q.Name + " " + q.Type);
                    Debug.WriteLine($"got a query for {String.Join(", ", names)}");
                };
                mdns.AnswerReceived += (s, e) =>
                {
                    var names = e.Message.Answers
                                .Select(q => q.Name + " " + q.Type)
                                .Distinct();
                    Debug.WriteLine($"got answer for {String.Join(", ", names)}");
                };
                mdns.NetworkInterfaceDiscovered += (s, e) =>
                {
                    foreach (var nic in e.NetworkInterfaces)
                    {
                        Debug.WriteLine($"discovered NIC '{nic.Name}'");
                    }
                };

                var sd = new ServiceDiscovery(mdns);

                var address = new List <IPAddress>();
                address.Add(IPAddress.Parse("10.113.81.192"));

                var s1 = new ServiceProfile("JOSHMobile", "_airplay._tcp.", 7000, address);
                s1.AddProperty("deviceid", "00:05:A6:16:45:8F");
                s1.AddProperty("features", "0xA7FFFF7,0xE");
                s1.AddProperty("flags", "0x4");
                s1.AddProperty("model", "AppleTV5,3");
                s1.AddProperty("pi", "6b448552-85ce-4143-a896-e28d12e8a0ab");
                s1.AddProperty("pk", "F381DC574DEAF9C70B75297755BC7C7C35BB1D0DB500258F3AB46B5FE7C7355B");
                s1.AddProperty("srcvers", "220.68");
                s1.AddProperty("vv", "2");



                var s2 = new ServiceProfile("0005A616458F@JOSHMobile", "_raop._tcp.", 7000, address);
                s2.AddProperty("am", "AppleTV5,3");
                s2.AddProperty("ch", "2");
                s2.AddProperty("cn", "0,1,2,3");
                s2.AddProperty("da", "true");
                s2.AddProperty("ek", "1");
                s2.AddProperty("et", "0,3,5");
                s2.AddProperty("md", "0,1,2");
                s2.AddProperty("pw", "false");
                s2.AddProperty("sm", "false");
                s2.AddProperty("sr", "44100");
                s2.AddProperty("ss", "16");
                s2.AddProperty("sv", "false");
                s2.AddProperty("tp", "UDP");
                s2.AddProperty("txvers", "1");
                s2.AddProperty("vn", "65537");
                s2.AddProperty("vs", "220.68");
                s2.AddProperty("sf", "0x4");
                s2.AddProperty("ft", "0xA7FFFF7,0xE");
                s2.AddProperty("pk", "F381DC574DEAF9C70B75297755BC7C7C35BB1D0DB500258F3AB46B5FE7C7355B");
                s2.AddProperty("vv", "2");

                sd.Advertise(s2);
                sd.Advertise(s1);
                mdns.Start();
            }
                     );
        }
Ejemplo n.º 10
0
        public Task StartMdnsAsync()
        {
            if (string.IsNullOrWhiteSpace(_deviceId))
            {
                throw new ArgumentNullException(_deviceId);
            }

            var rDeviceId = new Regex("^(([0-9a-fA-F][0-9a-fA-F]):){5}([0-9a-fA-F][0-9a-fA-F])$");
            var mDeviceId = rDeviceId.Match(_deviceId);

            if (!mDeviceId.Success)
            {
                throw new ArgumentException("Device id must be a mac address", _deviceId);
            }

            var deviceIdInstance = string.Join(string.Empty, mDeviceId.Groups[2].Captures) + mDeviceId.Groups[3].Value;

            _mdns = new MulticastService();
            var sd = new ServiceDiscovery(_mdns);

            foreach (var ip in MulticastService.GetIPAddresses())
            {
                Console.WriteLine($"IP address {ip}");
            }

            _mdns.NetworkInterfaceDiscovered += (s, e) =>
            {
                foreach (var nic in e.NetworkInterfaces)
                {
                    Console.WriteLine($"NIC '{nic.Name}'");
                }
            };

            // Internally 'ServiceProfile' create the SRV record
            var airTunes = new ServiceProfile($"{deviceIdInstance}@{_instance}", AirTunesType, _airTunesPort);

            airTunes.AddProperty("ch", "2");
            airTunes.AddProperty("cn", "2,3");
            airTunes.AddProperty("et", "0,3,5");
            airTunes.AddProperty("md", "0,1,2");
            airTunes.AddProperty("sr", "44100");
            airTunes.AddProperty("ss", "16");
            airTunes.AddProperty("da", "true");
            airTunes.AddProperty("sv", "false");
            airTunes.AddProperty("ft", "0x5A7FFFF7,0x1E"); // 0x4A7FFFF7, 0xE
            airTunes.AddProperty("am", "AppleTV5,3");
            airTunes.AddProperty("pk", "29fbb183a58b466e05b9ab667b3c429d18a6b785637333d3f0f3a34baa89f45e");
            airTunes.AddProperty("sf", "0x4");
            airTunes.AddProperty("tp", "UDP");
            airTunes.AddProperty("vn", "65537");
            airTunes.AddProperty("vs", "220.68");
            airTunes.AddProperty("vv", "2");

            /*
             * ch	2	audio channels: stereo
             * cn	0,1,2,3	audio codecs
             * et	0,3,5	supported encryption types
             * md	0,1,2	supported metadata types
             * pw	false	does the speaker require a password?
             * sr	44100	audio sample rate: 44100 Hz
             * ss	16	audio sample size: 16-bit
             */

            // Internally 'ServiceProfile' create the SRV record
            var airPlay = new ServiceProfile(_instance, AirPlayType, _airPlayPort);

            airPlay.AddProperty("deviceid", _deviceId);
            airPlay.AddProperty("features", "0x5A7FFFF7,0x1E"); // 0x4A7FFFF7
            airPlay.AddProperty("flags", "0x4");
            airPlay.AddProperty("model", "AppleTV5,3");
            airPlay.AddProperty("pk", "29fbb183a58b466e05b9ab667b3c429d18a6b785637333d3f0f3a34baa89f45e");
            airPlay.AddProperty("pi", "aa072a95-0318-4ec3-b042-4992495877d3");
            airPlay.AddProperty("srcvers", "220.68");
            airPlay.AddProperty("vv", "2");

            sd.Advertise(airTunes);
            sd.Advertise(airPlay);

            _mdns.Start();

            return(Task.CompletedTask);
        }
Ejemplo n.º 11
0
 /// <summary>
 /// Add information (key-value-pair) to TXT-record of advertise message
 /// </summary>
 /// <param name="key"></param>
 /// <param name="value"></param>
 public void AddProperty(string key, string value)
 {
     serviceProfile.AddProperty(key, value);
 }