Search code examples
c#.netippinvokeunmanaged

Manager IP Helper Functions in C# .NET


Can any one give any managed ip helper functions converted in c#.net? I know it should be written by PInvokeing.

Here is the IP Helper Functions : Microsoft

Will be grateful to you.

Here is an example:

public static TcpTable GetExtendedTcpTable(bool sorted)
    {
        List<TcpRow> tcpRows = new List<TcpRow>();

        IntPtr tcpTable = IntPtr.Zero;
        int tcpTableLength = 0;

        if (IpHelper.GetExtendedTcpTable(tcpTable, ref tcpTableLength, sorted, IpHelper.AfInet, IpHelper.TcpTableType.OwnerPidAll, 0) != 0)
        {
            try
            {
                tcpTable = Marshal.AllocHGlobal(tcpTableLength);
                if (IpHelper.GetExtendedTcpTable(tcpTable, ref tcpTableLength, true, IpHelper.AfInet, IpHelper.TcpTableType.OwnerPidAll, 0) == 0)
                {
                    IpHelper.TcpTable table = (IpHelper.TcpTable)Marshal.PtrToStructure(tcpTable, typeof(IpHelper.TcpTable));

                    IntPtr rowPtr = (IntPtr)((long)tcpTable + Marshal.SizeOf(table.length));
                    for (int i = 0; i < table.length; ++i)
                    {
                        tcpRows.Add(new TcpRow((IpHelper.TcpRow)Marshal.PtrToStructure(rowPtr, typeof(IpHelper.TcpRow))));
                        rowPtr = (IntPtr)((long)rowPtr + Marshal.SizeOf(typeof(IpHelper.TcpRow)));
                    }
                }
            }
            finally
            {
                if (tcpTable != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(tcpTable);
                }
            }
        }

        return new TcpTable(tcpRows);
    }

`

and here is the native function:

[DllImport(IpHelper.DllName, SetLastError = true)]
public static extern uint GetExtendedTcpTable(IntPtr tcpTable, ref int tcpTableLength, bool sort, int ipVersion, TcpTableType tcpTableType, int reserved);

Solution

  • You can check out pinvoke.net for that

    [DllImport("iphlpapi.dll", CharSet=CharSet.Ansi)]
    public static extern int GetAdaptersInfo(IntPtr pAdapterInfo, ref Int64 pBufOutLen);
    
    [DllImport("iphlpapi.dll", SetLastError=true)]
    static extern uint GetExtendedTcpTable(IntPtr pTcpTable, ref int dwOutBufLen, bool sort, int ipVersion, TCP_TABLE_CLASS tblClass,int reserved);