재우니의 블로그

c# 코드로 ip 정보를 * 별표로 표기하는 방법입니다. 개인정보 보안 때문에 필요하게 되더군요.

https://stackoverflow.com/a/11972520


/// <summary>
/// Ips the masking.
/// luckshim
/// </summary>
/// <param name="html">The HTML.</param>
/// <param name="s">The s.</param>
/// <param name="hide">The index.</param>
/// <returns></returns>
public static MvcHtmlString IPMasking(this HtmlHelper html, string s, int hide = 1)
{
if (s.ToNull().Length == 0) return new MvcHtmlString(s);
//192.168.*.*
var name = Regex.Replace(s, @"^(?<Prefix>(\d{1,3}\.){3})\d{1,3}$", "${Prefix}*");

switch (hide)
{
case 1:
//192.168.0.*
name = Regex.Replace(s, @"^(?<Prefix>(\d{1,3}\.){3})\d{1,3}$", "${Prefix}*");
break;
case 2:
//192.168.*.*
name = Regex.Replace(s, @"^(?<Prefix>(\d{1,3}\.){2})\d{1,3}\.\d{1,3}$", "${Prefix}*.*");
break;
case 3:
//192.*.*.*
name = Regex.Replace(s, @"^(?<Prefix>(\d{1,3}\.))\d{1,3}\.\d{1,3}\.\d{1,3}$", "${Prefix}*.*.*");
break;
}

return (MvcHtmlString.Create(HttpContext.Current.Server.HtmlEncode(name).Replace(Environment.NewLine, "<br />")));
}