Beispiel #1
0
        private void btn_GetLocation_Click(object sender, EventArgs e)
        {
            System.Net.IPHostEntry myEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());
            string ipAddress = myEntry.AddressList[0].ToString();

            this.Text = ipAddress;
        }
Beispiel #2
0
        private void button3_Click(object sender, EventArgs e)
        {
            //string x = Dns.GetHostName();
            //try
            //{
            //    string PCName = Dns.GetHostEntry(IPAddress.Parse(textBox4.Text)).HostName;
            //    textBox5.Text = PCName;
            //}
            //catch (Exception ex)
            //{
            //    textBox5.Text = "Fail";

            //}
            ////Dns.GetHostEntry(System.Web.HttpContext.Current.Request.ServerVariables["192.168.0.10"]).HostName;

            //  IPAddress ip = IPAddress.Parse(textBox4.Text);
            try
            {
                System.Net.IPHostEntry ip = System.Net.Dns.GetHostByAddress(textBox4.Text);
                //Console.WriteLine("IP Address {0}: {1}", ++AddressCount, ip.HostName);
                textBox5.Text = ip.HostName.ToString();
            }
            catch (Exception ex)
            {
                textBox5.Text = "FAIL";
            }
        }
Beispiel #3
0
        public void Connect()
        {
            System.Net.IPHostEntry hostIps = System.Net.Dns.GetHostEntry(host);
            connctHost = hostIps.AddressList[0];

#if TESTMODE
            System.Diagnostics.Debug.WriteLine("-------------------------------------");
            System.Diagnostics.Debug.WriteLine("Dns back");
            foreach (var tempIp in hostIps.AddressList)
            {
                System.Diagnostics.Debug.WriteLine(tempIp.ToString());
            }
            System.Diagnostics.Debug.WriteLine("-------------------------------------");
#endif

            mySocket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //mySocket.NoDelay = true;
            IPEndPoint hostEndPoint = new IPEndPoint(connctHost, 443);
            mySocket.Connect(hostEndPoint);
            {
                //ThreadPool.QueueUserWorkItem(new WaitCallback(ReceviData), mySocket);  //这里使用线程池将失去部分对线程的控制能力(创建及启动会自动被延迟)
                reciveThread = new Thread(new ParameterizedThreadStart(ReceviData));
                reciveThread.IsBackground = true;
                reciveThread.Start(mySocket);
            }
            Console.WriteLine("connect ok");
        }
Beispiel #4
0
        static public string DNS2IP(string dns)
        {
            string ret;
            bool   bIsIp = false;

            try
            {
                System.Net.IPAddress.Parse(dns);
                bIsIp = true;
            }
            catch (Exception ex)
            {
                bIsIp = false;
                System.Console.Write(ex.Message);
            }
            try
            {
                if (!bIsIp)
                {
                    System.Net.IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(dns);
                    System.Net.IPAddress[] addr    = ipEntry.AddressList;
                    ret = addr[0].ToString();
                }
                else
                {
                    ret = dns;
                }
            }
            catch (Exception e)
            {
                System.Windows.Forms.MessageBox.Show(dns + e.Message);
                ret = dns;
            }
            return(ret);
        }
Beispiel #5
0
        public String GetIP(string host)
        {
            String ipadr = "";

            System.Net.IPHostEntry ipentry = null;
            try
            {
                ipentry = System.Net.Dns.GetHostEntry(host.Replace("CN=", ""));
                System.Net.IPAddress[] addrs = ipentry.AddressList;
                foreach (System.Net.IPAddress addr in addrs)
                {
                    //Limit to IPv4 for now
                    if (addr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        ipadr += addr.ToString() + ",";
                        Application.DoEvents();
                    }
                }
                ipadr = ipadr.Substring(0, ipadr.Length - 1);
            }
            catch
            {
                ipadr = StringValue.UnknownHost;
            }
            return(ipadr);
        }
Beispiel #6
0
        private IPAddress GetLocalAddress()
        {
            #region Getting Local Address Logic; might be replace with getting address from service config

            IPAddress localAddress = null;

            string localIP = ConfigurationSettings.AppSettings["ManagementServerIP"];
            try
            {
                localAddress = System.Net.IPAddress.Parse(localIP);
            }
            catch (Exception ex)
            {
                System.Net.IPHostEntry hostEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());


                if (hostEntry.AddressList != null)
                {
                    foreach (System.Net.IPAddress addr in hostEntry.AddressList)
                    {
                        if (addr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                        {
                            localAddress = addr;
                            break;
                        }
                    }
                }
            }
            return(localAddress);

            #endregion
        }
Beispiel #7
0
        public ManagementClass GetManagementClass(string scopeString, string classString, IPHostEntry hostEntry, string username, string password)
        {
            SetHost(hostEntry);
            ValidateHost();

            var connectionOptions = new ConnectionOptions()
            {
                Impersonation = ImpersonationLevel.Impersonate,
                EnablePrivileges = true,
                Username = username,
                Password = password
            };

            var managementScope = new ManagementScope(String.Format(@"\\{0}\{1}", _host, scopeString), connectionOptions);
            var managementClass = new ManagementClass(managementScope, new ManagementPath(classString), new ObjectGetOptions());

            managementScope.Connect();

            if (!managementScope.IsConnected)
            {
                throw new InstrumentationException(ExceptionMessages.ScopeConnectFail);
            }

            return managementClass;
        }
        public void Delete(IPHostEntry host, DirectoryInfo target)
        {
            var wqlQuery = new ObjectQuery(string.Format(@"SELECT * from Win32_Directory WHERE Name = '{0}'", target.Name));

            var managementClassEntry = _managementClassList.First(x => x.Item1 == _hostsList.IndexOf(host));
            ManagementObjectSearcher objectSearcher = new ManagementObjectSearcher(managementClassEntry.Item2.Scope, wqlQuery);
            ManagementObjectCollection directoryObjectsCollection = objectSearcher.Get();

            if (directoryObjectsCollection.Count == 0)
            {
                throw new FileSystemInstrumentationException(@"{0} {1}.", ExceptionMessages.Win32_DirectoryFail, target.Name);
            }

            foreach (ManagementObject shareObject in directoryObjectsCollection)
            {
                PropertyDataCollection outParams;
                long returnValue;

                managementClassEntry.Item3.Handle("Delete", new List<PropertyDataObject>(), out outParams);

                returnValue = long.Parse(outParams["ReturnValue"].Value.ToString());

                if (returnValue != 0)
                {
                    throw new FileSystemInstrumentationException(@"{0} {1}.", ExceptionMessages.Win32_DirectoryFail, _errorMessageProvider.GetErrorMessage(ErrorMessageProvider.ErrorClass.Win32_Directory, returnValue));
                }
            }
        }
