How to find a free port in C#?
using System.Net.NetworkInformation
private string FreeTcpPort(int iStart, int iEnd)
{
int iFreePort = 0;
int iStartRange = iStart;
int iEndRange = iEnd;
IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
IPEndPoint[] tcpEndPoints = properties.GetActiveTcpListeners();
List<int> iPortsinUse= tcpEndPoints.Select(p => p.Port).ToList<int>();
for (int port = iStartRange; port < iEndRange; port++)
{
if (!iPortsinUse.Contains(port))
{
iFreePort = port;
break;
}
}
return iFreePort.ToString();
}
Below code requests first open port from the given range
FreeTcpPort(2000,3000)
How to find a port which are being used or not in Windows OS?
netstat -an | find ":portno"
Example: find a port no 2000 is in use. If its not in use then return empty value otherwise it return "LISTENTING" as mentioned below
netstat -an | find ":2000"
TCP 127.0.0.1:2000 0.0.0.0:0 LISTENING
How to see the statistics (how many packets received, sent, discard) of the bounded IP in a machine using C#?
using System.Net.NetworkInformation
private void IPDetails()
{
IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
IPGlobalStatistics ipDetails = properties.GetIPv4GlobalStatistics();
Console.WriteLine(" Inbound Packet Data:");
Console.WriteLine(" Received packets: {0}", ipDetails.ReceivedPackets);
Console.WriteLine(" Forwarded packets: {0}", ipDetails.ReceivedPacketsForwarded);
Console.WriteLine(" Delivered packets: {0}", ipDetails.ReceivedPacketsDelivered);
Console.WriteLine(" Discarded packets: {0}", ipDetails.ReceivedPacketsDiscarded);
}