Esempio n. 1
0
        } // End Function GetDnsHostName

        public static System.Collections.Generic.List <ARSoft.Tools.Net.Dns.SrvRecord> GetLdap()
        {
            System.Net.NetworkInformation.IPGlobalProperties ipgp =
                System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties();

            // IDnsResolver resolver = new RecursiveDnsResolver(); // Warning: Doesn't work
            ARSoft.Tools.Net.Dns.IDnsResolver resolver = new ARSoft.Tools.Net.Dns.DnsStubResolver();
            ARSoft.Tools.Net.DomainName       dn       = ARSoft.Tools.Net.DomainName.Parse("_ldap._tcp." + ipgp.DomainName);

            System.Collections.Generic.List <ARSoft.Tools.Net.Dns.SrvRecord> srvRecords =
                resolver.Resolve <ARSoft.Tools.Net.Dns.SrvRecord>(dn, ARSoft.Tools.Net.Dns.RecordType.Srv);

            //foreach (ARSoft.Tools.Net.Dns.SrvRecord thisRecord in srvRecords)
            //{
            //    // System.Console.WriteLine(thisRecord.Name);
            //    System.Console.WriteLine(thisRecord.Target);
            //    System.Console.WriteLine(thisRecord.Port);

            //    // Note: OR LDAPS:// - but Novell doesn't want these parts anyway
            //    string url = "LDAP://" + thisRecord.Target + ":" + thisRecord.Port;
            //    System.Console.WriteLine(url);
            //} // Next thisRecord

            return(srvRecords);
        } // End Function GetLdap
Esempio n. 2
0
        /// <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);
        }
Esempio n. 3
0
        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);
        }
Esempio n. 4
0
        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);
        }
Esempio n. 5
0
        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);
        }
Esempio n. 6
0
        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);
        }
Esempio n. 7
0
 private void find()
 {
     richTextBox1.Text = "";
     System.Net.NetworkInformation.IPGlobalProperties         network     = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties();
     System.Net.NetworkInformation.TcpConnectionInformation[] connections = network.GetActiveTcpConnections();
     foreach (System.Net.NetworkInformation.TcpConnectionInformation tcp in connections)
     {
         richTextBox1.Text = richTextBox1.Text + "IP >>> " + "Remote Network Address : " + tcp.RemoteEndPoint.Address + " Local Network Address : " + tcp.LocalEndPoint.Address + " State : " + tcp.State.ToString() + "\n";
     }
 }
        public string GetDomainName()
        {
            try
            {
                System.Net.NetworkInformation.IPGlobalProperties ipProperties = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties();
                return(ipProperties.DomainName);
            }
            catch (Exception) { }

            return(String.Empty);
        }
Esempio n. 9
0
 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);
 }
Esempio n. 10
0
 /// <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);
 }
Esempio n. 11
0
 private void find()
 {
     richTextBox1.Text = "";
     System.Net.NetworkInformation.IPGlobalProperties         network     = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties();
     System.Net.NetworkInformation.TcpConnectionInformation[] connections = network.GetActiveTcpConnections();
     foreach (System.Net.NetworkInformation.TcpConnectionInformation tcp in connections)
     {
         richTextBox1.Text = richTextBox1.Text + "IP >>> " + "Remote Network Address : " + tcp.RemoteEndPoint.Address + " Local Network Address : " + tcp.LocalEndPoint.Address + " State : " + tcp.State.ToString() + "\n";
     }
     if (richTextBox1.Text == "")
     {
         richTextBox1.Text = "Unfortunately No Computers Where found On your Current Network, You may Want to check your Network Cables or Windows Networking Settings.";
     }
 }
Esempio n. 12
0
        internal static string WinGetHostName()
        {
            System.Net.NetworkInformation.IPGlobalProperties ipProperties =
                System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties();

            string hostname = ipProperties.HostName;

            if (!String.IsNullOrEmpty(ipProperties.DomainName))
            {
                hostname = hostname + "." + ipProperties.DomainName;
            }

            return(hostname);
        }
Esempio n. 13
0
        // Initialize static data in partInfoData
        private void InitPartInfoData()
        {
            string processId = System.Diagnostics.Process.GetCurrentProcess().Id.ToString();

            System.Net.NetworkInformation.IPGlobalProperties gp = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties();
            string Name = gp.HostName + " (" + processId + ")";

            lock (partInfoData)
            {
                partInfoData.name = Name;
                partInfoData.languageImplementation = "C#";
                partInfoData.id     = participantID;
                partInfoData.domain = domainID;
            }
        }
