Browse Source

Fix for correct handling of null-terminated strings

Fixes #30
NX 7 years ago
parent
commit
e7cf11b9e7
1 changed files with 18 additions and 5 deletions
  1. 18 5
      Source/Managed/ENet.cs

+ 18 - 5
Source/Managed/ENet.cs

@@ -564,10 +564,10 @@ namespace ENet {
 				byte[] ip = ArrayPool.GetBuffer();
 				byte[] ip = ArrayPool.GetBuffer();
 
 
 				if (Native.enet_peer_get_ip(nativePeer, ip, (IntPtr)ip.Length) == 0) {
 				if (Native.enet_peer_get_ip(nativePeer, ip, (IntPtr)ip.Length) == 0) {
-					if (Encoding.ASCII.GetString(ip).Remove(7) == "::ffff:")
-						return Encoding.ASCII.GetString(ip).Substring(7);
-
-					return Encoding.ASCII.GetString(ip);
+					if (Encoding.ASCII.GetString(ip).Remove(7) != "::ffff:")
+						return Encoding.ASCII.GetString(ip, 0, ip.StringLength());
+					else
+						return Encoding.ASCII.GetString(ip, 0, ip.StringLength()).Substring(7);
 				} else {
 				} else {
 					return String.Empty;
 					return String.Empty;
 				}
 				}
@@ -728,6 +728,19 @@ namespace ENet {
 		}
 		}
 	}
 	}
 
 
+	public static class Extensions {
+		public static int StringLength(this byte[] data) {
+			if (data == null)
+				throw new ArgumentNullException("data");
+
+			int i;
+
+			for (i = 0; i < data.Length && data[i] != 0; i++);
+
+			return i;
+		}
+	}
+
 	public static class Library {
 	public static class Library {
 		public const uint maxChannelCount = 0xFF;
 		public const uint maxChannelCount = 0xFF;
 		public const uint maxPeers = 0xFFF;
 		public const uint maxPeers = 0xFFF;
@@ -922,4 +935,4 @@ namespace ENet {
 		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
 		[DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
 		internal static extern void enet_peer_reset(IntPtr peer);
 		internal static extern void enet_peer_reset(IntPtr peer);
 	}
 	}
-}
+}