Beispiel #9
0
 /// <summary>
 /// Connect to Server:Port
 /// </summary>
 public void Connect(IPHostEntry ip, Int32 Port)
 {
     foreach (IPAddress addr in ip.AddressList)
     {
         this.Connect(addr, Port);
     }
 }
Beispiel #10
0
		// Run the operation thread.
		public void BeginInvoke(String hostName)
				{
					try
					{
						switch(operation)
						{
							case DnsOperation.GetHostByName:
							{
								acceptResult = Dns.GetHostByName(hostName);
							}
							break;

							case DnsOperation.Resolve:
							{
								acceptResult = Dns.Resolve(hostName);
							}
							break;
						}
					}
					catch(Exception e)
					{
						// Save the exception to be thrown in EndXXX.
						exception = e;
					}
					completed = true;
					if(callback != null)
					{
						callback(this);
					}
				#if ECMA_COMPAT
					SocketMethods.WaitHandleSet(waitHandle);
				#else
					((ManualResetEvent)waitHandle).Set();
				#endif
				}
 protected ArrayList alBuscarUsuarios()
 {
     ipHostName = Dns.GetHostEntry(Dns.GetHostName());
     foreach (IPAddress ip in ipHostName.AddressList)
     {
         sQuery = "SELECT cuenta_usr, foto_usr FROM tabm_SGusuario T1 INNER JOIN tabt_SGsesion T2 ON T2.cod_usr = T1.cod_usr WHERE ipdir_usr= \"" + ip.ToString() + "\" LIMIT 6";
         if (bAbrirConexion())
         {
             try
             {
                 OdbcCommand ocComando = new OdbcCommand(sQuery, Conexion);
                 OdbcDataReader odcReader = ocComando.ExecuteReader();
                 while (odcReader.Read())
                 {
                     E_Usuario eUsuario = new E_Usuario();
                     eUsuario.Cuenta = odcReader[0].ToString();
                     eUsuario.ImagenBytes = (byte[])odcReader[1];
                     alResultados.Add(eUsuario);
                 }
                 vCerrarConexion();
             }
             catch (OdbcException ex)
             {
                 return null;
             }
         }
     }
     return alResultados;
 }
Beispiel #12
0
        /// <summary>
        /// 檢查是否有連接網路的能力。
        /// </summary>
        /// <returns></returns>
        public static bool IsNetworkConnected()
        {
            try
            {
                System.Net.IPHostEntry entry = System.Net.Dns.GetHostEntry("www.google.com");
                return(true);
            }
            catch
            {
                return(false);
            }

/*以下作法在某些環境會出現 WMI 物件的 TypeInitializationException,故不使用。
 *          bool connected = false;
 *          string qry = "SELECT NetConnectionStatus FROM Win32_NetworkAdapter";
 *
 *          using (ManagementObjectSearcher mngSearcher = new ManagementObjectSearcher(qry))
 *          {
 *              ManagementObjectCollection mngObjects = mngSearcher.Get();
 *              foreach (ManagementObject networkAdapter in mngObjects)
 *              {
 *                  if (networkAdapter["NetConnectionStatus"] != null)
 *                  {
 *                      if (Convert.ToInt32(networkAdapter["NetConnectionStatus"]).Equals(2))
 *                      {
 *                          connected = true;
 *                          break;
 *                      }
 *                  }
 *              }
 *          }
 *          return connected;
 */
        }
Beispiel #13
0
 public string GetHostNameByIp(string ip)
 {
     ip = ip.Trim();
     if (ip == string.Empty)
     {
         return(string.Empty);
     }
     try
     {
         // 是否 Ping 的通
         if (this.Ping(ip))
         {
             System.Net.IPHostEntry host = System.Net.Dns.GetHostEntry(ip);
             return(host.HostName);
         }
         else
         {
             return(string.Empty);
         }
     }
     catch (Exception)
     {
         return(string.Empty);
     }
 }
Beispiel #14
0
        public void GetIP4AddressTest_MissingIP4Address()
        {
            // Testing the failure when the IP4Address format is missing from the structure.
            String localName = m_library.GetLocalName();

            System.Net.IPHostEntry IPHEntry = m_communications.GetIPHostInfo(localName);

            IPAddress fakeAddress;
            String    fakeAddressString = "fe80::7d02:2f4c:6208:edc2%12";

            fakeAddress = IPAddress.Parse(fakeAddressString);

            int length = IPHEntry.AddressList.Length;

            for (int i = 0; i < length; i++)
            {
                IPHEntry.AddressList[i] = fakeAddress;
            }


            IPAddress fakeValue       = m_communications.GetIP4Address(IPHEntry);
            String    fakeValueString = fakeValue.ToString();

            bool isFakeValue = fakeValueString.Contains(fakeAddressString);

            Assert.IsTrue(isFakeValue);
        }
 public static Net.IPAddress GetIP(string hostName, bool ipv6)
 {
     Net.IPAddress address = null;
     if (!string.IsNullOrEmpty(hostName))
     {
         try
         {
             if (!Net.IPAddress.TryParse(hostName, out address))
             {
                 Net.IPHostEntry host = Net.Dns.GetHostEntry(hostName);
                 if (host != null)
                 {
                     foreach (Net.IPAddress ip in host.AddressList)
                     {
                         if (((ipv6) && (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)) ||
                             ((!ipv6) && (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)))
                         {
                             address = ip;
                             break;
                         }
                     }
                 }
             }
         }
         catch
         {
         }
     }
     return(address);
 }
 //Constructor assigns global variables and creates listener socket
 public AsynchronousSocketListener()
 {
     this.ipHostInfo = Dns.Resolve(Dns.GetHostName()); // Establish the local endpoint for the socket.
     this.ipAddress = ipHostInfo.AddressList[0]; //
     this.localEndPoint = new IPEndPoint(ipAddress, 8080); //
     this.listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Create a TCP/IP socket.
 }
