Beispiel #1
0
        private FoundDevice BuildResponse(AddressRecord aRecord, TXTRecord tXTRecord)
        {
            var IpAddress  = aRecord.Address.ToString();
            var DeviceId   = aRecord.Name.Labels[0].Replace("-", "");
            var DeviceName = Utils.Common;

            if (tXTRecord != null)
            {
                var prop = tXTRecord.Strings.Find(x => x.Contains("fn"));
                if (prop != null)
                {
                    var info = prop.Split("=");
                    DeviceName = info[1] ?? Utils.Common;
                }
                else
                {
                    DeviceName = aRecord.Name.Labels[0];
                }
            }
            else
            {
                DeviceName = aRecord.Name.Labels[0];
            }

            return(new FoundDevice
            {
                IpAddress = IpAddress,
                DeviceId = DeviceId,
                DeviceName = DeviceName,
                FoundAt = aRecord.CreationTime,
                FoundUsing = "MDNS"
            });
        }
        public void ServiceResolved
        (
            DNSSDService sref,
            DNSSDFlags flags,
            uint ifIndex,
            String fullName,
            String hostName,
            ushort port,
            TXTRecord txtRecord
        )
        {
            ResolveData data = new ResolveData();

            data.InterfaceIndex = ifIndex;
            data.FullName       = fullName;
            data.HostName       = hostName;
            data.Port           = port;
            data.TxtRecord      = txtRecord;

            //
            // Don't forget to stop the resolver. This eases the burden on the network
            //
            resolver.Stop();
            resolver = null;

            Populate((BrowseData)browseList.SelectedItem, data);
        }
        /// <summary>
        /// Parses a <see cref="TXTRecord"/> into a <see cref="Freebox.Data.ApiInfo"/> object
        /// </summary>
        /// <param name="record">The record to try and parse</param>
        /// <returns></returns>
        internal static ApiInfo ApiInfo(this TXTRecord record)
        {
            var result = new ApiInfo();


            if (TryParse(record, out Dictionary <string, string> strings))
            {
                var setters = typeof(ApiInfo).GetProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public)
                              .SelectMany(p =>
                                          p.GetCustomAttributes(typeof(JsonPropertyAttribute))
                                          .ToDictionary(
                                              k => ((JsonPropertyAttribute)k).PropertyName,
                                              v => p.SetMethod))
                              .ToDictionary(k => k.Key, v => v.Value);

                foreach (var kvp in strings)
                {
                    if (setters.ContainsKey(kvp.Key))
                    {
                        setters[kvp.Key].Invoke(result, new[] { kvp.Value });
                    }
                }

                return(result);
            }

            return(null);
        }
