Esempio n. 1
0
 /// <summary>
 /// 获取指定IP的机器名
 /// </summary>
 /// <param name="address">一个System.Net.IPAddress</param>
 /// <returns>机器名</returns>
 public static string GetIPHostName(System.Net.IPAddress address)
 {
     try
     {
         System.Net.IPHostEntry iphe = Dns.GetHostByAddress(address.ToString());
         return(iphe.HostName);
     }
     catch
     {
         return("<未知>");
     }
 }
Esempio n. 2
0
 public void GetHostByAddressString_Address_Null()
 {
     try {
         Dns.GetHostByAddress((string)null);
         Assert.Fail("#1");
     } catch (ArgumentNullException ex) {
         Assert.AreEqual(typeof(ArgumentNullException), ex.GetType(), "#2");
         Assert.IsNull(ex.InnerException, "#3");
         Assert.IsNotNull(ex.Message, "#4");
         Assert.AreEqual("address", ex.ParamName, "#5");
     }
 }
    public void DisplayHostAddress(String IpAddressString)
    {
        // Call 'GetHostByAddress(IPAddress)' method giving an 'IPAddress' object as argument.
        // Obtain an 'IPHostEntry' instance, containing address information of the specified host.
// <Snippet1>
        try
        {
            IPAddress   hostIPAddress = IPAddress.Parse(IpAddressString);
            IPHostEntry hostInfo      = Dns.GetHostByAddress(hostIPAddress);
            // Get the IP address list that resolves to the host names contained in
            // the Alias property.
            IPAddress[] address = hostInfo.AddressList;
            // Get the alias names of the addresses in the IP address list.
            String[] alias = hostInfo.Aliases;

            Console.WriteLine("Host name : " + hostInfo.HostName);
            Console.WriteLine("\nAliases :");
            for (int index = 0; index < alias.Length; index++)
            {
                Console.WriteLine(alias[index]);
            }
            Console.WriteLine("\nIP address list : ");
            for (int index = 0; index < address.Length; index++)
            {
                Console.WriteLine(address[index]);
            }
        }
        catch (SocketException e)
        {
            Console.WriteLine("SocketException caught!!!");
            Console.WriteLine("Source : " + e.Source);
            Console.WriteLine("Message : " + e.Message);
        }
        catch (FormatException e)
        {
            Console.WriteLine("FormatException caught!!!");
            Console.WriteLine("Source : " + e.Source);
            Console.WriteLine("Message : " + e.Message);
        }
        catch (ArgumentNullException e)
        {
            Console.WriteLine("ArgumentNullException caught!!!");
            Console.WriteLine("Source : " + e.Source);
            Console.WriteLine("Message : " + e.Message);
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception caught!!!");
            Console.WriteLine("Source : " + e.Source);
            Console.WriteLine("Message : " + e.Message);
        }
// </Snippet1>
    }
Esempio n. 4
0
 /// <summary>
 /// 获取指定IP的机器名
 /// </summary>
 /// <param name="IPStr">表示IP地址的字符串</param>
 /// <returns>机器名</returns>
 public static string GetIPHostName(string IPStr)
 {
     try
     {
         System.Net.IPHostEntry iphe = Dns.GetHostByAddress(IPStr);
         return(iphe.HostName);
     }
     catch
     {
         return("<未知>");
     }
 }
Esempio n. 5
0
        static void Main(string[] args)
        {
            IPHostEntry iphost = Dns.GetHostByAddress(IPAddress.Loopback);

            Console.WriteLine("host name: " + iphost.HostName);
            Console.WriteLine("Day IP: ");
            foreach (IPAddress ip in iphost.AddressList)
            {
                Console.WriteLine(ip);
            }
            Console.ReadLine();
        }
