/// <summary> /// 判断指定端口号是否被占用 /// </summary> /// <param name="port"></param> /// <returns></returns> internal static Boolean IsPortUsed(Int32 port) { Boolean result = false; try { System.Net.NetworkInformation.IPGlobalProperties iproperties = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties(); System.Net.IPEndPoint[] ipEndPoints = iproperties.GetActiveTcpListeners(); //System.Net.NetworkInformation.TcpConnectionInformation[] conns = iproperties.GetActiveTcpConnections(); //foreach (var con in conns) foreach (var con in ipEndPoints) { // if (con.LocalEndPoint.Port == port) if (con.Port == port) { result = true; break; } } } catch (Exception) { } return(result); }
internal static Boolean IsPortOccupedFun2(Int32 port, IpAndPort m_PortList) { System.Net.NetworkInformation.IPGlobalProperties iproperties = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties(); System.Net.IPEndPoint[] ipEndPoints = iproperties.GetActiveTcpListeners(); if (!PortList.Contains(m_PortList.port)) { PortList.Add(m_PortList.port); IpAndPortList.Add(m_PortList); } foreach (var item in ipEndPoints) { if (item.Port == Convert.ToInt32(m_PortList.port)) { foreach (IpAndPort ipPort in IpAndPortList) { if (ipPort.ip.Equals(m_PortList.ip) && ipPort.port.Equals(m_PortList.port)) { return(false); } } return(true); } } return(false); }
internal static Boolean IsPortOccupedFun2(params Int32[] ports) { Boolean result = false; try { System.Net.NetworkInformation.IPGlobalProperties iproperties = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties(); System.Net.IPEndPoint[] ipEndPoints = iproperties.GetActiveTcpListeners(); foreach (var item in ipEndPoints) { foreach (var port in ports) { if (item.Port == port) { result = true; return(true); } } } } catch (Exception ex) { LogHelper.LogFilter(true, ex.StackTrace); } return(result); }
public static string StartServer() { string strError = null; try { //清空原来所有实时数据 ClearRedisServer(); //数据下派 子线程 Thread threadSend = new Thread(DownScheduleHandler); threadSend.Start(); //异常日志写入子线程 Thread threadErrorInsert = new Thread(db.InsertErrorInfo); threadErrorInsert.Start(); //端口监听并接受数据 serverListen = new TcpListener(IPAddress.Any, SERVER_PORT_NUMBER); serverListen.Start(); keepListening = true; while (keepListening) { TcpClient serverReceive = serverListen.AcceptTcpClient(); NetStructure.NormalDataStruct dataInfo = new NetStructure.NormalDataStruct(); dataInfo.stream = serverReceive.GetStream(); dataInfo.IpAddress = ((IPEndPoint)serverReceive.Client.RemoteEndPoint).Address.ToString(); //子线程接收和处理信息 Thread ThreadHanler = new Thread(new ParameterizedThreadStart(ThreadHandler)); ThreadHanler.Start(dataInfo); } //ClientHanlderProductInfo info = new ClientHanlderProductInfo(); //info.HandlerTest(); } catch (SocketException socketEx) { db.InsertErrorInfo(enumSystemErrorCode.TcpListenerException, socketEx, "监听异常", null); strError = socketEx.Message; System.Net.NetworkInformation.IPGlobalProperties ipProperties = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties(); IPEndPoint[] ipEndPoints = ipProperties.GetActiveTcpListeners(); foreach (IPEndPoint endPoint in ipEndPoints) { if (endPoint.Port == SERVER_PORT_NUMBER) { keepListening = true; strError = "操作成功"; break; } } } catch (Exception ex) { strError = ex.Message; db.InsertErrorInfo(enumSystemErrorCode.TcpListenerException, ex, "监听异常", null); } return(strError); }
public static int FindOpenPort(ProtocolType type, int start = 30000, bool even = true) { //Only Tcp or Udp :) if (type != ProtocolType.Udp && type != ProtocolType.Tcp) { return(-1); } int port = start; //Get the IpGlobalProperties System.Net.NetworkInformation.IPGlobalProperties ipGlobalProperties = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties(); //Can't get any information if (ipGlobalProperties == null) { return(port = -1); } //We need endpoints to ensure the ports we want are not in use IEnumerable <IPEndPoint> listeners = null; //Get the endpoints if (type == ProtocolType.Udp) { listeners = ipGlobalProperties.GetActiveUdpListeners(); } else if (type == ProtocolType.Tcp) { listeners = ipGlobalProperties.GetActiveTcpListeners(); } //Enumerate the ones that are = or > then port and increase port along the way foreach (IPEndPoint ep in listeners.Where(ep => ep.Port >= port)) { if (port == ep.Port) { port++; } else if (ep.Port == port + 1) { port += 2; } } int remainder = port % 2; //If we only want even ports and we found an even one return it if (even && remainder == 0 || !even && remainder != 0) { return(port); } //We found an even and we wanted odd or vice versa return(++port); }
/// <summary> /// 是否空闲端口 /// </summary> /// <param name="port"></param> /// <returns></returns> public static bool IsValidPort(int port) { System.Net.NetworkInformation.IPGlobalProperties iproperties = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties(); System.Net.IPEndPoint[] ipEndPoints = iproperties.GetActiveTcpListeners(); foreach (var item in ipEndPoints) { if (item.Port == port) { return(false); } } return(true); }
internal static Boolean IsPortOccuped(Int32 port) { System.Net.NetworkInformation.IPGlobalProperties iproperties = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties(); System.Net.IPEndPoint[] ipEndPoints = iproperties.GetActiveTcpListeners(); foreach (var item in ipEndPoints) { if (item.Port == port) { return(true); } } return(false); }
public static string StartServer() { string strError = null; try { //端口监听并接受数据 serverListen = new TcpListener(IPAddress.Any, SERVER_PORT_NUMBER); serverListen.Start(); keepListening = true; while (keepListening) { Console.WriteLine("开始监听:" + DateTime.Now.ToString()); TcpClient serverReceive = serverListen.AcceptTcpClient(); string clientIP = serverReceive.Client.RemoteEndPoint.ToString(); clientIP = clientIP.Substring(0, clientIP.IndexOf(':')); Console.WriteLine("连接成功==:" + DateTime.Now.ToString()); NetworkStream ns = serverReceive.GetStream(); string strIP = ((IPEndPoint)serverReceive.Client.RemoteEndPoint).Address.ToString(); ReceiveByProtocol(ns, strIP); } } catch (SocketException socketEx) { strError = socketEx.Message; System.Net.NetworkInformation.IPGlobalProperties ipProperties = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties(); IPEndPoint[] ipEndPoints = ipProperties.GetActiveTcpListeners(); foreach (IPEndPoint endPoint in ipEndPoints) { if (endPoint.Port == SERVER_PORT_NUMBER) { keepListening = true; strError = "操作成功"; break; } } } catch (Exception ex) { strError = ex.Message; } return(strError); }
/// <summary> /// Source: http://stackoverflow.com/questions/570098/in-c-how-to-check-if-a-tcp-port-is-available /// </summary> /// <param name="port">The TCP-Port to check for</param> /// <returns>true if unused</returns> public static bool TcpPortIsUnused(int port) { // Evaluate current system tcp connections. This is the same information provided // by the netstat command line application, just in .Net strongly-typed object // form. We will look through the list, and if our port we would like to use // in our TcpClient is occupied, we will set isAvailable to false. System.Net.NetworkInformation.IPGlobalProperties ipGlobalProperties = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties(); IPEndPoint[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpListeners(); foreach (IPEndPoint endpoint in tcpConnInfoArray) { if (endpoint.Port == port) { return(false); } } return(true); }
private void ScanPorts(string host) { rtbOutput.Clear(); try { System.Net.NetworkInformation.IPGlobalProperties properties = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties(); IPEndPoint[] tcpEndPoints = properties.GetActiveTcpListeners(); System.Net.NetworkInformation.TcpConnectionInformation[] tcpConnections = properties.GetActiveTcpConnections(); tcpConnections.ToList().ForEach(p => { rtbOutput.Text += $"Local = [{p.LocalEndPoint.Address}:{p.LocalEndPoint.Port}] Remote = [{p.RemoteEndPoint.Address}:{p.RemoteEndPoint.Port}] State = [{p.State}]\n"; }); } catch (Exception ex) { PrintSomeLogInfo(ex.Message); } }
public Form1() { InitializeComponent(); System.Net.NetworkInformation.IPGlobalProperties ipgp = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties(); System.Net.IPEndPoint[] tcplist = ipgp.GetActiveTcpListeners(); IPEndPoint iep = tcplist.FirstOrDefault(o => o.Port == 139); if (iep != null) { IPAddress ipa = IPAddress.Parse(iep.Address.ToString()); strFormText = this.Text + " " + ipa.ToString(); _server = new TcpListener(ipa, 8080); } else { _server = new TcpListener(8080); strFormText = this.Text; } }
public static string StartServer(int userId) { string strError = null; try { serverListen = new TcpListener(IPAddress.Any, SERVER_PORT_NUMBER); serverListen.Start(); keepListening = true; Thread socketThread = new Thread(Listening); socketThread.Start(); } catch (SocketException socketEx) { System.Net.NetworkInformation.IPGlobalProperties ipProperties = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties(); IPEndPoint[] ipEndPoints = ipProperties.GetActiveTcpListeners(); foreach (IPEndPoint endPoint in ipEndPoints) { if (endPoint.Port == SERVER_PORT_NUMBER) { keepListening = true; strError = "操作成功"; break; } } if (!keepListening) { strError = socketEx.Message; db.RecordErrorInfo(enumSystemErrorCode.TcpListenerException, socketEx, "监听异常", null, userId); } } catch (Exception ex) { strError = ex.Message; db.RecordErrorInfo(enumSystemErrorCode.TcpListenerException, ex, "监听异常", null, userId); } return(strError); }
/// <summary> /// 判断指定端口号是否被占用 /// </summary> /// <param name="port"></param> /// <returns></returns> internal static Boolean isPortOccuped(Int32 port) { Boolean result = false; try { System.Net.NetworkInformation.IPGlobalProperties iproperties = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties(); System.Net.IPEndPoint[] ipEndPoints = iproperties.GetActiveTcpListeners(); foreach (var item in ipEndPoints) { if (item.Port == port) { result = true; break; } } } catch (Exception) { } return(result); }
/// <summary> /// 判断指定端口号是否被占用 占用返回true /// </summary> /// <param name="port"></param> /// <returns></returns> internal static bool IsPort(Int32 port) { bool result = false; try { System.Net.NetworkInformation.IPGlobalProperties iproperties = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties(); System.Net.IPEndPoint[] ipEndPoints = iproperties.GetActiveTcpListeners(); foreach (var item in ipEndPoints) { if (item.Port == port) { result = true; break; } } } catch (Exception ex) { Console.WriteLine(ex.Message); } return(result); }
public static int FindOpenPort(System.Net.Sockets.ProtocolType type, int start = 30000, bool even = true) { //Only Tcp or Udp :) if (type != System.Net.Sockets.ProtocolType.Udp && type != System.Net.Sockets.ProtocolType.Tcp) { return(-1); } int port = start; //Get the IpGlobalProperties System.Net.NetworkInformation.IPGlobalProperties ipGlobalProperties = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties(); //Can't get any information if (ipGlobalProperties == null) { return(port = -1); } //We need endpoints to ensure the ports we want are not in use System.Collections.Generic.IEnumerable <System.Net.IPEndPoint> listeners = System.Linq.Enumerable.Empty <System.Net.IPEndPoint>(); switch (type) { case System.Net.Sockets.ProtocolType.Udp: listeners = ipGlobalProperties.GetActiveUdpListeners(); break; case System.Net.Sockets.ProtocolType.Tcp: listeners = ipGlobalProperties.GetActiveTcpListeners(); break; default: throw new System.NotSupportedException("The given ProtocolType is not supported"); } //Enumerate the ones that are = or > then port and increase port along the way foreach (System.Net.IPEndPoint ep in listeners) { if (ep.Port <= port) { continue; } if (port == ep.Port) { port++; } else if (ep.Port == port + 1) { port += 2; } } //If we only want even ports and we found an even one return it if (even && Binary.IsEven(port) || false == even && Binary.IsOdd(port)) { return(port); } //We found an even and we wanted odd or vice versa return(++port); }
public static int FindOpenPort(System.Net.Sockets.ProtocolType type, int start = 30000, bool even = true, System.Net.IPAddress localIp = null) { //As IP would imply either or Only Tcp or Udp please. if (type != System.Net.Sockets.ProtocolType.Udp && type != System.Net.Sockets.ProtocolType.Tcp) { return(-1); } //Start at the given port number int port = start; //Get the IpGlobalProperties System.Net.NetworkInformation.IPGlobalProperties ipGlobalProperties = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties(); //Can't get any information if (ipGlobalProperties == null) { return(port = -1); } //We need endpoints to ensure the ports we want are not in use System.Collections.Generic.IEnumerable <System.Net.IPEndPoint> listeners;// = System.Linq.Enumerable.Empty<System.Net.IPEndPoint>(); //Try to get the active listeners of the type of protocol specified. try { //Determine if Udp or Tcp listeners are being checked. switch (type) { case System.Net.Sockets.ProtocolType.Udp: listeners = ipGlobalProperties.GetActiveUdpListeners(); break; case System.Net.Sockets.ProtocolType.Tcp: listeners = ipGlobalProperties.GetActiveTcpListeners(); break; default: throw new System.NotSupportedException("The given ProtocolType is not supported"); } } catch (System.NotImplementedException) { //When the method is not implemented then use ProbeForOpenPorts. return(ProbeForOpenPort(type, start, even, localIp)); } //Enumerate the listeners that are == then port and increase port along the way foreach (System.Net.IPEndPoint ep in listeners) { //If the port is less than the port in question continue. if (ep.Port < port) { continue; } //Ensure correctly filtering to the given IP if (localIp != null && ep.Address != localIp) { continue; } if (port == ep.Port) { port++; //Increment the port } else if (ep.Port == port + 1) { port += 2; //Increment by 2, probably not needed. Trying to find a port pair is beyond the scope of this function. } //Only look until the max port is reached. if (port > ushort.MaxValue) { return(-1); } } //If we only want even ports and we found an even one return it if (even && Binary.IsEven(port) || false == even && Binary.IsOdd(port)) { return(port); } //We found an even and we wanted odd or vice versa //Only increase the port if not ushort.MaxValue return(port == ushort.MaxValue ? port : ++port); }
/// <summary> /// Attempt to sign into the system with the provided username and password. Note that a database connection must already have been established at this point. /// </summary> /// <param name="Username">The case insensitive username.</param> /// <param name="Password">The case insensitive password.</param> /// <returns>Returns true if the user details are correct and could be retrieved, otherwise returns false.</returns> /// <remarks>Created: Theo Crous 14/11/2011</remarks> public static bool Signin(String Username, String Password) { try { //CompleteDataLayer.User user = CompleteDataLayer.UserDataProvider.Instance.Authenticate(Username, Password); DB.SEC_User user = BL.SEC.SEC_User.Authenticate(Username, EncodePassword(Password)); if (user != null) { // User provided correct credentials ApplicationDataContext.Instance.LoggedInUser = user; ApplicationDataContext.Instance.LoggedInUser.Person = ApplicationDataContext.Instance.SystemEntityContext.SYS_Person.FirstOrDefault(n => n.Id == ApplicationDataContext.Instance.LoggedInUser.PersonId); ApplicationDataContext.Instance.LoggedInUser.DefaultPrinter = ApplicationDataContext.Instance.SystemEntityContext.SYS_Printer.FirstOrDefault(n => n.Id == ApplicationDataContext.Instance.LoggedInUser.DefaultPrinterId); ApplicationDataContext.Instance.LoggedInUser.DefaultSite = ApplicationDataContext.Instance.SystemEntityContext.SYS_Site.Include("SYS_Entity").FirstOrDefault(n => n.EntityId == ApplicationDataContext.Instance.LoggedInUser.DefaultSiteId); //Console.WriteLine(ApplicationDataContext.Instance.LoggedInUser.DefaultSite.SYS_Entity.Id); int PortStartIndex = 1000; int PortEndIndex = 2000; System.Net.NetworkInformation.IPGlobalProperties properties = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties(); IPEndPoint[] tcpEndPoints = properties.GetActiveTcpListeners(); List <int> usedPorts = tcpEndPoints.Select(p => p.Port).ToList <int>(); int unusedPort = 0; for (int port = PortStartIndex; port < PortEndIndex; port++) { if (!usedPorts.Contains(port)) { unusedPort = port; break; } } // Update Last Login Details user.LastDate = DateTime.Now; //user.LastLocation = String.Format("Machine: {0};OS: {1}; User:{2}; IP: {3}", Environment.MachineName, Environment.OSVersion, Environment.UserName, System.Net.Dns.GetHostAddresses(Environment.MachineName).Where(n => !n.IsIPv6LinkLocal && !n.IsIPv6Multicast && !n.IsIPv6SiteLocal && !n.IsIPv6Teredo).FirstOrDefault().ToString()); user.LastLocation = String.Format("Machine: {0};OS: {1}; User:{2}; IP: {3};Open Port: {4}", Environment.MachineName, Environment.OSVersion, Environment.UserName, System.Net.Dns.GetHostAddresses(Environment.MachineName).Where(n => !n.IsIPv6LinkLocal && !n.IsIPv6Multicast && !n.IsIPv6SiteLocal && n.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).FirstOrDefault().ToString(), unusedPort); //IF this is null you are not loggin in from CDS.Desktop if (Assembly.GetEntryAssembly() == null) { user.LastVersion = FileVersionInfo.GetVersionInfo(Assembly.GetCallingAssembly().Location).ProductVersion; } else { user.LastVersion = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Location).ProductVersion; } using (System.Transactions.TransactionScope transaction = BL.ApplicationDataContext.Instance.DataContext.GetTransactionScope()) { BL.ApplicationDataContext.Instance.DataContext.SaveChangesEntitySecurityContext(); BL.ApplicationDataContext.Instance.DataContext.CompleteTransaction(transaction); } //// Get the user roles and associated access rights //long[] roleids = BL.ApplicationDataContext.Instance.SecurityEntityContext.SEC_UserRole.Where(n => n.UserId == user.Id).Select(n => n.RoleId).ToArray(); //ApplicationDataContext.Instance.AccessIds = BL.ApplicationDataContext.Instance.SecurityEntityContext.SEC_RoleAccess.Where(n => roleids.Contains(n.RoleId)).Select(n => n.AccessId).Distinct().ToArray(); return(true); } else { // User provided incorrect credentials return(false); } } catch (Exception ex) { //if (BusinessLogicExceptionHandler.HandleException(ref ex)) throw ex; throw ex.InnerException; } }