Beispiel #4
0
        public void ServiceResolved(DNSSDService service,
                                    DNSSDFlags flags,
                                    uint ifIndex,
                                    String fullName,
                                    String hostName,
                                    ushort port,
                                    TXTRecord txtRecord)
        {
            String user     = null;
            String password = null;
            String path     = null;

            if (txtRecord.ContainsKey("u"))
            {
                user = txtRecord.GetValueForKey("u").ToString();
            }
            if (txtRecord.ContainsKey("p"))
            {
                password = txtRecord.GetValueForKey("p").ToString();
            }
            if (txtRecord.ContainsKey("path"))
            {
                path = txtRecord.GetValueForKey("path").ToString();
            }
            base.add(fullName, hostName, port, user, password, path);
            service.Stop();
        }
        ServiceResolved
        (
            DNSSDService sref,
            DNSSDFlags flags,
            uint ifIndex,
            String fullName,
            String hostName,
            ushort port,
            TXTRecord txtRecord
        )
        {
            m_resolver.Stop();
            m_resolver = null;

            PeerData peer = (PeerData)comboBox1.SelectedItem;

            peer.Port = port;

            try
            {
                m_resolver = m_service.QueryRecord(0, ifIndex, hostName, DNSSDRRType.kDNSSDType_A, DNSSDRRClass.kDNSSDClass_IN, m_eventManager);
            }
            catch
            {
                MessageBox.Show("QueryRecord Failed", "Error");
                Application.Exit();
            }
        }
 /// <summary>
 /// Method to convert a <see cref="TXTRecord"/> into a <see cref="Dictionary{TKey, TValue}">Dictionary{string, string}</see>"/>
 /// The record strings need to all contain key value pairs separated by the character "="
 /// </summary>
 /// <param name="record">The record to parse</param>
 /// <returns>A dictionary containg a key value pair for each string in the record</returns>
 internal static Dictionary <string, string> StringsDictionary(this TXTRecord record)
 {
     return(record.Strings.Select(kv =>
     {
         var splitted = kv.Split('=');
         return new KeyValuePair <string, string>(splitted[0], splitted[1]);
     }).ToDictionary(k => k.Key, v => v.Value));
 }
        private void AnswerReceived(Message message)
        {
            List <PTRRecord> answers = message.Answers.Where(a => a.Name == AtemDeviceInfo.ServiceName).OfType <PTRRecord>().ToList();
            PTRRecord        answer  = answers.FirstOrDefault();

            if (answer == null)
            {
                return;
            }

            if (_debug && answers.Count != 1)
            {
                Console.WriteLine("Too many answers!");
            }

            List <ResourceRecord> records = message.AdditionalRecords;
            SRVRecord             srvRec  = records.OfType <SRVRecord>().FirstOrDefault(r => r.Type == DnsType.SRV && r.Name == answer.DomainName);

            if (srvRec == null)
            {
                if (_debug)
                {
                    Console.WriteLine("Missing SRV record for " + answer.DomainName);
                }
                return;
            }

            AddressRecord aRec = records.OfType <AddressRecord>().FirstOrDefault(r => r.Type == DnsType.A && r.Name == srvRec.Target);

            if (aRec == null)
            {
                if (_debug)
                {
                    Console.WriteLine("Missing A record for " + answer.DomainName);
                }
                return;
            }

            TXTRecord     txtRec  = records.OfType <TXTRecord>().FirstOrDefault(r => r.Type == DnsType.TXT && r.Name == answer.DomainName);
            List <string> strings = txtRec == null ? new List <string>() : txtRec.Strings;

            string name = string.Join(".", answer.DomainName.Labels);

            if (name.EndsWith(AtemDeviceInfo.ServiceName))
            {
                name = name.Substring(0, name.Length - AtemDeviceInfo.ServiceName.Length - 1);
            }

            var dev = new AtemDeviceInfo(name, srvRec.Target.ToString(), DateTime.Now, aRec.Address.ToString(), srvRec.Port, strings);

            lock (_knownDevices) {
                _knownDevices[dev.DeviceId] = dev;
            }

            OnDeviceSeen?.Invoke(this, dev);
        }
Beispiel #8
0
        /// <summary>
        ///   Add a property of the service to the <see cref="TXTRecord"/>.
        /// </summary>
        /// <param name="key">
        ///   The name of the property.
        /// </param>
        /// <param name="value">
        ///   The value of the property.
        /// </param>
        public void AddProperty(string key, string value)
        {
            var txt = Resources.OfType <TXTRecord>().FirstOrDefault();

            if (txt == null)
            {
                txt = new TXTRecord {
                    Name = FullyQualifiedName
                };
                Resources.Add(txt);
            }
            txt.Strings.Add(key + "=" + value);
        }
        private NetService ProcessTXTRecord(TXTRecord record)
        {
            string serviceInstanceName = record.Name;

            if (_discoveredServices.ContainsKey(serviceInstanceName))
            {
                NetService service = _discoveredServices[serviceInstanceName];
                service.TXTRecordData = record.Data;
                return(service);
            }

            return(null);
        }
        internal static bool TryParse(TXTRecord record, out Dictionary <string, string> result)
        {
            result = null;

            try
            {
                result = StringsDictionary(record);
                return(true);
            }
            catch
            {
                return(false);
            }
        }
        private TXTRecord DeserializeTxtRr(string name, int ttl, byte[] bytes, int start, int length, out int bytesRead)
        {
            var txt = new TXTRecord()
            {
                Name       = name,
                TimeToLive = ttl,
                Length     = length
            };

            var wordBytes = new byte[length];

            Array.Copy(bytes, start, wordBytes, 0, length);
            txt.TextData = Encoding.ASCII.GetString(wordBytes);

            bytesRead = length;

            return(txt);
        }