Beispiel #17
0
        private string mGetLocalIP(string _IP)
        {
            string sMess = null;

            try
            {
                string hostName = System.Net.Dns.GetHostName();
                System.Net.IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(hostName);
                //ip地址列表
                System.Net.IPAddress[] addr = ipEntry.AddressList;
                for (int i = 0; i < addr.GetLength(0); i++)
                {
                    string IPAddress = addr[i].ToString();
                    if (IPAddress == _IP)
                    {
                        return(IPAddress);
                    }
                }
                sMess = "物理IP与系统设置IP不匹配,请联系系统管理员";
                MyPublic.gWriteLog(MyPublic.g_LogErr, m_sClsName, "mGetLocalIP", sMess);
                OnDisCmdMess(1, sMess);
                return(null);
            }
            catch (System.Exception ex)
            {
                sMess = ex.Message.ToString();
                MyPublic.gWriteLog(MyPublic.g_LogErr, m_sClsName, "mGetLocalIP", sMess);
                return(null);
            }
        }
Beispiel #18
0
        // GetHostIpAddress returns the IP address of the local host.
        public static string GetHostIpAddress()
        {
            if (SystemInfo.operatingSystem.Contains("Mac"))
            {
                foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
                {
                    if (ni.Name == "en0")
                    {
                        foreach (System.Net.NetworkInformation.UnicastIPAddressInformation item in ni.GetIPProperties().UnicastAddresses)
                        {
                            if (item.Address.AddressFamily == AddressFamily.InterNetwork)
                            {
                                return(item.Address.ToString());
                            }
                        }
                    }
                }
            }

            System.Net.IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    return(ip.ToString());
                }
            }

            throw new Exception("No network adapters with an IPv4 address in the system");
        }
Beispiel #19
0
        public static string GetMAC(ref string IP)
        {
            string MAC = null;

            try
            {
                //se agrega la ip del equipo donde se esta ejecutando
                //NOTA: la ip cambia dependiendo del adaptador wifi ò ethernet
                if (IPAddress.Parse(IP).Equals(IPAddress.Parse("192.168.0.26")) || IPAddress.Parse(IP).Equals(IPAddress.Parse("::1")))
                {
                    System.Net.IPHostEntry iPHostEntry = Dns.GetHostEntry(HttpContext.Current.Server.MachineName);

                    IP = iPHostEntry.AddressList[1].ToString();
                }

                System.Net.IPAddress ipaddress = IPAddress.Parse(IP);

                byte[] ab  = new byte[6];
                int    len = ab.Length;

                int r = SendARP((int)ipaddress.AddressFamily, 0, ab, ref len);
                MAC = BitConverter.ToString(ab, 0, 6);
            }
            catch (Exception)
            {
                MAC = null;
            }

            return(MAC);
        }
Beispiel #20
0
 public void Connect()
 {
     try
     {
         System.Net.IPHostEntry       hostEntry = System.Net.Dns.GetHostEntry(this.TimeServer);
         System.Net.IPEndPoint        endPoint  = new System.Net.IPEndPoint(hostEntry.AddressList[0], 123);
         System.Net.Sockets.UdpClient udpClient = new System.Net.Sockets.UdpClient();
         udpClient.Client.ReceiveTimeout = 3000;
         udpClient.Client.SendTimeout    = 3000;
         udpClient.Connect(endPoint);
         this.Initialize();
         udpClient.Send(this.NTPData, this.NTPData.Length);
         this.NTPData            = udpClient.Receive(ref endPoint);
         this.ReceptionTimestamp = System.DateTime.Now;
         if (!this.IsResponseValid())
         {
             throw new System.Exception("Invalid response from " + this.TimeServer);
         }
     }
     catch (System.Net.Sockets.SocketException ex)
     {
         Log.WriteError("NTPʱ¼ä»ñȡʧ°Ü£º" + ¡¡ex.Message);
         throw new System.Exception(ex.Message);
     }
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            /*验证是否登陆了系统*/
            if (Session["User_Row"] != "Admin")
            {
                Response.Write("<script>top.location.href='../404.html';</script>");
                return;
            }

            Sever_Name.Text = System.Net.Dns.GetHostName();//获取服务端计算机名称
            System.Net.IPAddress   clientIP = System.Net.IPAddress.Parse(Request.UserHostAddress);
            System.Net.IPHostEntry ihe      = System.Net.Dns.GetHostEntry(clientIP);
            Label_Name.Text = ihe.HostName;//获取客户端主机名称
            HttpRequest request = HttpContext.Current.Request;
            string      result  = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrEmpty(result))
            {
                result = Request.ServerVariables.Get("Local_Addr").ToString();
            }
            if (string.IsNullOrEmpty(result))
            {
                result = request.UserHostAddress;
            }
            if (string.IsNullOrEmpty(result))
            {
                result = "0.0.0.0";
            }
            Sever_Ip.Text       = Request.ServerVariables.Get("Local_Addr").ToString();
            Sever_YuMing.Text   = Request.ServerVariables["SERVER_NAME"].ToString();
            Sever_Lan.Text      = Request.ServerVariables["HTTP_ACCEPT_LANGUAGE"].ToString();
            Sever_DuanKou.Text  = Request.ServerVariables["SERVER_PORT"].ToString();
            Sever_IIS.Text      = Request.ServerVariables["SERVER_SOFTWARE"].ToString();
            Sever_System.Text   = HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"].ToString();
            Sever_Src.Text      = Request.ServerVariables["PATH_TRANSLATED"].ToString();
            Sever_Cpu.Text      = Environment.GetEnvironmentVariable("NUMBER_OF_PROCESSORS");
            Sever_CpuClass.Text = Environment.GetEnvironmentVariable("PROCESSOR_IDENTIFIER");

            //Sever_Time.Text = GetAspNetCpu();
            //Sever_Timee.Text = "";
        }


        //统计人数
        SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["connectionstring"].ToString());

        con.Open();
        SqlCommand com = new SqlCommand();

        com.Connection = con;
        string     Tsql = "select count(*) from Student";
        SqlCommand cmd  = new SqlCommand(Tsql, con);

        Label3.Text = cmd.ExecuteScalar().ToString();
        string     Tsql2 = "select count(*) from Teacher";
        SqlCommand cmd2  = new SqlCommand(Tsql2, con);

        Label1.Text = cmd2.ExecuteScalar().ToString();
    }