Esempio n. 6
0
    public static void Main(string[] argv)
    {
        IPAddress test = IPAddress.Parse("192.168.1.1");

        IPHostEntry iphe = Dns.GetHostByAddress(test);

        Console.WriteLine(iphe.HostName);

        foreach (IPAddress address in iphe.AddressList)
        {
            Console.WriteLine("Address: {0}", address.ToString());
        }
    }
Esempio n. 7
0
 /// <summary>
 /// Generate the instance id for a <see cref="IScheduler" />
 /// </summary>
 /// <returns>The clusterwide unique instance id.</returns>
 public virtual string GenerateInstanceId()
 {
     try
     {
         return
             (Dns.GetHostByAddress(Dns.GetHostByName(Dns.GetHostName()).AddressList[0].ToString()).HostName +
              SystemTime.UtcNow().Ticks);
     }
     catch (Exception e)
     {
         throw new SchedulerException("Couldn't get host name!", e);
     }
 }
Esempio n. 8
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string remoteAddress = "85.215.188.44";
            bool   trusted       = false;

            IPAddress   hostIPAddress = IPAddress.Parse(remoteAddress);
            IPHostEntry hostInfo      = Dns.GetHostByAddress(hostIPAddress);

            if (hostInfo.HostName.EndsWith("trustme.com"))
            {
                trusted = true;
            }
        }
Esempio n. 9
0
        static void Main(string[] args)
        {
            IPHostEntry iphost = Dns.GetHostByAddress(IPAddress.Loopback);

            Console.WriteLine("host name: " + iphost.HostName);
            Console.WriteLine("Day IP: ");
            foreach (IPAddress ip in iphost.AddressList)
            {
                Console.WriteLine(ip);
            }
            Console.ReadLine();
            //iuwegafiuasgfiuahseiufhaesfhaiuesfhaseiuf afhawerweah iurahwriu
        }
Esempio n. 10
0
        public static string GetLocalIp()
        {
            System.Net.IPHostEntry ipEntry = Dns.GetHostByAddress(Environment.MachineName);

            foreach (System.Net.IPAddress ip in ipEntry.AddressList)
            {
                if (System.Net.IPAddress.IsLoopback(ip) == false)
                {
                    return(ip.ToString());
                }
            }

            return(System.Net.IPAddress.Loopback.ToString());
        }
Esempio n. 11
0
        /// <summary>
        /// 機器登録
        /// </summary>
        /// <param name="packet">受信ARPパケット</param>
        private void DeviceRegister(Packet packet)
        {
            // イーサネットタイプがARP以外は破棄
            if (packet.Ethernet.EtherType != EthernetType.Arp)
            {
                return;
            }

            var arp = packet.Ethernet.Arp;

            lock (this.lockObj) {
                // 送信元MACアドレスが登録済みの場合は破棄
                if (this.Devices.Any(x => x.MacAddress.SequenceEqual(arp.SenderHardwareAddress.ToArray())))
                {
                    return;
                }

                this.Devices.Add(new Device()
                {
                    IPAddress  = new CalculatableIPAddress(arp.SenderProtocolAddress.ToArray()),
                    MacAddress = arp.SenderHardwareAddress.ToArray()
                });

                // 時間のかかるベンダ検索、ホスト名逆引き処理をTask化
                this.taskList.Add(
                    Task.Run(() => {
                    using (var dataContext = new VendorDbContext(this._vendorDbPath)) {
                        foreach (var device in this.Devices)
                        {
                            var vendorId  = string.Join("", device.MacAddress.Take(3).Select(m => $"{m:X2}"));
                            device.Vendor = dataContext.Vendors.FirstOrDefault(x => x.Assignment == vendorId);
                            try {
#pragma warning disable CS0618 // 型またはメンバーが古い形式です
                                // Dns.GetHostEntryは正引き出来ないと失敗となるためDns.GetHostByAddressを使用する。
                                device.HostName = (Dns.GetHostByAddress(device.IPAddress)).HostName;
#pragma warning restore CS0618 // 型またはメンバーが古い形式です
                            } catch (SocketException) {
                            }
                        }
                    }
                })
                    );

                // 完了済みの削除
                this.taskList.RemoveAll(task =>
                                        task.Status == TaskStatus.RanToCompletion ||
                                        task.Status == TaskStatus.Canceled ||
                                        task.Status == TaskStatus.Faulted);
            }
        }
