C# 获取本机IP地址以及转换字符串
Posted 名扬博客
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# 获取本机IP地址以及转换字符串相关的知识,希望对你有一定的参考价值。
/// <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地址以及转换字符串的主要内容,如果未能解决你的问题,请参考以下文章