Beispiel #12
0
        private String ParseDNSAnswer(Dictionary <DnsType, ResourceRecord> answer)
        {
            Console.WriteLine("Parse the DNS Answer");
            if ((answer.ContainsKey(DnsType.A) || answer.ContainsKey(DnsType.AAAA)) && answer.ContainsKey(DnsType.SRV) && answer.ContainsKey(DnsType.TXT))
            {
                TXTRecord txt_item = answer[DnsType.TXT] as TXTRecord;
                Dictionary <String, String> text_dic = new Dictionary <String, String>();
                foreach (String item in txt_item.Strings)
                {
                    String[] item_split = item.Split("=");
                    text_dic.Add(item_split[0], item_split[1]);
                }
                if (text_dic.ContainsKey("td"))
                {
                    Console.WriteLine($"{txt_item.Type}: " + $"'{txt_item.Name}' {String.Join(" ", txt_item.Strings.ToArray())}");

                    Boolean using_a = false;
                    if (answer.ContainsKey(DnsType.A))
                    {
                        using_a = true;
                    }

                    AddressRecord aa_item;
                    if (using_a)
                    {
                        aa_item = answer[DnsType.A] as AddressRecord;
                        Console.WriteLine($"{aa_item.Type}: " + $"host '{aa_item.Name}' at '{aa_item.Address}'");
                    }
                    else
                    {
                        aa_item = answer[DnsType.AAAA] as AddressRecord;
                        Console.WriteLine($"{aa_item.Type}: " + $"host '{aa_item.Name}' at '{aa_item.Address}'");
                    }

                    SRVRecord srv_item = answer[DnsType.SRV] as SRVRecord;
                    Console.WriteLine($"{srv_item.Type}: " + $"service '{srv_item.Name}' on '{srv_item.Target}' at '{srv_item.Port}'");

                    String ret = $"http://{aa_item.Address}:{srv_item.Port}{text_dic["td"]}";
                    Console.WriteLine($"Combine Answer to {ret}\n");
                    return(ret);
                }
            }
            return("");
        }
Beispiel #13
0
        private void ParseMessage(Message message)
        {
            foreach (var record in message.Answers)
            {
                if (message?.AdditionalRecords.Count > 0)
                {
                    AddressRecord ARecord = (AddressRecord)message.AdditionalRecords.Find(x => x.Type.Equals(DnsType.A));
                    TXTRecord     TRecord = (TXTRecord)message.AdditionalRecords.Find(x => x.Type.Equals(DnsType.TXT));

                    var services = Utils.LoadMdnsServices();
                    var name     = record.Name.ToString();
                    if (services.Contains(name) && ARecord != null)
                    {
                        var foundDevice = BuildResponse(ARecord, TRecord);
                        Uow.Commit(foundDevice);
                    }
                }
            }
        }
        public void PublishBonjour()
        {
            Logger.Instance.eventLog.WriteEntry("Starting Bonjour", EventLogEntryType.Information);
            try
            {
                bonjourService = new DNSSDService();
            }
            catch
            {
                return;
            }
            String type = "_istatserv._tcp";
            String name = String.Format("{0},{1}", Clients.Instance.ServerUUID(), Environment.MachineName);

            Bonjour.TXTRecord record = new TXTRecord();
            record.SetValue("model", "windows");
            record.SetValue("time", String.Format("{0}", DateTime.Now.Ticks));
            //manager.ServiceRegistered += new _IDNSSDEvents_ServiceRegisteredEventHandler(this.ServiceRegistered);
            Logger.Instance.eventLog.WriteEntry("Registering Bonjour Service", EventLogEntryType.Information);
            bonjourServiceRegistrar = bonjourService.Register(0, 0, name, type, null, null, ushort.Parse(Preferences.Instance.Value("port")), record, null);
        }
        public void PublishBonjour()
        {
            Logger.Instance.eventLog.WriteEntry("Starting Bonjour", EventLogEntryType.Information);
            try
            {
                bonjourService = new DNSSDService();
            }
            catch
            {
                return;
            }
            String type = "_istatserv._tcp";
            String name = String.Format("{0},{1}", Clients.Instance.ServerUUID(), Environment.MachineName);

            Bonjour.TXTRecord record = new TXTRecord();
            record.SetValue("model", "windows");
            record.SetValue("time", String.Format("{0}", DateTime.Now.Ticks));
            //manager.ServiceRegistered += new _IDNSSDEvents_ServiceRegisteredEventHandler(this.ServiceRegistered);
            Logger.Instance.eventLog.WriteEntry("Registering Bonjour Service", EventLogEntryType.Information);
            bonjourServiceRegistrar = bonjourService.Register(0, 0, name, type, null, null, ushort.Parse(Preferences.Instance.Value("port")), record, null);
        }