Esempio n. 12
0
 /// <summary>
 /// </summary>
 /// <returns></returns>
 public static string GetClientHost()
 {
     try
     {
         var address = IPAddress.Parse(GetClientIp());
         var ipInfor = Dns.GetHostByAddress(address);
         return(ipInfor.HostName);
     }
     catch (Exception ex)
     {
         //LogWriter.WriteLog(FolderName.Error, ex.Message);
         return("");
     }
 }
Esempio n. 13
0
        /// <summary>
        /// 枚举本地OPC服务器
        /// </summary>
        public string[] GetLocalServer()
        {
            List <string> list = new List <string>();

            string strHostIP   = "";
            string strHostName = "";

            //获取本地计算机IP,计算机名称
            IPHostEntry IPHost = Dns.Resolve(Environment.MachineName);

            if (IPHost.AddressList.Length > 0)
            {
                strHostIP = IPHost.AddressList[0].ToString();
            }
            else
            {
                return(list.ToArray());
            }
            //通过IP来获取计算机名称,可用在局域网内
            IPHostEntry ipHostEntry = Dns.GetHostByAddress(strHostIP);

            strHostName = ipHostEntry.HostName.ToString();

            Console.WriteLine("HostName is: " + strHostName);

            //获取本地计算机上的OPCServerName
            try
            {
                OPCServer OpcServer = new OPCServer();
                object    result    = OpcServer.GetOPCServers(strHostName);



                if (result != null && result is Array)
                {
                    Array servers = result as Array;
                    foreach (string s in servers)
                    {
                        list.Add(s);
                    }
                }
            }
            catch (Exception err)
            {
                Console.WriteLine("枚举本地OPC服务器出错:" + err.Message);
                //MessageBox.Show("枚举本地OPC服务器出错:"+err.Message,"提示信息",MessageBoxButtons.OK,MessageBoxIcon.Warning);
            }
            return(list.ToArray());
        }
Esempio n. 14
0
        public void StartDaemon()
        {
            string remoteAddr = Client.RemoteEndPoint.ToString();

            remoteAddr = remoteAddr.Substring(0, remoteAddr.IndexOf(':'));
            string remoteHost = Dns.GetHostByAddress(IPAddress.Parse(remoteAddr)).HostName;

            ClientInfo.Options.remoteAddr = remoteAddr;
            ClientInfo.Options.remoteHost = remoteHost;


            Daemon.StartDaemon(ClientInfo);
            Client.Close();
            ClientSockets.Remove(this);
        }
Esempio n. 15
0
    /// <summary>
    /// Start listening for a local application to connected to saved EndPoint
    /// </summary>
    private void StartListener()
    {
        // Confirm supplied address is local to this computer
        var ipAddress = ((IPEndPoint)_listenerEP).Address;

        if (Dns.GetHostByAddress(ipAddress).HostName != Dns.GetHostByAddress("127.0.0.1").HostName)
        {
            SendNotification(this, new ProxyMessage {
                Message = $"Supplied Listener Address: {ipAddress.ToString()} is not local to this computer", Severity = 1
            });
            return;
        }

        _listener.Listen(_listenerEP);
    }
        /// <summary>
        /// Generate the instance id for a <see cref="IScheduler"/>
        /// </summary>
        /// <returns>The clusterwide unique instance id.</returns>
        public virtual string GenerateInstanceId()
        {
            try
            {
#if NET_20
                return(Dns.GetHostName());
#else
                return
                    (Dns.GetHostByAddress(Dns.GetHostByName(Dns.GetHostName()).AddressList[0].ToString()).HostName);
#endif
            }
            catch (Exception e)
            {
                throw new SchedulerException("Couldn't get host name!", e);
            }
        }
