Files
raven/server/AyaNova/util/StringUtil.cs
2018-06-28 23:41:48 +00:00

96 lines
3.0 KiB
C#

using System;
namespace AyaNova.Util
{
internal static class StringUtil
{
/// <summary>
/// Extract string between tokens
/// </summary>
/// <param name="s"></param>
/// <param name="openTag"></param>
/// <param name="closeTag"></param>
/// <returns></returns>
public static string Extract(string s, string openTag, string closeTag)
{
int startIndex = s.IndexOf(openTag);
if (startIndex == -1)
throw new System.IndexOutOfRangeException("ExtractString->Error: open tag not found");
startIndex += openTag.Length;
int endIndex = s.IndexOf(closeTag, startIndex);
if (endIndex == -1)
throw new System.IndexOutOfRangeException("ExtractString->Error: closing tag not found");
return s.Substring(startIndex, endIndex - startIndex);
}
/// <summary>
/// Trim a string if necessary
/// </summary>
/// <param name="s"></param>
/// <param name="maxLength"></param>
/// <returns></returns>
public static string MaxLength(string s, int maxLength)
{
if (s.Length > maxLength)
s = s.Substring(0, maxLength);
return s;
}
/// <summary>
/// mask the exact ip address by substituting the last position of the address with XXX
/// Works with v6 or v4 addresses as strings
/// </summary>
/// <param name="sIP"></param>
/// <returns></returns>
public static string MaskIPAddress(string sIP)
{
//My test station ip address!?
//"::ffff:127.0.0.1"
//weird dual format, new method that covers both v4 and v4 inside v6 format
if(sIP.Contains("."))
{
//new algorithm, replace anything after last period with an xxx
var ret=sIP.Substring(0,sIP.LastIndexOf("."))+".xxx";
return ret;
}
//8 groups IPV6 Address format
if (sIP.Contains(":"))
{
sIP=sIP.Replace("::",":0:");//rehydrate "compressed" addresses
var segs = sIP.Split(':');
if (segs.Length < 7)
return "UNRECOGNIZED V6 IP ADDRESS FORMAT";
else
return segs[0] + ":" + segs[1] + ":" + segs[2] + ":" + segs[3] + ":" + segs[4] + ":" + segs[5] + ":" + segs[6] + ":" + segs[7] + ":xxxx";
}
// //4 groups IPV4 Address format
// if (sIP.Contains("."))
// {
// //8 groups IPV6 Address format
// var segs = sIP.Split('.');
// if (segs.Length < 3)
// return "UNRECOGNIZED V4 IP ADDRESS FORMAT";
// else
// return segs[0] + "." + segs[1] + "." + segs[2] + ".xxx";
// }
return "UNRECOGNIZED IP ADDDRESS FORMAT";
}
}//eoc
}//eons