Beispiel #22
0
        Connection Connect(int _port)
        {
            // Set default parameters for the connection
            int       port    = _port;
            IPAddress address = null;

            // Connect to the server on localhost:port

            /*do
             * {
             *  Console.Write("Please enter an IP address to connect to: ");
             *  userInput = Console.ReadLine();
             * } while (!IPAddress.TryParse(userInput, out address));
             */

            #region Connection to server
            System.Net.IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
            address = ipHostInfo.AddressList[0];
            IPEndPoint localEndPoint = new IPEndPoint(address, port);

            Socket sender = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            sender.Connect(localEndPoint);
            #endregion

            // Connection should handle all of the reading, writing, and processing of a message thread
            // no connection manager for this program as we are generating the connection here
            Connection connection = new Connection(sender, manager, manager.ProcessClient);

            // When we create threads there are multiple ways to do so
            // you have already seen asynchrnous methods, this is an alternative
            Thread clientThread = new Thread(new ThreadStart(connection.Start));
            clientThread.Start();

            return(connection);
        }
Beispiel #23
0
 private static string GetIpByHostName(string hostName)
 {
     hostName = hostName.Trim();
     if (hostName == string.Empty)
     {
         return(string.Empty);
     }
     try
     {
         string IPAddress            = string.Empty;
         System.Net.IPHostEntry host = System.Net.Dns.GetHostEntry(hostName);
         foreach (System.Net.IPAddress ip in host.AddressList)
         {
             if (ip.AddressFamily == AddressFamily.InterNetwork)
             {
                 IPAddress = ip.ToString();
                 break;
             }
         }
         return(IPAddress);
     }
     catch (Exception)
     {
         return(string.Empty);
     }
 }
Beispiel #24
0
        bool ValidateHostInfo(RemoteHosts h)
        {
            try
            {
                // 1. is the supplied IR address a valid IP address or is it a host name?
                System.Net.IPAddress remoteIPAddress = null;
                if (!System.Net.IPAddress.TryParse(h.hostIPstr, out remoteIPAddress))
                {
                    // if it was not a valid ip address, perhaps it was a host name instead
                    System.Net.IPHostEntry GetIPHost = System.Net.Dns.GetHostEntry(h.hostIPstr);
                    h.hostIP = GetIPHost.AddressList[0];
                }
                else
                {
                    h.hostIP = System.Net.IPAddress.Parse(h.hostIPstr);
                }

                // 2. is the supplied host IP reachable via ping?

                h.MessageEventGenerators.OnStatusChange          += OnHostsStatusChange;
                h.MessageEventGenerators.OnGetHostName           += OnHostsRxHostName;
                h.MessageEventGenerators.OnRxValidAdminPassword  += OnValidPassword;
                h.MessageEventGenerators.OnRxValidViewerPassword += OnValidPassword;
                h.StartValidation();

//                h.StartValidation(OnHostsStatusChange, OnHostsRxHostName);
            }
            catch (Exception ex)
            {
                m_Log.Log("ValidateHostInfo ex: " + ex.Message, ErrorLog.LOG_TYPE.INFORMATIONAL);
            }
            return(true);
        }
Beispiel #25
0
        /// <summary>
        /// When new connections from NetworkTraceListeners are accepted the method adds
        /// the new client to the connected client listview.
        /// </summary>
        /// <param name="sender">Sender of the message should be a NetworkAdapter</param>
        /// <param name="e">Parameters for the event. Containing the accepted connection</param>
        /// <remarks>
        /// Marshals the call to the gui thread an then adds the new client to the
        /// connectedclient listbox.
        /// </remarks>
        void Adapter_ConnectionAccepted(
            object sender,
            ESolutions.Net.ConnectionAcceptedEventArgs e)
        {
            if (InvokeRequired)
            {
                Delegate thisMethod = new ConnectionAcceptedEventHandler(Adapter_ConnectionAccepted);

                Invoke(thisMethod, new object[] { sender, e });
            }
            else
            {
                System.Net.IPHostEntry entry = System.Net.Dns.GetHostEntry(
                    e.Connection.FarEndPoint.Address);

                String[] itemStrings = new String[] {
                    entry.HostName,
                    e.Connection.FarEndPoint.ToString(),
                    DateTime.Now.ToShortDateString() + " - " + DateTime.Now.ToLongTimeString()
                };

                ListViewItem newItem = new ListViewItem(
                    itemStrings);

                newItem.Tag = e.Connection;

                this.connectedClientsListView.Items.Add(newItem);
            }
        }
Beispiel #26
0
		void GetLocalHost (SimpleResolverEventArgs args)
		{
			//FIXME
			IPHostEntry entry = new IPHostEntry ();
			entry.HostName = "localhost";
			entry.AddressList = new IPAddress [] { IPAddress.Loopback };
			entry.Aliases = EmptyStrings;
			args.ResolverError = 0;
			args.HostEntry = entry;
			return;

/*
			List<IPEndPoint> eps = new List<IPEndPoint> ();
			foreach (NetworkInterface iface in NetworkInterface.GetAllNetworkInterfaces ()) {
				if (NetworkInterfaceType.Loopback == iface.NetworkInterfaceType)
					continue;

				foreach (IPAddress addr in iface.GetIPProperties ().DnsAddresses) {
					if (AddressFamily.InterNetworkV6 == addr.AddressFamily)
						continue;
					IPEndPoint ep = new IPEndPoint (addr, 53);
					if (eps.Contains (ep))
						continue;

					eps.Add (ep);
				}
			}
			endpoints = eps.ToArray ();
*/
		}
