首页 > 代码库 > C# 获取本机IP地址以及转换字符串
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地址以及转换字符串
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。