public static String CloseRemoteIP(MIB_TCPROW tcpRow) // return error string or Null { tcpRow.dwState = (uint)MIB_TCP_STATE.MIB_TCP_STATE_DELETE_TCB; IntPtr ptr = Marshal.AllocHGlobal(System.Runtime.InteropServices.Marshal.SizeOf(typeof(MIB_TCPROW))); Marshal.StructureToPtr(tcpRow, ptr, false); var ret = (SetTcpEntryErrors)SetTcpEntry(ptr); switch (ret) { case SetTcpEntryErrors.ERROR_SUCCESS: return(null); case SetTcpEntryErrors.ERROR_ACCESS_DENIED: return("Access denied"); case SetTcpEntryErrors.ERROR_NOT_SUPPORTED: return("Not supported"); case SetTcpEntryErrors.ERROR_INVALID_PARAMETER: return("Invalid parameter"); case SetTcpEntryErrors.ERROR_APPLICATION_NOT_ELEVATED: return("Application not elevated"); default: return(String.Format("Unknown error {0}", ret)); } }
public static void SetTcpEntry(MIB_TCPROW tcpRow) { IntPtr pTcpRow = IntPtr.Zero; try { pTcpRow = Marshal.AllocCoTaskMem(Marshal.SizeOf(tcpRow)); Marshal.StructureToPtr(tcpRow, pTcpRow, false); int result = SetTcpEntry(pTcpRow); switch (result) { case 0: break; case -1: throw new Exception("Unsuccessful"); case 65: throw new Exception("User has insufficient privilege to execute this API successfully"); case 87: throw new Exception("Specified port is not in state to be closed down"); default: throw new Exception(string.Format("Unknown error '{0}' ({1})", result, new Win32Exception(result).Message)); } } finally { if (pTcpRow != IntPtr.Zero) { Marshal.FreeCoTaskMem(pTcpRow); } } }
public TcpConnectionInfo(TCP_ESTATS_PATH_ROD_v0 stats, MIB_TCPROW_OWNER_MODULE ownerRow, MIB_TCPROW tcpRow, TCPIP_OWNER_MODULE_BASIC_INFO ownerInfo) { this.stats = stats; this.ownerRow = ownerRow; this.tcpRow = tcpRow; this.ownerInfo = ownerInfo; }
public static MIB_TCPTABLE GetTcpTableInfo() { IntPtr hTcpTableData = IntPtr.Zero; int iBufferSize = 0; MIB_TCPTABLE tcpTable = new MIB_TCPTABLE(); List <MIB_TCPROW> lstTcpRows = new List <MIB_TCPROW>(); GetTcpTable(hTcpTableData, ref iBufferSize, false); hTcpTableData = Marshal.AllocHGlobal(iBufferSize); int iTcpRowLen = Marshal.SizeOf(typeof(MIB_TCPROW)); int aryTcpRowLength = (int)Math.Ceiling((double)(iBufferSize - sizeof(int)) / iTcpRowLen); GetTcpTable(hTcpTableData, ref iBufferSize, false); for (int i = 0; i < aryTcpRowLength; i++) { IntPtr hTempTableRow = new IntPtr(hTcpTableData.ToInt64() + 4 + i * iTcpRowLen); MIB_TCPROW tcpRow = new MIB_TCPROW(); tcpRow.dwLocalAddr = 0; tcpRow.dwLocalPort = 0; tcpRow.dwRemoteAddr = 0; tcpRow.dwRemotePort = 0; tcpRow.dwState = 0; Marshal.PtrToStructure(hTempTableRow, tcpRow); lstTcpRows.Add(tcpRow); } tcpTable.dwNumEntries = lstTcpRows.Count; tcpTable.table = new MIB_TCPROW[lstTcpRows.Count]; lstTcpRows.CopyTo(tcpTable.table); return(tcpTable); }
public static TCP_ESTATS_BANDWIDTH_ROD_v0 GetTCPBandwidth(MIB_TCPROW row) { IntPtr rw = IntPtr.Zero; IntPtr rod = IntPtr.Zero; try { var rwS = Marshal.SizeOf(typeof(TCP_ESTATS_BANDWIDTH_RW_v0)); rw = Marshal.AllocHGlobal(rwS); var rodS = Marshal.SizeOf(typeof(TCP_ESTATS_BANDWIDTH_ROD_v0)); rod = Marshal.AllocHGlobal(rodS); var r = GetPerTcpConnectionEStats(ref row, TCP_ESTATS_TYPE.TcpConnectionEstatsBandwidth, rw, 0, (uint)rwS, IntPtr.Zero, 0, 0, rod, 0, (uint)rodS); if (r != 0) { throw new Win32Exception((int)r); } var parsedRW = (TCP_ESTATS_BANDWIDTH_RW_v0)Marshal.PtrToStructure(rw, typeof(TCP_ESTATS_BANDWIDTH_RW_v0)); if (parsedRW.EnableCollectionInbound != TCP_BOOLEAN_OPTIONAL.TcpBoolOptEnabled || parsedRW.EnableCollectionOutbound != TCP_BOOLEAN_OPTIONAL.TcpBoolOptEnabled) { throw new Exception("Monitoring is disabled for this connection."); } return((TCP_ESTATS_BANDWIDTH_ROD_v0)Marshal.PtrToStructure(rod, typeof(TCP_ESTATS_BANDWIDTH_ROD_v0))); } catch (Win32Exception we) { if (we.NativeErrorCode == ERROR_NOT_FOUND) { return(new TCP_ESTATS_BANDWIDTH_ROD_v0() { InboundBandwidth = 0, OutboundBandwidth = 0 }); } else { throw; } } catch (Exception) { throw; } finally { if (rw != IntPtr.Zero) { Marshal.FreeHGlobal(rw); } if (rod != IntPtr.Zero) { Marshal.FreeHGlobal(rod); } } }
/// <summary> /// The GetTcpTable function retrieves the IPv4 TCP connection table. /// </summary> /// <param name="sort">Specifies whether the TCP connection table should be sorted in the order of: /// (1) Local IP address /// (2) Local port /// (3) Remote IP address /// (4) Remote port /// </param> /// <returns>Returns the TCP connection table as an MIB_TCPROW array.</returns> public static MIB_TCPROW[] GetTcpTable(bool sort) { IntPtr pBuffer = IntPtr.Zero; try { // Used to hold the size of the returned data. int size = 0; // Call GetTcpTable the first time to determine the size of the data to be returned. int result = GetTcpTable(IntPtr.Zero, ref size, sort); // We should receive an 'Insufficient Buffer' error, otherwise throw an exception. if (result != ERROR_INSUFFICIENT_BUFFER) { throw new Win32Exception(result); } // Allocate the memory buffer of required size. pBuffer = Marshal.AllocCoTaskMem(size); // Call GetIpNetTable the second time to retreive the actual data. result = GetTcpTable(pBuffer, ref size, sort); // If the result is not 0 (no error), then throw an exception. if (result != 0) { throw new Win32Exception(result); } // Read the first four bytes from the buffer to determine the number of MIB_TCPROW structures returned. int count = Marshal.ReadInt32(pBuffer); //Declare an array to contain the returned data. MIB_TCPROW[] tcpTable = new MIB_TCPROW[count]; // Get the structure type and size. Type tMIB_TCPROW = typeof(MIB_TCPROW); size = Marshal.SizeOf(tMIB_TCPROW); int dw = Marshal.SizeOf(new int()); // 4-bytes // Cycle through the entries. for (int index = 0; index < count; index++) { // Call PtrToStructure, getting the structure information. tcpTable[index] = (MIB_TCPROW)Marshal.PtrToStructure(new IntPtr(pBuffer.ToInt64() + dw + (index * size)), tMIB_TCPROW); } return(tcpTable); } finally { // Release the allocate the memory buffer. if (pBuffer != IntPtr.Zero) { Marshal.FreeCoTaskMem(pBuffer); } } }
public MIB_TCPROW ToTcpRow() { var row = new MIB_TCPROW(); row.dwState = dwState; row.dwLocalAddr = dwLocalAddr; row.dwLocalPort = dwLocalPort; row.dwRemoteAddr = dwRemoteAddr; row.dwRemotePort = dwRemotePort; return(row); }
//Close a connection by returning the connectionstring public static void CloseConnection(string connectionstring) { try { //Split the string to its subparts string[] parts = connectionstring.Split('-'); if (parts.Length != 4) { throw new Exception("Invalid connectionstring - use the one provided by Connections."); } string[] loc = parts[0].Split(':'); string[] rem = parts[1].Split(':'); string[] locaddr = loc[0].Split('.'); string[] remaddr = rem[0].Split('.'); //Fill structure with data MIB_TCPROW row = new MIB_TCPROW(); row.dwState = 12; byte[] bLocAddr = new byte[] { byte.Parse(locaddr[0]), byte.Parse(locaddr[1]), byte.Parse(locaddr[2]), byte.Parse(locaddr[3]) }; byte[] bRemAddr = new byte[] { byte.Parse(remaddr[0]), byte.Parse(remaddr[1]), byte.Parse(remaddr[2]), byte.Parse(remaddr[3]) }; row.dwLocalAddr = BitConverter.ToInt32(bLocAddr, 0); row.dwRemoteAddr = BitConverter.ToInt32(bRemAddr, 0); row.dwLocalPort = htons(int.Parse(loc[1])); row.dwRemotePort = htons(int.Parse(rem[1])); //SetTcpEntry的返回值状态 默认87异常 int ret = 87; //Make copy of the structure into memory and use the pointer to call SetTcpEntry IntPtr ptr = GetPtrToNewObject(row); ret = SetTcpEntry(ptr); if (ret == -1) { throw new Exception("Unsuccessful"); } if (ret == 65) { throw new Exception("User has no sufficient privilege to execute this API successfully"); } if (ret == 87) { throw new Exception("Specified port is not in state to be closed down"); } if (ret != 0) { throw new Exception("Unknown error (" + ret + ")"); } } catch (Exception) { //throw new Exception("CloseConnection failed (" + connectionstring + ")! [" + ex.GetType().ToString() + "," + ex.Message + "]"); } }
//The function that fills the MIB_TCPROW array with connectioninfos private static MIB_TCPROW[] getTcpTable() { IntPtr buffer = IntPtr.Zero; bool allocated = false; try { int iBytes = 0; GetTcpTable(IntPtr.Zero, ref iBytes, false); //Getting size of return data buffer = Marshal.AllocCoTaskMem(iBytes); //allocating the datasize allocated = true; GetTcpTable(buffer, ref iBytes, false); int structCount = Marshal.ReadInt32(buffer); // Get the number of structures IntPtr buffSubPointer = buffer; //Making a pointer that will point into the buffer buffSubPointer = (IntPtr)(buffer + 4); //Move to the first data (ignoring dwNumEntries from the original MIB_TCPTABLE struct) MIB_TCPROW[] tcpRows = new MIB_TCPROW[structCount]; //Declaring the array //Get the struct size MIB_TCPROW tmp = new MIB_TCPROW(); Int64 sizeOfTCPROW = Marshal.SizeOf(tmp); //Fill the array 1 by 1 for (int i = 0; i < structCount; i++) { tcpRows[i] = (MIB_TCPROW)Marshal.PtrToStructure(buffSubPointer, typeof(MIB_TCPROW)); //copy struct data buffSubPointer = (IntPtr)((Int64)buffSubPointer + sizeOfTCPROW); //move to next structdata } return(tcpRows); } catch (Exception ex) { throw new Exception("getTcpTable failed! [" + ex.GetType().ToString() + "," + ex.Message + "]"); } finally { if (allocated) { Marshal.FreeCoTaskMem(buffer); //Free the allocated memory } } }
private MIB_TCPROW[] getTcpTable() { IntPtr buffer = IntPtr.Zero; bool allocated = false; try { int iBytes = 0; GetTcpTable(IntPtr.Zero, ref iBytes, false); buffer = Marshal.AllocCoTaskMem(iBytes); allocated = true; GetTcpTable(buffer, ref iBytes, false); int structCount = Marshal.ReadInt32(buffer); IntPtr buffSubPointer = buffer; buffSubPointer = (IntPtr)((int)buffer + 4); MIB_TCPROW[] tcpRows = new MIB_TCPROW[structCount]; MIB_TCPROW tmp = new MIB_TCPROW(); int sizeOfTCPROW = Marshal.SizeOf(tmp); for (int i = 0; i < structCount; i++) { tcpRows[i] = (MIB_TCPROW)Marshal.PtrToStructure(buffSubPointer, typeof(MIB_TCPROW)); buffSubPointer = (IntPtr)((int)buffSubPointer + sizeOfTCPROW); } return(tcpRows); } catch (Exception ex) { throw new Exception("getTcpTable failed! [" + ex.GetType().ToString() + "," + ex.Message + "]"); } finally { if (allocated) { Marshal.FreeCoTaskMem(buffer); } } }
public static TCP_ESTATS_DATA_ROD_v0 GetTCPStatistics(MIB_TCPROW_OWNER_MODULE conn) { IntPtr rw = IntPtr.Zero; IntPtr rod = IntPtr.Zero; try { var row = new MIB_TCPROW() { dwLocalAddr = conn._localAddr, dwRemoteAddr = conn._remoteAddr, dwLocalPort = conn._localPort, dwRemotePort = conn._remotePort, dwState = conn._state }; EnsureStatsAreEnabled(row); var rwS = Marshal.SizeOf(typeof(TCP_ESTATS_DATA_RW_v0)); rw = Marshal.AllocHGlobal(rwS); var rodS = Marshal.SizeOf(typeof(TCP_ESTATS_DATA_ROD_v0)); rod = Marshal.AllocHGlobal(rodS); var resp = GetPerTcpConnectionEStats(ref row, TCP_ESTATS_TYPE.TcpConnectionEstatsData, rw, 0, (uint)rwS, IntPtr.Zero, 0, 0, rod, 0, (uint)rodS); if (resp != NO_ERROR) { LogHelper.Error("Unable to get the connection statistics.", new Win32Exception((int)resp)); } var parsedRW = (TCP_ESTATS_DATA_RW_v0)Marshal.PtrToStructure(rw, typeof(TCP_ESTATS_DATA_RW_v0)); var parsedROD = (TCP_ESTATS_DATA_ROD_v0)Marshal.PtrToStructure(rod, typeof(TCP_ESTATS_DATA_ROD_v0)); return(parsedROD); } finally { if (rw != IntPtr.Zero) { Marshal.FreeHGlobal(rw); } if (rod != IntPtr.Zero) { Marshal.FreeHGlobal(rod); } } }
/// <summary>刪除連線並清除該連線的所有資源</summary> /// <param name="conn">連線資訊</param> /// <returns>是否刪除成功</returns> public static bool Kill(SocketInfo conn) { if (conn == null) { throw new ArgumentNullException("conn"); } MIB_TCPROW row = new MIB_TCPROW(); row.dwState = TcpState.DeleteTcb; #pragma warning disable 612,618 row.dwLocalAddr = (int)conn.LocalEndPoint.Address.Address; #pragma warning restore 612,618 row.dwLocalPort = TranslatePort(conn.LocalEndPoint.Port); #pragma warning disable 612,618 row.dwRemoteAddr = (int)conn.RemoteEndPoint.Address.Address; #pragma warning restore 612,618 row.dwRemotePort = TranslatePort(conn.RemoteEndPoint.Port); return(SetTcpEntry(ref row) == 0); }
public static void EnsureStatsAreEnabled(MIB_TCPROW row) { var rwS = Marshal.SizeOf(typeof(TCP_ESTATS_BANDWIDTH_RW_v0)); IntPtr rw = Marshal.AllocHGlobal(rwS); Marshal.StructureToPtr(new TCP_ESTATS_BANDWIDTH_RW_v0() { EnableCollectionInbound = TCP_BOOLEAN_OPTIONAL.TcpBoolOptEnabled, EnableCollectionOutbound = TCP_BOOLEAN_OPTIONAL.TcpBoolOptEnabled }, rw, true); try { var r = SetPerTcpConnectionEStats(ref row, TCP_ESTATS_TYPE.TcpConnectionEstatsBandwidth, rw, 0, (uint)rwS, 0); if (r != 0) { throw new Win32Exception((int)r); } } finally { Marshal.FreeHGlobal(rw); } }
/// <summary>刪除連線並清除該連線的所有資源</summary> /// <param name="localEndPoint">本地端通訊埠</param> /// <param name="remoteEndPoint">遠端通訊埠</param> /// <returns>是否刪除成功</returns> public static bool Kill(IPEndPoint localEndPoint, IPEndPoint remoteEndPoint) { if (localEndPoint == null) { throw new ArgumentNullException("localEndPoint"); } if (remoteEndPoint == null) { throw new ArgumentNullException("remoteEndPoint"); } MIB_TCPROW row = new MIB_TCPROW(); row.dwState = TcpState.DeleteTcb; #pragma warning disable 612,618 row.dwLocalAddr = (int)localEndPoint.Address.Address; #pragma warning restore 612,618 row.dwLocalPort = TranslatePort(localEndPoint.Port); #pragma warning disable 612,618 row.dwRemoteAddr = (int)remoteEndPoint.Address.Address; #pragma warning restore 612,618 row.dwRemotePort = TranslatePort(remoteEndPoint.Port); return(SetTcpEntry(ref row) == 0); }
/// <summary> /// Close a connection by returning the connectionstring /// </summary> /// <param name="connectionstring"></param> public static void CloseConnection(string connectionstring) { try { //Split the string to its subparts string[] parts = connectionstring.Split('-'); if (parts.Length != 4) throw new Exception("Invalid connectionstring - use the one provided by Connections."); string[] loc = parts[0].Split(':'); string[] rem = parts[1].Split(':'); string[] locaddr = loc[0].Split('.'); string[] remaddr = rem[0].Split('.'); //Fill structure with data MIB_TCPROW row = new MIB_TCPROW(); row.dwState = 12; byte[] bLocAddr = new byte[] { byte.Parse(locaddr[0]), byte.Parse(locaddr[1]), byte.Parse(locaddr[2]), byte.Parse(locaddr[3]) }; byte[] bRemAddr = new byte[] { byte.Parse(remaddr[0]), byte.Parse(remaddr[1]), byte.Parse(remaddr[2]), byte.Parse(remaddr[3]) }; row.dwLocalAddr = BitConverter.ToInt32(bLocAddr, 0); row.dwRemoteAddr = BitConverter.ToInt32(bRemAddr, 0); row.dwLocalPort = htons(int.Parse(loc[1])); row.dwRemotePort = htons(int.Parse(rem[1])); //Make copy of the structure into memory and use the pointer to call SetTcpEntry IntPtr ptr = GetPtrToNewObject(row); int ret = SetTcpEntry(ptr); if (ret == -1) throw new Exception("Unsuccessful"); if (ret == 65) throw new Exception("User has no sufficient privilege to execute this API successfully"); if (ret == 87) throw new Exception("Specified port is not in state to be closed down"); if (ret != 0) throw new Exception("Unknown error (" + ret + ")"); } catch (Exception ex) { throw new Exception("CloseConnection failed (" + connectionstring + ")! [" + ex.GetType().ToString() + "," + ex.Message + "]"); } }
private void FindSocket() { var buff = IntPtr.Zero; try { // get all sockets var buffSize = 0; while (GetTcpTable(buff, ref buffSize, false) == Error.ERROR_INSUFFICIENT_BUFFER) { if (buff != IntPtr.Zero) Marshal.FreeHGlobal(buff); buff = Marshal.AllocHGlobal(buffSize); } var err = GetTcpTable(buff, ref buffSize, false); var numEntries = Marshal.ReadInt32(buff); var entrySize = Marshal.SizeOf(typeof(MIB_TCPROW)); const int entriesOffset = sizeof(uint); for (var i = 0; i < numEntries; i++) { var nativePtr = buff + entriesOffset + (entrySize * i); var row = (MIB_TCPROW)Marshal.PtrToStructure(nativePtr, typeof(MIB_TCPROW)); if (row.dwRemotePort == remotePort && remoteAddr.Contains(row.dwRemoteAddr) && row.dwState == (uint)MIB_TCPROW_STATE.MIB_TCP_STATE_ESTAB) { // enable monitoring var rw = new TCP_ESTATS_FINE_RTT_RW_v0 { EnableCollection = 1 }; var rwPtr = Marshal.AllocHGlobal(Marshal.SizeOf(rw)); Marshal.StructureToPtr(rw, rwPtr, false); var ret = SetPerTcpConnectionEStats(ref row, TCP_ESTATS_TYPE.TcpConnectionEstatsFineRtt, rwPtr, 0, Marshal.SizeOf(rw), 0); Marshal.FreeHGlobal(rwPtr); // remember _tcpFound = true; _tcpRow = row; return; } } // did not find a socket _tcpFound = false; } finally { if (buff != IntPtr.Zero) Marshal.FreeHGlobal(buff); } }
private static extern Error SetPerTcpConnectionEStats(ref MIB_TCPROW rowPtr, TCP_ESTATS_TYPE EstatsType, IntPtr Rw, uint RwVersion, int RwSize, uint Offset);
private static extern Error GetPerTcpConnectionEStats(ref MIB_TCPROW rowPtr, TCP_ESTATS_TYPE EstatsType, IntPtr rw, uint RwVersion, int RwSize, IntPtr ros, uint RosVersion, int RosSize, IntPtr rod, uint RodVersion, int RodSize);
//The function that fills the MIB_TCPROW array with connectioninfos private static MIB_TCPROW[] getTcpTable() { IntPtr buffer = IntPtr.Zero; bool allocated = false; try { int iBytes = 0; GetTcpTable(IntPtr.Zero, ref iBytes, false); //Getting size of return data buffer = Marshal.AllocCoTaskMem(iBytes); //allocating the datasize allocated = true; GetTcpTable(buffer, ref iBytes, false); //Run it again to fill the memory with the data int structCount = Marshal.ReadInt32(buffer); // Get the number of structures IntPtr buffSubPointer = buffer; //Making a pointer that will point into the buffer buffSubPointer = (IntPtr)((int)buffer + 4); //Move to the first data (ignoring dwNumEntries from the original MIB_TCPTABLE struct) MIB_TCPROW[] tcpRows = new MIB_TCPROW[structCount]; //Declaring the array //Get the struct size MIB_TCPROW tmp = new MIB_TCPROW(); int sizeOfTCPROW = Marshal.SizeOf(tmp); //Fill the array 1 by 1 for (int i = 0; i < structCount; i++) { tcpRows[i] = (MIB_TCPROW)Marshal.PtrToStructure(buffSubPointer, typeof(MIB_TCPROW)); //copy struct data buffSubPointer = (IntPtr)((int)buffSubPointer + sizeOfTCPROW); //move to next structdata } return tcpRows; } catch (Exception ex) { throw new Exception("getTcpTable failed! [" + ex.GetType().ToString() + "," + ex.Message + "]"); } finally { if (allocated) Marshal.FreeCoTaskMem(buffer); //Free the allocated memory } }
internal static extern uint GetPerTcpConnectionEStats(ref MIB_TCPROW Row, TCP_ESTATS_TYPE EstatsType, IntPtr Rw, uint RwVersion, uint RwSize, IntPtr Ros, uint RosVersion, uint RosSize, IntPtr Rod, uint RodVersion, uint RodSize);
internal static extern uint SetPerTcpConnectionEStats(ref MIB_TCPROW Row, TCP_ESTATS_TYPE EstatsType, IntPtr Rw, uint RwVersion, uint RwSize, uint Offset);
private static extern int SetTcpEntry(ref MIB_TCPROW pTcpRow);