Beispiel #16
0
        /// <inheritdoc />
        public override ServiceProfile BuildProfile()
        {
            // Only internet addresses.
            var addresses = LocalPeer.Addresses
                            .Where(a => a.Protocols.First().Name == "ip4" || a.Protocols.First().Name == "ip6")
                            .ToArray();

            if (addresses.Length == 0)
            {
                return(null);
            }
            var ipAddresses = addresses
                              .Select(a => IPAddress.Parse(a.Protocols.First().Value));

            // Only one port is supported.
            var tcpPort = addresses.First()
                          .Protocols.First(p => p.Name == "tcp")
                          .Value;

            // Create the DNS records for this peer.  The TXT record
            // is singular and must contain the peer ID.
            var profile = new ServiceProfile(
                instanceName: LocalPeer.Id.ToBase58(),
                serviceName: ServiceName,
                port: ushort.Parse(tcpPort),
                addresses: ipAddresses
                );

            profile.Resources.RemoveAll(r => r.Type == DnsType.TXT);
            var txt = new TXTRecord {
                Name = profile.FullyQualifiedName
            };

            txt.Strings.Add(profile.InstanceName.ToString());
            profile.Resources.Add(txt);

            return(profile);
        }
Beispiel #17
0
        private Message GetPublishMessage(PublishMessageType type)
        {
            Message        message = new Message();
            ResourceRecord record;

            // This message is a response
            message.QueryResponse = true;
            // This is an authoritative response
            message.AuthoritativeAnswer = true;

            // SRV Record
            record = new SRVRecord()
            {
                TimeToLive = (type == PublishMessageType.Stop) ? TimeSpan.Zero : BroadcastTTL,
                CacheFlush = true,
                Name       = FullServiceInstanceName,
                Target     = Hostname,
                Port       = Port,
            };
            message.AnswerRecords.Add(record);

            // TXT Record
            if (TXTRecordData != null && TXTRecordData.Count > 0)
            {
                record = new TXTRecord()
                {
                    TimeToLive = (type == PublishMessageType.Stop) ? TimeSpan.Zero : BroadcastTTL,
                    CacheFlush = true,
                    Name       = FullServiceInstanceName,
                    Data       = TXTRecordData,
                };
                message.AnswerRecords.Add(record);
            }

            // PTR Record for DNS-SD Service Type Enumeration
            if (type == PublishMessageType.Normal)
            {
                record = new PTRRecord()
                {
                    TimeToLive = BroadcastTTL,
                    Name       = BonjourUtility.DNSSDServiceTypeEnumerationName,
                    DomainName = Type,
                };
                message.AnswerRecords.Add(record);
            }

            // Service PTR Record
            if (type != PublishMessageType.Initial)
            {
                record = new PTRRecord()
                {
                    TimeToLive = (type == PublishMessageType.Stop) ? TimeSpan.Zero : BroadcastTTL,
                    Name       = Type,
                    DomainName = FullServiceInstanceName,
                };
                message.AnswerRecords.Add(record);
            }

            // A Records
            if (type != PublishMessageType.Stop)
            {
                foreach (var ip in IPAddresses)
                {
                    record = new ARecord()
                    {
                        TimeToLive = BroadcastTTL,
                        CacheFlush = true,
                        Name       = Hostname,
                        Address    = ip,
                    };
                    message.AdditionalRecords.Add(record);
                }
            }

            return(message);
        }