Esempio n. 17
0
        public override void Bad()
        {
            switch (7)
            {
            case 7:
                IPAddress hostIPAddress = IPAddress.Parse("8.8.8.8");
                /* FLAW: Use of deprecated Dns.GetHostByAddress() method */
                IPHostEntry hostInfo = Dns.GetHostByAddress(hostIPAddress);
                IO.WriteLine("Host name : " + hostInfo.HostName);
                break;

            default:
                /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
                IO.WriteLine("Benign, fixed string");
                break;
            }
        }
Esempio n. 18
0
        public void HandleIncome(int port)
        {
            bool done = false;

            listener = new UdpClient(port);
            IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, port);

            try
            {
                while (!done)
                {
                    byte[] bytes = listener.Receive(ref groupEP);
                    if (System.Text.Encoding.UTF8.GetString(bytes).Equals(msg_check))
                    {
                        SendContent(groupEP.Address.ToString(), msg_check_back);
                    }
                    if (System.Text.Encoding.UTF8.GetString(bytes).Equals(msg_check_back))
                    {
                        string machineName = null;
                        string host        = groupEP.Address.ToString();

                        try
                        {
                            machineName = Dns.GetHostByAddress(host).HostName;
                        }
                        catch (Exception ex)
                        {
                            machineName = "";
                        }
                        this.Invoke((MethodInvoker)(() => listBox_users.Items.Add(host + " " + machineName)));
                        //Console.WriteLine("Connected to the client {0}, {1}", groupEP, Encoding.ASCII.GetString(bytes));

                        //SendContent(host, msg_check);
                        //this.Invoke((MethodInvoker)(() => listBox_users.Items.Add(host + " " + machineName)));
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {
                listener.Close();
            }
        }
 public override void Bad()
 {
     if (IO.StaticReturnsTrueOrFalse())
     {
         IPAddress hostIPAddress = IPAddress.Parse("8.8.8.8");
         /* FLAW: Use of deprecated Dns.GetHostByAddress() method */
         IPHostEntry hostInfo = Dns.GetHostByAddress(hostIPAddress);
         IO.WriteLine("Host name : " + hostInfo.HostName);
     }
     else
     {
         IPAddress hostIPAddress = IPAddress.Parse("8.8.8.8");
         /* FIX: Use preferred Dns.GetHostEntry() method */
         IPHostEntry hostInfo = Dns.GetHostEntry(hostIPAddress);
         IO.WriteLine("Host name : " + hostInfo.HostName);
     }
 }
        private string GetPCName(string _IP)
        {
            string _PCName = "NA";

            try
            {
                IPHostEntry ip = Dns.GetHostByAddress(_IP);
                _PCName = ip.HostName.ToString();
            }
            catch (Exception a)
            {
                return(_PCName);
                //   _PCName = "NA";
            }

            return(_PCName);
        }
Esempio n. 21
0
        private void dNSForIPToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string Ipv4 = "";

            InputBox("Resolve", "Enter IPV4 address", ref Ipv4);
            LB.Items.Add("Looking up " + Ipv4);

            try
            {
                IPHostEntry host = Dns.GetHostByAddress(Ipv4);
                LB.Items.Add(host.HostName);
            }
            catch (Exception em)
            {
                LB.Items.Add(em.Message);
            }
        }
Esempio n. 22
0
        private void btLangNghe_Click(object sender, EventArgs e)
        {
            // Khai bao cac thanh phan de ket noi
            IPHostEntry host = Dns.GetHostByAddress("127.0.0.1");
            IPAddress   ip   = host.AddressList[0];
            IPEndPoint  ep   = new IPEndPoint(ip, 12000);

            byte[] boDem = new byte[1024];

            // Lang nghe cac ket noi den
            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                server.Bind(ep);
                server.Listen(10);
                String data = "";
                while (true)
                {
                    // Neu co ket noi den thi nhan du lieu va phan hoi
                    Socket client = server.Accept();
                    while (true)
                    {
                        int byteNhan = client.Receive(boDem);
                        data += Encoding.UTF8.GetString(boDem).Trim();
                        if (data.ToLower().Contains("<eof>"))
                        {
                            break;
                        }
                    }

                    String duongDan = Application.StartupPath + "\\..\\..\\log.txt";
                    using (StreamWriter sw = new StreamWriter(duongDan, true, Encoding.UTF8))
                    {
                        sw.WriteLine(DateTime.Now + ":" + data.Trim());
                    }

                    client.Send(Encoding.UTF8.GetBytes("Da nhan"));

                    client.Shutdown(SocketShutdown.Both);
                    client.Close();
                }
            }
            catch { }
        }