Beispiel #27
0
 internal IPEndPoint GetHostEndPoint()
 {
     lock (this)
     {
         if (_host == null || ServicePointManager.DnsRefreshTimeout >= 0 && (DateTime.Now - _lastUpdateTime).TotalMilliseconds > ServicePointManager.DnsRefreshTimeout)
         {
             var uriHost = _uri.Host;
             if (_uri.HostNameType == UriHostNameType.IPv6 || _uri.HostNameType == UriHostNameType.IPv4)
             {
                 if (_uri.HostNameType == UriHostNameType.IPv6)
                 {
                     // Remove square brackets
                     uriHost = uriHost.Substring(1, uriHost.Length - 2);
                 }
                 _host = new IPHostEntry();
                 _host.AddressList = new IPAddress[] { IPAddress.Parse(uriHost) };
             }
             else
             {
                 _host = Dns.GetHostEntry(uriHost);
             }
             _lastUpdateTime = DateTime.Now;
         }
         var index = ServicePointManager.EnableDnsRoundRobin ? ((uint)_index++ % _host.AddressList.Length) : _index;
         return new IPEndPoint(_host.AddressList[index], _uri.Scheme == Uri.UriSchemeHttps ? (_uri.IsDefaultPort ? 443 : _uri.Port) : _uri.Port);
     }
 }
Beispiel #28
0
        public static string NetworkGetNic(string RemoteHostName)
        {
            try
            {
                byte[] ab  = new byte[6];
                int    len = ab.Length;

                System.Net.IPHostEntry Tempaddr = null;

                //Tempaddr = (System.Net.IPHostEntry)Dns.GetHostEntry(RemoteHostName);
                Tempaddr = (System.Net.IPHostEntry)Dns.Resolve(RemoteHostName);

                //int Address = (int)Tempaddr.AddressList[0].Address;
                int Address = (int)Tempaddr.AddressList[0].Address;
                int r       = SendARP(Address, 0, ab, ref len);

                string mac = BitConverter.ToString(ab, 0, 6);

                return(mac);
            }
            catch (Exception)
            {
                return("");
            }
        }
Beispiel #29
0
        private bool downloadNewFile(UpdateType ut, string curVersion, ref bool HasUpdate)
        {
            try
            {
                //قابل دسترس است
                System.Net.IPHostEntry objIPHE = System.Net.Dns.GetHostEntry("www.nwdic.com");
            }
            catch (Exception)
            {
                lblMessage.Text = " امکان بروز رسانی به دلیل عدم  اتصال به اینترنت وجود ندارد ...";
                txtMessage.Text = string.Empty;
                return(false);
            }
            switch (downloadFile(ut))
            {
            case ResultUpdate.exit:
                resultByInternet = ResultUpdate.exit;
                return(false);

            case ResultUpdate.uptodate:
                return(true);

            case ResultUpdate.update:
                return(HasDownloaded(ut, curVersion, ref HasUpdate));

            case ResultUpdate.fatal:
                resultByInternet = ResultUpdate.fatal;
                return(false);
            }
            return(false);
        }
        private static NameValueCollection getSessionData()
        {
            NameValueCollection result = new NameValueCollection();
            HttpContext         ctx    = HttpContext.Current;

            try
            {
                result.Add("Caller Info:", "Attempting to determine caller Info");
                StringBuilder sb           = new StringBuilder();
                String        strHostName2 = Dns.GetHostName();
                Console.WriteLine("Local Machine's Host Name: " + strHostName2);
                // Then using host name, get the IP address list..
                IPHostEntry ipEntry = Dns.GetHostByName(strHostName2);
                IPAddress[] addr    = ipEntry.AddressList;
                string      ip      = addr[0].ToString();

                result.Add("Request.UserHostAddress", ip);

                if (ip.Substring(0, 4) == "10.0")
                {
                    System.Net.IPHostEntry host = null;
                    String strHostName          = Dns.GetHostName();
                    host = Dns.GetHostEntry(strHostName);
                    string strComputerName = host.HostName;
                    result.Add("MachineName", strComputerName);
                }
            }
            catch (Exception ex)
            {
            }

            return(result);
        }
        /// <summary>
        /// Creates a proxy server from the server in the given connection string using the default construction parameters and starts the proxy
        /// </summary>
        /// <param name="connectionString">Connection string to the server to proxy</param>
        /// <param name="newConnectionString">Connection string to the proxy server (using the same parameters as <paramref name="connectionString"/>)</param>
        /// <returns>The created and started proxy server</returns>
        public static ProxyServer CreateAndStartProxy(string connectionString, out string newConnectionString)
        {
            // Build builders
            SqlConnectionStringBuilder connStringbuilder = new SqlConnectionStringBuilder(connectionString);
            DataSourceBuilder          dataSourceBuilder = new DataSourceBuilder(connStringbuilder.DataSource);

            // Setup proxy
            Task <System.Net.IPHostEntry> ipEntryTask = Dns.GetHostEntryAsync(dataSourceBuilder.ServerName);

            ipEntryTask.Wait();
            System.Net.IPHostEntry serverIpEntry = ipEntryTask.Result;

            ProxyServer proxy = new ProxyServer();

            proxy.RemoteEndpoint = new IPEndPoint(serverIpEntry.AddressList[0], dataSourceBuilder.Port ?? 1433);
            proxy.Start();

            // Switch connection over
            dataSourceBuilder.Protocol   = "tcp";
            dataSourceBuilder.ServerName = "127.0.0.1";
            dataSourceBuilder.Port       = proxy.LocalPort;
            connStringbuilder.DataSource = dataSourceBuilder.ToString();
            connStringbuilder.Remove("Network Library");

            newConnectionString = connStringbuilder.ToString();
            return(proxy);
        }
        /// <summary>
        /// Initializes the socket
        /// </summary>`
        public void init(int offset, string ipAddress)
        {
            socketType = SocketType.Stream;
            protocolType = ProtocolType.Tcp;
            //addressFamily = AddressFamily.InterNetwork;
            addressFamily = AddressFamily.InterNetwork;
            try
            {
                ipEntry = Dns.GetHostEntry(Dns.GetHostName());
                IPAddress[] addr = ipEntry.AddressList;
                //endpoint = new IPEndPoint(addr[0], port);
                for (int i = 0; i < addr.Length; i++)
                {
                    Console.WriteLine("IP Address {0}: {1} ", i, addr[i].ToString());
                }
                if (ipAddress == "")
                {
                    address = addr[addr.Length - offset];
                }
                else
                {
                    address = IPAddress.Parse(ipAddress);
                }
                Console.WriteLine("Using the Address {0}: {1}", address.ToString(), port);
                endpoint = new IPEndPoint(address, port);
            }
            catch (SocketException ex)
            {
                System.Console.WriteLine(ex.Message);
            }
            createSocket();

        }
 public bool bComprobarFuente() 
 {
     sQuery = "SELECT cod_usr FROM tabm_sgusuario WHERE  ipdir_usr = '******' ";
     alResultados = csFunciones.alConsultar(sQuery);
     if (alResultados.Count == 0)
     {
         bool bBandera = false;
         ipHostName = Dns.GetHostEntry(Dns.GetHostName());
         foreach (IPAddress ip in ipHostName.AddressList)
         {
             sQuery = "SELECT cod_usr FROM tabm_sgusuario WHERE ipdir_usr = \"" + ip.ToString() + "\"";
             alResultados = csFunciones.alConsultar(sQuery);
             if (alResultados.Count != 0)
             {
                 bBandera = true;
                 break;
             }
             else
             {
                 bBandera = false;
             }     
         }
         if (bBandera == false) { MessageBox.Show("La dirección del equipo no corresponde con la cuenta", "Hotel San Carlos"); }
         return bBandera;
     }
     else 
     {
         return true;
     }
 }