Beispiel #18
0
        //
        // ServiceResolved
        //
        // Called by DNSServices core as a result of DNSService.Resolve()
        // call
        //
        public void ServiceResolved(

                    DNSSDService sref,

                    DNSSDFlags flags,

                    uint ifIndex,

                    String fullName,

                    String hostName,

                    ushort port,

                    TXTRecord txtRecord

                    )
        {
            m_resolver.Stop();

            m_resolver = null;

            PeerData peer = (PeerData)comboBox1.SelectedItem;

            peer.Port = port;

            try

            {

                m_resolver = m_service.QueryRecord(0, ifIndex, hostName, DNSSDRRType.kDNSSDType_A, DNSSDRRClass.kDNSSDClass_IN, m_eventManager );

            }

            catch

            {

                MessageBox.Show("QueryRecord Failed", "Error");

                Application.Exit();

            }
        }
Beispiel #19
0
        // ServiceResolved
        //
        // Called by DNSServices core as a result of DNSService.Resolve()
        public void ServiceResolved(DNSSDService sref, DNSSDFlags flags, uint ifIndex, String fullName, String hostName, ushort port, TXTRecord txtRecord)
        {
            m_resolver.Stop();
            m_resolver = null;

            PeerData peer = this.selectedPeer;

            peer.Port = port;

            try
            {
                m_resolver = m_service.QueryRecord(0, ifIndex, hostName, DNSSDRRType.kDNSSDType_A, DNSSDRRClass.kDNSSDClass_IN, m_eventManager);
            }
            catch
            {
                System.Console.WriteLine("Error - QueryRecord Failed");
            }
        }
        void ServiceResolved(DNSSDService resolver, DNSSDFlags flags, uint ifIndex, string fullname, string hostname, ushort port, TXTRecord record)
        {
            var info = new ServerInfo
            {
                Index = (int)ifIndex,
                FullName = fullname,
                HostName = hostname,
                Port = port
            };

            if (this.inProgress.ContainsKey(resolver))
            {
                info.Name = this.inProgress[resolver];

                this.inProgress.Remove(resolver);
            }
            resolver.Stop();

            this.service.GetAddrInfo(
                flags,
                ifIndex,
                DNSSDAddressFamily.kDNSSDAddressFamily_IPv4,
                hostname,
                this.eventManager);

            DoInvoke(() => Servers.Add(info));
        }
Beispiel #21
0
        static void Main(string[] args)
        {
            bool run = true;

            TcpListener controllerListener = null;
            TcpListener managementListener = null;

            var t1 = new Thread(() =>
            {
                Thread.CurrentThread.IsBackground = true;
                Thread.CurrentThread.Name         = "Advertising";

                DNSSDService service = new DNSSDService();

                TXTRecord txtRecord = new TXTRecord();
                txtRecord.SetValue("sf", "1"); // 1 means discoverable. 0 means it has been paired.
                txtRecord.SetValue("ff", "0x00");
                txtRecord.SetValue("ci", "2");
                txtRecord.SetValue("id", ID);
                txtRecord.SetValue("md", "Climenole");
                txtRecord.SetValue("s#", "1");
                txtRecord.SetValue("c#", "678");

                var mgr = new DNSSDEventManager();
                mgr.RecordRegistered  += Mgr_RecordRegistered;
                mgr.OperationFailed   += Mgr_OperationFailed;
                mgr.ServiceRegistered += Mgr_ServiceRegistered;

                var record = service.Register(0, 0, "Climenole", "_hap._tcp", null, null, 51826, txtRecord, mgr);

                Console.WriteLine("Advertising Service in background thread");
            });

            t1.Start();

            var t2 = new Thread(() =>
            {
                Thread.CurrentThread.IsBackground = true;
                Thread.CurrentThread.Name         = "Controller Port";

                IPAddress address = IPAddress.Any;
                IPEndPoint port   = new IPEndPoint(address, 51826);

                controllerListener = new TcpListener(port);
                controllerListener.Start();

                Console.WriteLine("--Controller Server Started--");

                while (run) //loop forever
                {
                    try
                    {
                        Console.WriteLine("Waiting for Controller to connect");

                        TcpClient client = controllerListener.AcceptTcpClient();

                        CurrentlyConnectedController = client;

                        Console.WriteLine("A Controller has connected!");

                        Thread clientThread = new Thread(new ParameterizedThreadStart(HandleControllerConnection));
                        clientThread.Start(client);
                    }
                    catch
                    { }
                }
            });

            t2.Start();

            var t3 = new Thread(() =>
            {
                IPAddress address = IPAddress.Any;
                IPEndPoint port   = new IPEndPoint(address, 51827);

                managementListener = new TcpListener(port);
                managementListener.Start();

                Console.WriteLine("--Management Server Started--");

                while (run) //loop forever
                {
                    try
                    {
                        Console.WriteLine("Waiting for Manager to connect");

                        TcpClient client = managementListener.AcceptTcpClient();

                        Console.WriteLine("A manager has connected!");

                        Thread clientThread = new Thread(new ParameterizedThreadStart(HandleManagerConnection));
                        clientThread.Start(client);
                    }
                    catch
                    { }
                }
            });

            t3.Start();

            Console.WriteLine("Press any key to terminate");
            Console.ReadKey();

            run = false;

            managementListener?.Stop();
            controllerListener?.Stop();

            t1?.Join();
            t2?.Join();
            t3?.Join();
        }