Esempio n. 14
0
        public void Open()
        {
            if (!opened)
            {
                //// For udp receiver sockets it's important to set the "ReuseAddress" socket option
                //// before we call bind. Otherwise we will have a conflict with other applications
                //// listening on the same port.
                udpSocket = new UdpClient();
                //udpSocket.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);

                string IpAddress = "0.0.0.0";
                // We need to bind to a specific interface so we can get an IP address to publish to udp senders
                if (this.localInterface.Equals("0.0.0.0"))
                {
                    System.Net.NetworkInformation.IPGlobalProperties gp = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties();
                    System.Net.NetworkInformation.UnicastIPAddressInformationCollection x = gp.GetUnicastAddresses();
                    for (int i = 0; i < x.Count; i++)
                    {
                        if (x[i].Address.AddressFamily == AddressFamily.InterNetwork) //IPV4
                        {
                            IpAddress = x[i].Address.ToString();
                            break;
                        }
                    }
                }
                else
                {
                    IpAddress = this.localInterface;
                }

                // If this.port == 0, the system will assign us a port. We fetch the used port below.
                IPEndPoint ep = new IPEndPoint(IPAddress.Parse(IpAddress), this.port);
                udpSocket.Client.Bind(ep);

                // Fetch actualy used ip and port that we listen to
                this.IP   = ((IPEndPoint)udpSocket.Client.LocalEndPoint).Address.ToString();
                this.Port = ((IPEndPoint)udpSocket.Client.LocalEndPoint).Port;

                if (this.receiveBufferSize > 0)
                {
                    udpSocket.Client.ReceiveBufferSize = this.receiveBufferSize;
                }

                this.opened = true;
            }
        }
Esempio n. 15
0
        /// <summary>
        /// Determine if the specified end point is available.
        /// </summary>
        /// <param name="ipEndPoint">The IP end point to check.</param>
        /// <returns>true if the specified end point is available; otherwise, false.</returns>
        public static bool IsIPEndPointAvailable(IPEndPoint ipEndPoint)
        {
            bool isIPEndPointAvailable = true;

            System.Net.NetworkInformation.IPGlobalProperties ipGlobalProperties = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties();
            IPEndPoint[] activeUdpListeners = ipGlobalProperties.GetActiveUdpListeners();
            foreach (IPEndPoint activeUdpListener in activeUdpListeners)
            {
                if ((activeUdpListener.Address == ipEndPoint.Address) && (activeUdpListener.Port == ipEndPoint.Port))
                {
                    isIPEndPointAvailable = false;
                    break;
                }
            }

            return(isIPEndPointAvailable);
        }
Esempio n. 16
0
        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);
        }
Esempio n. 17
0
        // Get all MX records for a domain using a recursive resolver
        public static void Test4()
        {
            System.Net.NetworkInformation.IPGlobalProperties ipgp =
                System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties();

            // IDnsResolver resolver = new RecursiveDnsResolver(); // Warning: Doesn't work
            IDnsResolver     resolver   = new DnsStubResolver();
            List <SrvRecord> srvRecords = resolver.Resolve <SrvRecord>("_ldap._tcp." + ipgp.DomainName, RecordType.Srv);

            foreach (SrvRecord thisRecord in srvRecords)
            {
                // System.Console.WriteLine(thisRecord.Name);
                System.Console.WriteLine(thisRecord.Target);
                System.Console.WriteLine(thisRecord.Port);

                string url = "LDAP://" + thisRecord.Target + ":" + thisRecord.Port; // Note: OR LDAPS:// - but Novell doesn't want these parts anyway
                System.Console.WriteLine(url);
            } // Next thisRecord
        }
Esempio n. 18
0
        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);
            }
        }
Esempio n. 19
0
        }     // End Sub TestX11_Shared

        public static void ShowActiveTcpConnections()
        {
            System.Console.WriteLine("Active TCP Connections");
            System.Net.NetworkInformation.IPGlobalProperties properties = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties();

            // System.Console.WriteLine("Computer name: {0}", properties.HostName);
            // System.Console.WriteLine("Domain name:   {0}", properties.DomainName);
            // System.Console.WriteLine("Node type:     {0:f}", properties.NodeType);
            // System.Console.WriteLine("DHCP scope:    {0}", properties.DhcpScopeName);
            // System.Console.WriteLine("WINS proxy?    {0}", properties.IsWinsProxy);

            System.Net.NetworkInformation.TcpConnectionInformation[] connections = properties.GetActiveTcpConnections();
            foreach (System.Net.NetworkInformation.TcpConnectionInformation c in connections)
            {
                System.Console.WriteLine("{0} <==> {1}",
                                         c.LocalEndPoint.ToString(),
                                         c.RemoteEndPoint.ToString());
            }
        }
        /// <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);
        }
Esempio n. 21
0
        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;
            }
        }