Beispiel #34
0
        public string GetMAC(ref string IP, ref string HttpContext)
        {
            string MAC = null;

            try
            {
                if (IPAddress.Parse(IP).Equals(IPAddress.Parse("127.0.0.1")))
                {
                    System.Net.IPHostEntry iPHostEntry = Dns.GetHostEntry(HttpContext);//////

                    IP = iPHostEntry.AddressList[1].ToString();
                }

                System.Net.IPAddress ipAddress = IPAddress.Parse(IP);

                byte[] ab  = new byte[6];
                int    len = ab.Length;

                int r = SendARP((int)ipAddress.Address, 0, ab, ref len);
                MAC = BitConverter.ToString(ab, 0, 6);
            }
            catch (Exception)
            {
                MAC = null;
            }

            return(MAC);
        }
        public void StartListening()
        {
            byte[] bytes = new Byte[BufferSize];

            IPHostEntry ipHostInfo = new IPHostEntry();
            ipHostInfo.AddressList = new IPAddress[] { _serverIP};
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPEndPoint remoteEndPoint = new IPEndPoint(ipAddress, port);
            // Create a TCP/IP socket.
            Socket listener = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream, ProtocolType.Tcp);

            try
            {
                listener.BeginConnect(remoteEndPoint, new AsyncCallback(ConnectCallback), listener);
                connectDone.WaitOne();

                // receive data
                receiveDone.Reset();
                Receive(listener);
                receiveDone.WaitOne();

                Console.WriteLine("Disconnecting from feed");

                listener.Shutdown(SocketShutdown.Both);
                listener.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("Feed Error " + e.ToString());
            }
        }
Beispiel #36
0
        public static IPAddress GetLocalIPAddress()
        {
            if (_localIP != null)
            {
                return(_localIP);
            }

            string ip = ConfigurationSettings.AppSettings["LocalIP"];

            if (ip != null)
            {
                return(IPAddress.Parse(ip));
            }

            System.Net.IPHostEntry hostEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());
            if (hostEntry.AddressList != null)
            {
                foreach (System.Net.IPAddress addr in hostEntry.AddressList)
                {
                    if (addr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        return(addr);
                    }
                }
            }
            return(System.Net.IPAddress.Parse("127.0.0.1"));
        }
 public HostNameCompletedEventArgs( IPAddress ipAddress, IPHostEntry hostEntry )
 {
     if( ipAddress == null ) throw new NullReferenceException( "ipAddress" );
     if( hostEntry == null ) throw new NullReferenceException( "hostEntry" );
     _ipAddress = ipAddress;
     _hostEntry = hostEntry;
 }
Beispiel #38
0
		private static IPHostEntry hostent_to_IPHostEntry(string h_name, string[] h_aliases, string[] h_addrlist) 
		{
			IPHostEntry he = new IPHostEntry();
			ArrayList addrlist = new ArrayList();

			he.HostName = h_name;
			he.Aliases = h_aliases;
			for(int i=0; i<h_addrlist.Length; i++) {
				try {
					IPAddress newAddress = IPAddress.Parse(h_addrlist[i]);

					if( (Socket.SupportsIPv6 && newAddress.AddressFamily == AddressFamily.InterNetworkV6) ||
					    (Socket.SupportsIPv4 && newAddress.AddressFamily == AddressFamily.InterNetwork) )
						addrlist.Add(newAddress);
				} catch (ArgumentNullException) {
					/* Ignore this, as the
					 * internal call might have
					 * left some blank entries at
					 * the end of the array
					 */
				}
			}

			if(addrlist.Count == 0)
				throw new SocketException(11001);

			he.AddressList = addrlist.ToArray(typeof(IPAddress)) as IPAddress[];
			return he;
		}
Beispiel #39
0
        private void StartNewTCPConnection(Uri connection)
        {
            ConnectionInfo info = new ConnectionInfo();

            info.Addr = connection.DnsSafeHost;
            info.Port = connection.Port;

            System.Net.IPHostEntry hostEntry = System.Net.Dns.GetHostEntry(info.Addr);
            System.Net.IPAddress   ipAddress = System.Net.Dns.GetHostEntry(hostEntry.HostName).AddressList[0];
            IPEndPoint             endpoint  = new IPEndPoint(ipAddress, info.Port);

            foreach (MessageChannelAcceptor acceptor in channelAcceptorList)
            {
                if (!acceptor.IsClosed && acceptor.LocalEndPoint != null && acceptor.LocalEndPoint.Equals(endpoint))
                {
                    //We are trying to connect to our own acceptor!
                    return;
                }
            }

            TCPMessageChannel channel = new TCPMessageChannel(info);

            if (log.IsDebugEnabled)
            {
                log.Debug("Connected from " + channel.InternalSocket.LocalEndPoint +
                          " to " + channel.InternalSocket.RemoteEndPoint);
                log.Debug("Timeouts in mls: Receive " + channel.InternalSocket.ReceiveTimeout +
                          ", Send " + channel.InternalSocket.SendTimeout);
            }

            AddChannel(channel);
        }