Beispiel #22
0
        private void ServiceResolved(DNSSDService resolver, DNSSDFlags flags, uint ifIndex, string fullName, string hostName, ushort port, TXTRecord txtRecord)
        {
            Log("Service " + hostName + ":" + port + " resolved");
            resolver.Stop();
            string serviceName = resolvers[resolver];
            Server server      = new Server(serviceName, hostName, port, this);

            Mutex.WaitOne();
            servers.Add(server);
            resolvers.Remove(resolver);
            ServerAdded?.Invoke(server);
            Mutex.ReleaseMutex();
        }
        public void ServiceResolved(
						DNSSDService    sref,  
						DNSSDFlags      flags,
						uint			ifIndex,
                        String          fullName,
                        String          hostName,
                        ushort           port,
                        TXTRecord       txtRecord
						)
        {
            ResolveData data = new ResolveData();

            data.InterfaceIndex = ifIndex;
            data.FullName		= fullName;
            data.HostName		= hostName;
            data.Port			= port;
            data.TxtRecord		= txtRecord;

            //
            // Don't forget to stop the resolver. This eases the burden on the network
            //
            resolver.Stop();
            resolver = null;

            Populate((BrowseData) browseList.SelectedItem, data);
        }
Beispiel #24
0
 public void ServiceResolved(DNSSDService service,
     DNSSDFlags flags,
     uint ifIndex,
     String fullName,
     String hostName,
     ushort port,
     TXTRecord txtRecord)
 {
     String user = null;
     String password = null;
     String path = null;
     if (txtRecord.ContainsKey("u"))
     {
         user = ByteArrayToString((byte[]) txtRecord.GetValueForKey("u"));
     }
     if (txtRecord.ContainsKey("p"))
     {
         password = ByteArrayToString((byte[]) txtRecord.GetValueForKey("p"));
     }
     if (txtRecord.ContainsKey("path"))
     {
         path = ByteArrayToString((byte[]) txtRecord.GetValueForKey("path"));
     }
     base.add(fullName, hostName, port, user, password, path);
     service.Stop();
 }
Beispiel #25
0
 private void EventManager_ServiceResolved(DNSSDService service, DNSSDFlags flags, uint ifIndex, string fullname, string hostname, ushort port, TXTRecord record)
 {
     try
     {
         strRoutine = this.Name + "; " + MethodBase.GetCurrentMethod().Name + "; ";
         //throw new NotImplementedException();
         Console.WriteLine("-------------------eventManager_ServiceResolved---------------------");
         Console.WriteLine("DNSSDService " + service + "\nDNSSDFlags " + flags + "\nifindex " + ifIndex + "\nfullname " + fullname + "hostname " + hostname + "\nport " + port + "\nrecord " + record);
         //var str = System.Text.Encoding.Default.GetString(record.GetValueForKey("macaddress"));
         //Console.WriteLine("mac " + str);
         Console.WriteLine("----------------------------------------");
         DNSSDEventManager eventManager = new DNSSDEventManager();
         //**********AddressFound************//
         eventManager.AddressFound += new _IDNSSDEvents_AddressFoundEventHandler(eventManager_AddressFound);
         DNSSDAddressFamily family = new DNSSDAddressFamily();
         service.GetAddrInfo(flags, ifIndex, family, hostname, eventManager);
     }
     catch (Exception ex)
     {
         csLog.LogError(strRoutine + ex.Message);
     }
 }
 private static void EventManager_ServiceResolved(DNSSDService service, DNSSDFlags flags, uint ifIndex, string fullname, string hostname, ushort port, TXTRecord record)
 {
     throw new NotImplementedException();
 }