Esempio n. 23
0
        public static string GetHostName(string ipAddress)
        {
            string hostName = string.Empty;

            try
            {
                IPAddress   hostIPAddress = IPAddress.Parse(ipAddress);
                IPHostEntry hostInfo      = Dns.GetHostByAddress(hostIPAddress);

                IPAddress[] address = hostInfo.AddressList;
                String[]    alias   = hostInfo.Aliases; // In case I want to do something with this later

                hostName = ("Host name : " + hostInfo.HostName);
            }
            catch (SocketException e)
            {
                Logger.Warn(ipAddress);
                Logger.Warn("SocketException");
                Logger.Warn("Source : " + e.Source);
                Logger.Warn("Message : " + e.Message);
            }
            catch (FormatException e)
            {
                Logger.Warn(ipAddress);
                Logger.Warn("FormatException");
                Logger.Warn("Source : " + e.Source);
                Logger.Warn("Message : " + e.Message);
            }
            catch (ArgumentNullException e)
            {
                Logger.Warn(ipAddress);
                Logger.Warn("ArgumentNullException");
                Logger.Warn("Source : " + e.Source);
                Logger.Warn("Message : " + e.Message);
            }
            catch (Exception e)
            {
                Logger.Warn(ipAddress);
                Logger.Warn("Exception");
                Logger.Warn("Source : " + e.Source);
                Logger.Warn("Message : " + e.Message);
            }

            return(hostName);
        }
Esempio n. 24
0
 private void AutoDnsButton_Click(object sender, EventArgs e)
 {
     foreach (DataGridViewRow row in AliasGridView.SelectedRows)
     {
         try
         {
             row.AccessibilityObject.GetChild(2).Value =
                 Dns.GetHostByAddress(IPAddress.Parse(
                                          row.AccessibilityObject.GetChild(1).Value)).HostName;
             AliasGridView.Update();
         }
         catch
         {
             row.AccessibilityObject.GetChild(1).Value = "!!!" +
                                                         row.AccessibilityObject.GetChild(1).Value;
         }
     }
 }
