示例#1
0
        /// <summary>
        /// 根据服务器IP获取能连接到该服务器的其中一个客户端面IP地址
        /// </summary>
        /// <param name="serverIp">服务器IP</param>
        /// <returns>找到的客户端IP地址</returns>
        public static IPAddress GetPingServerIpClientIp(string serverIp)
        {
            IPAddress serverIpAddr;

            if (!IPAddress.TryParse(serverIp, out serverIpAddr))
            {
                throw new Exception(string.Format("服务端IP:{0}不是有效有IP值", serverIp));
            }

            IPAddress ipAddrRet = null;

            IPAddress[] ipaddrs = Dns.GetHostAddresses(Dns.GetHostName());

            foreach (IPAddress ipAddr in ipaddrs)
            {
                //ipAddr.AddressFamily :对于 IPv4,返回 InterNetwork;对于 IPv6,返回 InterNetworkV6。
                if (serverIpAddr.AddressFamily != ipAddr.AddressFamily)
                {
                    continue;
                }

                if (IPAddressEx.ValidateClientIpPingServerIp(ipAddr.ToString(), serverIp))
                {
                    ipAddrRet = ipAddr;
                    break;
                }
            }

            return(ipAddrRet);
        }
示例#2
0
        /// <summary>
        /// 验证一个端口号是否被使用
        /// </summary>
        /// <param name="ipaddr">IP对象</param>
        /// <param name="port">需要验证的端口号</param>
        /// <returns>如果被使用返回true,否则返回false</returns>
        public static bool PortAvailable(this IPAddress ipaddr, int port)
        {
            List <int> tcpPorts = null;
            List <int> udpPorts = null;
            List <int> ipPorts  = null;
            var        allports = IPAddressEx.GetUsedPorts(out tcpPorts, out udpPorts, out ipPorts);

            return(allports.Contains(port));
        }
示例#3
0
        /// <summary>
        /// IPV4地址转换为Int64整数(返回值全为正数)
        /// </summary>
        /// <param name="ipStr">ip字符串</param>
        /// <returns>ip对应的整数</returns>
        public static long IPV4ToInt64(string ipStr)
        {
            if (!IPAddressEx.ValidateIPV4(ipStr))
            {
                throw new Exception(string.Format("服务端IP:{0}不是有效有IPV4值", ipStr));
            }

            string[] items = ipStr.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
            return(long.Parse(items[0]) << 24
                   | long.Parse(items[1]) << 16
                   | long.Parse(items[2]) << 8
                   | long.Parse(items[3]));
        }
示例#4
0
        /// <summary>
        /// 获取已使用的端口号
        /// </summary>
        /// <returns>当前所有已使用端口号集合</returns>
        public static List <int> GetUsedPorts()
        {
            List <int> tcpPorts, udpPorts, ipPorts;

            return(IPAddressEx.GetUsedPorts(out tcpPorts, out udpPorts, out ipPorts));
        }