Beispiel #27
0
        public void ServiceResolved(DNSSDService sref, DNSSDFlags flags, uint ifIndex, string serviceName, string hostName, ushort port, TXTRecord txtRecord)
        {
            var comm = foundComms.SingleOrDefault(r => r.NetworkResolverInfo.Resolver == sref);

            comm.NetworkResolverInfo.InterfaceIndex = ifIndex;
            comm.NetworkResolverInfo.HostName       = hostName;
            comm.NetworkResolverInfo.Port           = port;

            if (txtRecord != null)
            {
                try
                {
                    comm.NetworkResolverInfo.DeviceName   = Encoding.ASCII.GetString((byte[])txtRecord.GetValueForKey(DeviceNameKey));
                    comm.NetworkResolverInfo.SerialNumber = Encoding.ASCII.GetString((byte[])txtRecord.GetValueForKey(SerialNumberKey));
                }
                catch (Exception e)
                {
                    //Log.Error("Error reading address info", e);
                }
            }

            (comm.NetworkResolverInfo.Resolver as DNSSDService).Stop();

            comm.NetworkResolverInfo.Resolver = sref.GetAddrInfo(flags, ifIndex, DNSSDAddressFamily.kDNSSDAddressFamily_IPv4, hostName, this.eventManager);
        }
Beispiel #28
0
        public void ServiceResolved(DNSSDService sref, DNSSDFlags flags, uint ifIndex, String fullName, String hostName, ushort port, TXTRecord txtRecord)
        {
            m_resolver.Stop();
            m_eventManager.ServiceResolved -= new _IDNSSDEvents_ServiceResolvedEventHandler(ServiceResolved);

            try
            {
                // connect to server
                int i = 0;
                IPAddress[] ipa = Dns.GetHostAddresses(hostName);
                for (i = 0; i < ipa.Length; i++)
                {
                    if (!(ipa[i].IsIPv6LinkLocal || ipa[i].IsIPv6SiteLocal || ipa[i].IsIPv6Multicast))
                        break;
                }
                IPEndPoint ep = new IPEndPoint(ipa[i], port);
                skt.Connect(ep);
                byte[] buffer = new byte[12];
                skt.Receive(buffer);
                if ((buffer[1] << 8) + buffer[2] == NODENUMBER)
                {
                    nodenumber = ((long)buffer[3] << 40) + ((long)buffer[4] << 32) + (buffer[5] << 24) + (buffer[6] << 16)
                        + (buffer[7] << 8) + buffer[8];
                }
                else
                {
                    return;
                }
                skt.BeginReceive(inputbuffer, 0, 2000, SocketFlags.None, (AsyncCallback)InputTask, skt);
                serverconnected = true;
                SendHexString(INITCOMPLETE + nodenumber.ToString("X12") + nodenumber.ToString("X12"));
            }
            catch
            {
            }
        }
Beispiel #29
0
 public MdnsFactory()
 {
     ServiceName = nameof(ServiceEnum.MDNS);
     TRecord     = null;
     ARecord     = null;
 }