Esempio n. 25
0
        private static void StartClient()
        {
            // Connect to a remote device.
            try
            {
                // Establish the remote endpoint for the socket.
                // The name of the
                // remote device is "host.contoso.com".
                //IPHostEntry ipHostInfo = Dns.GetHostEntry("host.contoso.com");
                IPHostEntry ipHostInfo = Dns.GetHostByAddress("127.0.0.1");
                //IPAddress ipAddress = ipHostInfo.AddressList[0];
                IPAddress  ipAddress = ipHostInfo.AddressList[0];
                IPEndPoint remoteEP  = new IPEndPoint(ipAddress, port);

                // Create a TCP/IP socket.
                Socket client = new Socket(ipAddress.AddressFamily,
                                           SocketType.Stream, ProtocolType.Tcp);

                // Connect to the remote endpoint.
                client.BeginConnect(remoteEP,
                                    new AsyncCallback(ConnectCallback), client);
                connectDone.WaitOne();

                // Send test data to the remote device.
                Send(client, "This is a test<EOF>");
                sendDone.WaitOne();

                // Receive the response from the remote device.
                Receive(client);
                //receiveDone.WaitOne();

                // Write the response to the console.

                Console.WriteLine("Response received : {0}", response);

                // Release the socket.
                client.Shutdown(SocketShutdown.Both);
                client.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
Esempio n. 26
0
        /// <summary>
        /// 枚举本地OPC服务器
        /// </summary>
        private void GetLocalServer()
        {
            //OpcClient opc = new DaOpc();
            //List<DaOpcItem> s = new List<DaOpcItem>();
            //opc.GetItemValues(s);


            //获取本地计算机IP,计算机名称
            IPHostEntry IPHost = Dns.Resolve(Environment.MachineName);

            if (IPHost.AddressList.Length > 0)
            {
                strHostIP = IPHost.AddressList[0].ToString();
            }
            else
            {
                return;
            }
            //通过IP来获取计算机名称,可用在局域网内
            IPHostEntry ipHostEntry = Dns.GetHostByAddress(strHostIP);

            strHostName = ipHostEntry.HostName.ToString();

            //获取本地计算机上的OPCServerName
            try
            {
                KepServer = new OPCServer();
                object serverList = KepServer.GetOPCServers(strHostName);

                foreach (string turn in (Array)serverList)
                {
                    cmbServerName.Items.Add(turn);
                }

                cmbServerName.SelectedIndex = 0;
                btnConnServer.Enabled       = true;
            }
            catch (Exception err)
            {
                MessageBox.Show("枚举本地OPC服务器出错:" + err.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
Esempio n. 27
0
        private void CheckByIpButtonClick(object sender, RoutedEventArgs e)
        {
            nameTextBox.Text = "";
            if (nameTextBox.Text == "" && ipTextBox.Text != "")
            {
                try
                {
                    IPHostEntry ipList = Dns.GetHostByAddress(ipTextBox.Text);

                    foreach (var a in ipList.HostName)
                    {
                        nameTextBox.Text += a.ToString();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }
Esempio n. 28
0
        public override void Connect()
        {
            base.Connect();

            m_ReadBuffer = null;
            m_ReadBuffer = new byte[BUFFERSIZE];

            m_SocksConnected = false;

            //IPHostEntry ipHostInfo = Dns.Resolve(Address);
            IPHostEntry ipHostInfo = Dns.GetHostByAddress(Address);
            //Dns.GetHostEntry
            IPAddress ipAddress = ipHostInfo.AddressList[0];// IPAddress.Parse(address);
            //IPAddress ipAddress =  IPAddress.Parse(Address);

            IPEndPoint endPoint = new IPEndPoint(ipAddress, Port);

            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            _socket.BeginConnect(endPoint, new AsyncCallback(EndConnect), null);
        }
Esempio n. 29
0
            public void scan()
            {
                IPAddress myIP = IPAddress.Parse(ip);

                try
                {
                    IPHostEntry myHost = Dns.GetHostByAddress(myIP);
                    HostName = myHost.HostName.ToString();
                }
                catch
                {
                    HostName = "";
                }
                if (HostName == "")
                {
                    HostName = "主机没有响应";
                }
                if (ul != null)
                {
                    ul(ip, HostName, BangName);
                }
            }
Esempio n. 30
0
 public static string GetName(string ip)
 {
     if (!DnsNames_.Contains(ip))
     {
         try
         {
             IPHostEntry tmp = Dns.GetHostByAddress(ip);
             if (!DnsNames_.Contains(ip))
             {
                 DnsNames_.Add(ip, tmp.HostName);
             }
         }
         catch (Exception)
         {
             if (!DnsNames_.Contains(ip))
             {
                 DnsNames_.Add(ip, ip);
             }
         }
     }
     return((string)DnsNames_[ip]);
 }