Beispiel #40
0
		static void GetLocalHost (SimpleResolverEventArgs args)
		{
			//FIXME
			IPHostEntry entry = new IPHostEntry ();
			entry.HostName = "localhost";
			entry.Aliases = EmptyStrings;
			args.ResolverError = 0;
			args.HostEntry = entry;

			bool ipv4 = Socket.OSSupportsIPv4;
			bool ipv6 = Socket.OSSupportsIPv6;
			List<IPAddress> ips = new List<IPAddress> ();
			if (ipv4)
				ips.Add (IPAddress.Loopback);
			if (ipv6)
				ips.Add (IPAddress.IPv6Loopback);

			foreach (NetworkInterface iface in NetworkInterface.GetAllNetworkInterfaces ()) {
				if (NetworkInterfaceType.Loopback == iface.NetworkInterfaceType)
					continue;

				foreach (UnicastIPAddressInformation info in iface.GetIPProperties ().UnicastAddresses) {
					IPAddress addr = info.Address;
					AddressFamily family = addr.AddressFamily;
					if ((ipv6 && AddressFamily.InterNetworkV6 == family) ||
						(ipv4 && AddressFamily.InterNetwork == family)) {
						ips.Add (addr);
					}
				}
			}
			entry.AddressList = ips.ToArray ();
		}
 private void SetHostName(IPHostEntry host)
 {
     if (ListView != null && ListView.InvokeRequired)
         ListView.Invoke(new SetHostNameDelegate(SetHostName), host);
     else if (host != null && !host.HostName.Equals(SubItems[0].Text))
         Hostname = host.HostName;
 }
Beispiel #42
0
    byte[] sendData    = new byte[1024]; //用于缓存客户端所发送的信息,通过socket传递的信息必须为字节数组

    //程序初始化
    public void Init(string IP, int port)
    {
        //初始化命令字符串
        returnStr  = "";
        receiveStr = "";

        //获取IP
        string hostName = System.Net.Dns.GetHostName();

        System.Net.IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(hostName);

        //ip地址列表
        System.Net.IPAddress[] addr = ipEntry.AddressList;

        //建立服务器端socket
        IPEndPoint ipep = new IPEndPoint(/*addr[0]*/ IPAddress.Parse(IP), port);//本机预使用的IP和端口

        severSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        severSocket.Bind(ipep); //绑定
        severSocket.Listen(10); //监听
        //建立服务器端socket end


        //新建线程
        thread = new Thread(new ThreadStart(GoClient));
        //启动线程
        thread.Start();
    }
Beispiel #43
0
        /// <summary>
        /// The adapter received a package from a NetworkTraceListener.
        /// </summary>
        /// <param name="sender">Adapter sending the event.</param>
        /// <param name="e">Parameters for this event including the connection that was used for transmission.</param>
        /// <remarks>
        /// The call is marshaled to the gui thread and then adds the message to the message window.
        /// </remarks>
        void Adapter_PackageReceived(
            object sender,
            ESolutions.Net.PackageReceivedEventArgs e)
        {
            if (InvokeRequired)
            {
                Invoke(new ESolutions.Net.PackageReceivedEventHandler(Adapter_PackageReceived), new object[] { sender, e });
            }
            else
            {
                System.Net.IPHostEntry entry = System.Net.Dns.GetHostEntry(
                    e.Connection.FarEndPoint.Address);

                String[] values = new String[] {
                    e.Package.Payload,
                    entry.HostName,
                    e.Connection.FarEndPoint.ToString(),
                    DateTime.Now.ToShortDateString() + " - " + DateTime.Now.ToLongTimeString()
                };

                ListViewItem newItem = new ListViewItem(values);

                messagesListView.Items.Insert(
                    0,
                    newItem);
            }
        }
Beispiel #44
0
        /// <summary>  
        /// SendArp获取MAC地址  
        /// </summary>  
        /// <returns></returns>  
        public string GetMacAddressBySendARP()
        {
            StringBuilder strReturn = new StringBuilder();
            try
            {
                System.Net.IPHostEntry Tempaddr = (System.Net.IPHostEntry)Dns.GetHostByName(Dns.GetHostName());
                System.Net.IPAddress[] TempAd = Tempaddr.AddressList;
                Int32 remote = (int)TempAd[0].Address;
                Int64 macinfo = new Int64();
                Int32 length = 6;
                SendARP(remote, 0, ref macinfo, ref length);

                string temp = System.Convert.ToString(macinfo, 16).PadLeft(12, '0').ToUpper();

                int x = 12;
                for (int i = 0; i < 6; i++)
                {
                    if (i == 5) { strReturn.Append(temp.Substring(x - 2, 2)); }
                    else { strReturn.Append(temp.Substring(x - 2, 2) + "-"); }
                    x -= 2;
                }

                return strReturn.ToString();
            }
            catch
            {
                return "";
            }
        } 
 private IPEndPoint GetEndPoint(string address, int port)
 {
     var host = new IPHostEntry();
     host.HostName = address;
     var ipAddress = Dns.GetHostAddresses(address).First();
     return new IPEndPoint(ipAddress, port);
 }
Beispiel #46
0
        public static string getIp()
        {
            System.Net.IPHostEntry myEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());
            string ipAddress = myEntry.AddressList[0].ToString();

            return(ipAddress);
        }
Beispiel #47
0
 public SocketClient(int _port, int _bufferSize)
 {
     port = _port;
     bufferSize = _bufferSize;
     ipHostInfo = Dns.Resolve(Dns.GetHostName());
     address = ipHostInfo.AddressList[0];
     remoteEnpoint = new IPEndPoint(address, port);
 }