Esempio n. 22
0
        private bool IsTcpIPStill(TcpClient tcpClient)
        {
            System.Net.NetworkInformation.IPGlobalProperties         ipProperties   = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties();
            System.Net.NetworkInformation.TcpConnectionInformation[] tcpConnections = ipProperties.GetActiveTcpConnections().Where(x => x.LocalEndPoint.Equals(tcpClient.Client.LocalEndPoint) && x.RemoteEndPoint.Equals(tcpClient.Client.RemoteEndPoint)).ToArray();

            if (tcpConnections != null && tcpConnections.Length > 0)
            {
                System.Net.NetworkInformation.TcpState stateOfConnection = tcpConnections.First().State;
                if (stateOfConnection == System.Net.NetworkInformation.TcpState.Established)
                {
                    // Connection is OK
                    return(true);
                }
                else
                {
                    // No active tcp Connection to hostName:port
                    return(false);
                }
            }
            return(false);
        }
Esempio n. 23
0
        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);
        }
Esempio n. 24
0
        private bool IsUsed(int port)
        {
            bool isUsed = false;

            // 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();
            System.Net.NetworkInformation.TcpConnectionInformation[] tcpConnInfoArray   = ipGlobalProperties.GetActiveTcpConnections();

            foreach (System.Net.NetworkInformation.TcpConnectionInformation tcpi in tcpConnInfoArray)
            {
                if (tcpi.LocalEndPoint.Port == port)
                {
                    isUsed = true;
                    break;
                }
            }

            return(isUsed);
        }
        /// <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);
        }
Esempio n. 26
0
        /// <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);
        }
Esempio n. 27
0
        // If argument contains a "/" we assume it is on the form:  subnet-address/subnet-mask
        // In that case we loop over all interfaces and take the first one that matches
        // i.e. the one whos interface address is on the subnet
        public static string DoSubnetTranslation(string ip)
        {
            int index = ip.IndexOf('/');

            if (index < 0)
            {
                return(ip);
            }

            string subnetIp   = ip.Substring(0, index);
            string subnetMask = ip.Substring(index + 1);

            byte[] mask = System.Net.IPAddress.Parse(subnetMask).GetAddressBytes();

            System.Net.NetworkInformation.IPGlobalProperties computerProperties = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties();
            System.Net.NetworkInformation.NetworkInterface[] nics = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();

            if (nics != null && nics.Length > 0)
            {
                foreach (System.Net.NetworkInformation.NetworkInterface adapter in nics)
                {
                    System.Net.NetworkInformation.IPInterfaceProperties properties = adapter.GetIPProperties();
                    System.Net.NetworkInformation.UnicastIPAddressInformationCollection uniCast = properties.UnicastAddresses;
                    if (uniCast == null)
                    {
                        continue;
                    }

                    foreach (System.Net.NetworkInformation.UnicastIPAddressInformation uni in uniCast)
                    {
                        if (uni.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) //IPV4
                        {
                            byte[] addr = uni.Address.GetAddressBytes();
                            for (int j = 0; j < addr.Length; j++)
                            {
                                addr[j] = (byte)((int)addr[j] & (int)mask[j]);
                            }
                            string Subnet = new System.Net.IPAddress(addr).ToString();

                            if (Subnet.Equals(subnetIp))
                            {
                                return(uni.Address.ToString());
                            }
                        }
                    }
                }
            }
            return(subnetIp);

            //// This only works on Vista and later
            //System.Net.NetworkInformation.IPGlobalProperties gp = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties();
            //System.Net.NetworkInformation.UnicastIPAddressInformationCollection x = gp.GetUnicastAddresses();
            //for (int i = 0; i < x.Count; i++)
            //{
            //    if (x[i].Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) //IPV4
            //    {
            //        byte[] addr = x[i].Address.GetAddressBytes();
            //        byte[] mask = x[i].IPv4Mask.GetAddressBytes();
            //        for (int j = 0; j < addr.Length; j++) addr[j] = (byte)((int)addr[j] & (int)mask[j]);
            //        string Subnet = new System.Net.IPAddress(addr).ToString();

            //        if (Subnet.Equals(subnetIp))
            //        {
            //            return x[i].Address.ToString();
            //        }
            //    }
            //}
            //return subnetIp;
        }
Esempio n. 28
0
 /// <summary>
 /// Gets the fully qualified domain name of the computer where this app runs.
 /// </summary>
 /// <returns>The fully qualified domain name of the computer where this app runs.</returns>
 public static string GetFullyQualifiedDomainName()
 {
     System.Net.NetworkInformation.IPGlobalProperties ipProperties = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties();
     return(string.Format("{0}.{1}", ipProperties.HostName, ipProperties.DomainName));
 }
Esempio n. 29
0
        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);
        }
Esempio n. 30
0
        /// <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;
            }
        }