C# 擷取本機IP地址以及轉換字串

來源:互聯網
上載者:User

標籤:擷取本機ip   ons   etl   ext   tostring   ipaddress   param   ip地址   style   

        /// <summary>        /// IP地址轉化        /// </summary>        /// <param name="ipaddr">整型的IP地址</param>        /// <returns>字串的IP地址</returns>        private string UintIPToStringIP(uint ipaddr)        {            string hexStr = ipaddr.ToString("X8");            int ip1 = Convert.ToInt32(hexStr.Substring(0, 2), 16);            int ip2 = Convert.ToInt32(hexStr.Substring(2, 2), 16);            int ip3 = Convert.ToInt32(hexStr.Substring(4, 2), 16);            int ip4 = Convert.ToInt32(hexStr.Substring(6, 2), 16);            return ip4 + "." + ip3 + "." + ip2 + "." + ip1;        }        /// <summary>        /// IP地址轉化        /// </summary>        /// <param name="ipaddr">字串的IP地址</param>        /// <returns>整型的IP地址</returns>        private uint StringIPToUintIP(string ipaddr)        {            string[] ips = ipaddr.Split(‘.‘);            return Convert.ToUInt32(ips[3]) * 256 * 256 * 256 + Convert.ToUInt32(ips[2]) * 256 * 256 + Convert.ToUInt32(ips[1]) * 256 + Convert.ToUInt32(ips[0]);                  }        /// <summary>        /// 擷取本機IP地址        /// </summary>        /// <returns></returns>        private string GetLocalIPAddress()        {            string resultIP = string.Empty;            System.Net.IPAddress[] ips = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList;            foreach (System.Net.IPAddress ip in ips)            {                if (IsCorrentIP(ip.ToString()))                {                    resultIP = ip.ToString();                    break;                }            }            return resultIP;        }        /// <summary>        /// 驗證IP地址是否有效        /// </summary>        /// <param name="ip"></param>        /// <returns></returns>        private bool IsCorrentIP(string ip)        {            string pattrn = @"(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])";            if (System.Text.RegularExpressions.Regex.IsMatch(ip, pattrn))            {                return true;            }            else            {                return false;            }        }

 

C# 擷取本機IP地址以及轉換字串

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.