/// <summary> /// Extract the address family from the saddr /// </summary> /// <param name="saddrHexString">Saddr hex dump</param> /// <returns>LinuxAddressFamily type</returns> public static LinuxAddressFamily ExtractFamilyFromSaddr(string saddrHexString) { var bytes = ByteExtensions.GetBytesFromFromHexString(saddrHexString); int family = bytes[0]; return((LinuxAddressFamily)family); }
/// <summary> /// Decode a string that is presented in an encoded way /// </summary> /// <param name="encodedString">The encoded string in hex</param> /// <param name="encoding">The text encoding to assume when decoding</param> /// <returns></returns> public static string DecodeHexStringIfNeeded(string encodedString, Encoding encoding) { //sometimes fields that should be encoded are not encoded because reasons ¯\_(ツ)_/¯ //in that case, just return the original string if (NonHexRegex.IsMatch(encodedString) || IsNumberRegex.IsMatch(encodedString)) { return(encodedString); } byte[] data = ByteExtensions.GetBytesFromFromHexString(encodedString); string str = encoding.GetString(data); return(str.Replace("\0", " ")); }
/// <summary> /// The function parse the saddr structure used by Linux connect and accept APIs /// It parses only saddr that represent INET or INET6 family type /// </summary> /// This function receives saddr in hex and translate it /// Note: the translation will be done only if the family name is of type INET for other families null will be returned /// <param name="saddrHexString">Saddr hex dump</param> /// <returns>ConnectionSaddr</returns> public static ConnectionSaddr ParseSaddrToInetConnection(string saddrHexString) { ConnectionSaddr retSaddr = null; LinuxAddressFamily family = ExtractFamilyFromSaddr(saddrHexString); // Saddr Template: // 0-1 bytes - family, // 2-3 bytes - port // 4-7 byte - ip //Extract port var bytes = ByteExtensions.GetBytesFromFromHexString(saddrHexString); var port = bytes.ToUshort(2, false); if (family == LinuxAddressFamily.AF_INET) { var ip = bytes.Skip(4).Take(4); retSaddr = new ConnectionSaddr { Ip = string.Join('.', ip), Port = port }; } else if (family == LinuxAddressFamily.AF_INET6) { // Saddr for IPv6: // 0-1 bytes - family, // 2-3 bytes - port // 4-7 byte - flowinfo // 8-23 24 - ip var ip = BitConverter.ToString(bytes.Skip(8).Take(16).ToArray()).Replace("-", ""); ip = Regex.Replace(ip, "(.{4})", "$1:"); ip = ip.Remove(ip.Length - 1, 1); retSaddr = new ConnectionSaddr { Ip = ip, Port = port }; } return(retSaddr); }