Beispiel #30
0
        public Task <Result> FindValue(string ip, string search)
        {
            var services = Utils.LoadMdnsServices();
            var result   = new Result {
                FoundAt = ServiceName
            };

            try
            {
                foreach (var service in services)
                {
                    try
                    {
                        Message msg = Lookup(service).GetAwaiter().GetResult();
                        if (msg != null)
                        {
                            var random = new Random();

                            #region Store result
                            ResourceRecord record = msg.Answers.FirstOrDefault();

                            if (msg.AdditionalRecords != null)
                            {
                                ARecord = (AddressRecord)msg
                                          .AdditionalRecords.Find(x => x.Type.Equals(DnsType.A));
                                TRecord = (TXTRecord)msg
                                          .AdditionalRecords.Find(x => x.Type.Equals(DnsType.TXT));

                                var DeviceName = Utils.Common;
                                var DeviceId   = Utils.Common;

                                if (ARecord?.Address.ToString().Equals(ip) == true)
                                {
                                    DeviceId = ARecord.Name.Labels
                                               .FirstOrDefault()?.Replace("-", "") ?? Utils.Common;
                                    DeviceName = ARecord.Name.Labels
                                                 .FirstOrDefault() ?? Utils.Common;
                                }

                                if (TRecord != null)
                                {
                                    var prop = TRecord.Strings.Find(x => x.Contains("fn"));
                                    if (prop != null)
                                    {
                                        var info = prop.Split("=");
                                        DeviceName = info[0];
                                    }
                                }

                                switch (search.ToUpper())
                                {
                                case "SYSTEMNAME":
                                    result.Value = DeviceName;
                                    break;

                                case "SERIAL":
                                    result.Value = DeviceId;
                                    break;
                                }

                                if (ARecord != null || TRecord != null)
                                {
                                    // Uow.Commit(foundDevice);
                                    return(Task.Run(() => result));
                                }
                            }
                            else
                            {
                                // ToDo: what should I do then...
                            }
                            #endregion
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }
                return(Task.Run(() => new Result()
                {
                    Value = Utils.Common
                }));
            }
            catch (Exception)
            {
                return(Task.Run(() => new Result()
                {
                    Value = Utils.Common
                }));
            }
        }
Beispiel #31
0
        public void ServiceResolved(DNSSDService sref, DNSSDFlags flags, uint ifIndex, String fullName,
            String hostName, ushort port, TXTRecord txtRecord)
        {
            m_resolver.Stop();
            m_eventManager.ServiceResolved -= new _IDNSSDEvents_ServiceResolvedEventHandler(ServiceResolved);

            log("OpenLCB service on " + hostName + ":" + port.ToString());

            try
            {
                // connect to server
                int i = 0;
                IPAddress[] ipa = Dns.GetHostAddresses(hostName);
                for (i = 0; i < ipa.Length; i++)
                {
                    if (ipa[i].AddressFamily == AddressFamily.InterNetwork)
                        break;
                }
                IPEndPoint ep = new IPEndPoint(ipa[i], port);
                connects[0].skt.Connect(ep);
                connects[0].inuse = true;
                byte[] buffer = new byte[12];
                connects[0].skt.Receive(buffer);
                if ((buffer[1] << 8) + buffer[2] == NODENUMBER)
                {
                    connects[0].nodenumber = ((long)buffer[3] << 40) + ((long)buffer[4] << 32) + (buffer[5] << 24)
                        + (buffer[6] << 16) + (buffer[7] << 8) + buffer[8];
                    log("OpenLCB Node Number " + connects[0].nodenumber.ToString("X12"));
                }
                else
                {
                    log("No node number allocated.");
                    return;
                }

                while (true)
                {
                    int size = connects[0].skt.Receive(connects[0].buffer);
                    if (size == 0)
                        break;
                    if (LogCB.Checked)
                    {
                        string l = "";
                        for (i = 0; i < size; i++)
                            l += connects[0].buffer[i].ToString("X2");
                        log("< (" + 0.ToString() + ") " + l);
                    }
                    int p = 0;
                    while (p < size)
                    {
                        connects[0].UpdateFilters(connects[0].buffer, p, localhub);
                        SendToAll(connects[0].buffer, p, 0);
                        p += connects[0].buffer[p];
                    }
                } // end of while true
            }
            catch (Exception e)
            {
                log("OpenLCB server connection failed " + e.ToString());
            }
        }
Beispiel #32
0
 private void M_eventManager_ServiceResolved(DNSSDService service, DNSSDFlags flags, uint ifIndex, string fullname, string hostname, ushort port, TXTRecord record)
 {
     Program.logIt($"fullname={fullname}, hostname={hostname}, port={port}");
     if (record != null)
     {
         uint count = record.GetCount();
         for (uint i = 0; i < count; i++)
         {
             string  k = record.GetKeyAtIndex(i);
             dynamic v = record.GetValueAtIndex(i);
         }
     }
     m_service.QueryRecord(0, ifIndex, hostname, DNSSDRRType.kDNSSDType_A, DNSSDRRClass.kDNSSDClass_IN, m_eventManager);
 }