Beispiel #48
0
 //end event-------------------------------------
 public SocketClient(string _host, int _port, int _bufferSize)
 {
     host = _host;
     port = _port;
     bufferSize = _bufferSize;
     ipHostInfo = Dns.Resolve(host);
     address = ipHostInfo.AddressList[0];
     remoteEnpoint = new IPEndPoint(address, port);
 }
 public ArrayList alBuscarUsuarios()
 {
     ipHostName = Dns.GetHostEntry(Dns.GetHostName()); 
     foreach (IPAddress ip in ipHostName.AddressList)
     {
         alResultados = D_Inicio.alBuscarUsuarios();
     }
     return alResultados;
 }
 internal NetworkDictionaryItem( IPAddress ipAddress, PingReply pingReply, PhysicalAddress macAddress, IPHostEntry hostEntry, IOS os )
 {
     _ipAddress = ipAddress;
     _pingReply = pingReply;
     _macAddress = macAddress;
     _hostEntry = hostEntry;
     _os = os;
     _ports = new ConcurrentDictionary<ushort,ushort>();
 }
 public Socket(Config config)
 {
     this.host = config.Host;
     this.port = config.Port;
     this.backlog = config.Backlog;
     host_entry = Dns.GetHostEntry(host);
     ip_address = host_entry.AddressList[0];
     end_point = new IPEndPoint(ip_address, port);
 }
Beispiel #52
0
 public IPHostEntry Lookup(string address)
 {
     IPHostEntry hostEntry = new IPHostEntry();
     try {
         IPAddress hostIPAddress = IPAddress.Parse(address);
         hostEntry = Dns.GetHostEntry(hostIPAddress);
     } catch { }
     return hostEntry;
 }
Beispiel #53
0
 /// <summary>
 /// Contructor init server's info, Host name is Server's address (default)
 /// </summary>
 /// <param name="_port">Port of app server</param>
 /// <param name="_bufferSize">Size of buffer send, receive</param>
 /// <param name="_backlog">Number pending connection queue</param>
 public SocketServer(int _port, int _buffeerSize, int _backlog)
 {
     backlog = _backlog;
     port = _port;
     bufferSize = _buffeerSize;
     ipHostInfo = Dns.Resolve(Dns.GetHostName());
     ipAddress = ipHostInfo.AddressList[0];
     localEndPoint = new IPEndPoint(ipAddress, port);
 }
Beispiel #54
0
		private IPHostEntry GetHostEntry(string hostname) {
			IPAddress address;
			if (IPAddress.TryParse(hostname, out address)) {
				IPHostEntry entry = new IPHostEntry();
				entry.AddressList = new IPAddress[] { address };
				return entry;
			}
			return Dns.GetHostEntry(hostname);
		}
        public AsynchronousTcpSocket()
        {
            _localHostEntry = Dns.GetHostEntry(Dns.GetHostName());
            _localIpAddress = _localHostEntry.AddressList[0];
            _localEndpoint = new IPEndPoint(_localIpAddress, Defaults.TCP_PORT);

            _socket = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream, ProtocolType.Tcp);
        }
Beispiel #56
0
        public void Startscan(Object state)
        {
            string ip = state.ToString();
            int list = 0;
            threadnum++;
            if (endscan == false)
            {
                    try
                    {
                        IPHostEntry HostA = new IPHostEntry();
                        HostA = Dns.Resolve(ip);
                        string ipt = HostA.HostName.ToString();

                        TcpClient tcp = new TcpClient();
                        tcp.Connect(ipt, int.Parse(textBox2.Text));

                        //list = portlist.Items.Add(port.ToString() + "端口开放" ,false);
                        MyInvoke mi = new MyInvoke(UpdateUIport);
                        this.BeginInvoke(mi, new object[] { ip + "开放" });
                        list = list + 1;

                    }
                    catch
                    {
                        //portlist1.Items.Add(port.ToString() + "端口无法连接");
                        MyInvoke mi = new MyInvoke(UpdateUI);
                        this.BeginInvoke(mi, new object[] { ip + "无法连接" });

                    }
                    finally
                    {
                        Thread.Sleep(0);
                        //loglist.Items.Add("结束线程" + port.ToString());
                        //委托调用
                        MyInvoke mi = new MyInvoke(UpdateUI2);
                        this.BeginInvoke(mi, new object[] { "结束线程" +ip });

                        asyncOpsAreDone.Close();
                        // label5.Text = portnum.ToString();

                        MyInvoke mi3 = new MyInvoke(UpdateUI3);
                        this.BeginInvoke(mi3, new object[] { list.ToString()});
                    }

            }

            if (endscan == true || ip==textBox1.Text)
            {
                // button1.Enabled = true;
                // button2.Enabled = false;
                asyncOpsAreDone.Close();
                MyInvoke mi4 = new MyInvoke(UpdateUI4);
                this.BeginInvoke(mi4, new object[] { "344" });

            }
        }
Beispiel #57
0
 //public event
 //end event------------------------
 /// <summary>
 /// Contructor init server's info
 /// </summary>
 /// <param name="_host">Host name or Ip adress</param>
 /// <param name="_port">Port of app server</param>
 /// <param name="_bufferSize">Size of buffer send, receive</param>
 /// <param name="_backlog">Number pending connection queue</param>
 public SocketServer(string _host, int _port, int _bufferSize, int _backlog)
 {
     backlog = _backlog;
     host = _host;
     port = _port;
     bufferSize = _bufferSize;
     ipHostInfo = Dns.Resolve(host);
     ipAddress = ipHostInfo.AddressList[0];
     localEndPoint = new IPEndPoint(ipAddress, port);
 }
        private void btnStart_Click_1(object sender, RoutedEventArgs e)
        {
            ipHost = Dns.GetHostEntry("localhost");
            ipAddr = ipHost.AddressList[0];

            ipEndPoint = new IPEndPoint(ipAddr, Convert.ToInt32(tbxPort.Text));
            sender_1 = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            bytes = new byte[1024];
            sender_1.Connect(ipEndPoint);
        }
Beispiel #59
0
 private void SetHost(IPHostEntry hostEntry)
 {
     _host =
         hostEntry.AddressList == null || hostEntry.AddressList.FirstOrDefault() == null ?
             string.IsNullOrEmpty(hostEntry.HostName) ?
                 hostEntry.Aliases == null || string.IsNullOrEmpty(hostEntry.Aliases.FirstOrDefault()) ?
                     null : hostEntry.Aliases.FirstOrDefault()
             : hostEntry.HostName
         : hostEntry.AddressList.FirstOrDefault().MapToIPv6().ToString();
 }
Beispiel #60
0
 public static string GetIPString(IPHostEntry iphostentry)
 {
     string IPString = "";
     string Divider = "";
     foreach (IPAddress IP in iphostentry.AddressList)
     {
         IPString += Divider + IP.ToString();
         Divider = ", ";
     }
     return IPString;
 }