Find out which service is being used on TCP C port#
I created a scan Port in C# (winforms), which is checking a range of ports, previously set, I can verify that the port is open, but my problem is the following: I know that the port is open, but I do not know what type of Service is running on this port, is there any function or library that I can check which service is running on these open ports??
public void StartScan(object o)
{
IPAddress ipAddress = o as IPAddress;
gridPortaAberta.Rows.Clear();
for (int i = startPort; i <= endPort; i++)
{
lock (consoleLock)
{
label5.Text = "Scaneando Porta: " + i;
}
while (waitingForResponses >= maxQueriesAtOneTime)
Thread.Sleep(0);
if (stop)
break;
try
{
Socket s = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
//Representa um ponto de extremidade de rede como um endereço IP e um número de porta.
s.BeginConnect(new IPEndPoint(ipAddress, i), EndConnect, s);
Interlocked.Increment(ref waitingForResponses);
}
catch (Exception)
{
}
}
}
public void EndConnect(IAsyncResult ar)
{
try
{
DecrementResponses();
List<string> items = new List<string>();
Socket s = ar.AsyncState as Socket;
s.EndConnect(ar);
if (s.Connected)
{
int openPort = Convert.ToInt32(s.RemoteEndPoint.ToString().Split(':')[1]);
openPorts.Add(openPort);
gridPortaAberta.Rows.Add(openPort.ToString());
lock (consoleLock)
{
Console.WriteLine("TCP conectado na porta: { 0}", openPort);
}
s.Disconnect(true);
}
}
catch (Exception)
{
}
}
public void IncrementResponses()
{
Interlocked.Increment(ref waitingForResponses);
PrintWaitingForResponses();
}
public void DecrementResponses()
{
Interlocked.Decrement(ref waitingForResponses);
PrintWaitingForResponses();
}
public void PrintWaitingForResponses()
{
lock (consoleLock)
{
label6.Text = "Esperando respostas de " + waitingForResponses + " threads";
}
}
1
Author: Rovann Linhalis, 2018-03-13
1 answers
You can use netstat -b
to get this information. You can run this command with Process.Start
and read the output returned by nestat to get the process + Port pair information. I made a small example.
public class UsedPort
{
public int Port { get; set; }
public string Process { get; set; }
}
public static IEnumerable<UsedPort> GetUsedPorts()
{
var process = Process.Start(new ProcessStartInfo("netstat", "-anb")
{
RedirectStandardOutput = true,
UseShellExecute = false
});
string line = null;
while ((line = process.StandardOutput.ReadLine()) != null)
{
if (line.IndexOf("TCP") >= 0 || line.IndexOf("UDP") >= 0)
{
var row = line.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
var localAddress = row[1];
var processName = process.StandardOutput.ReadLine();
if(!processName.Contains("Can not obtain ownership information")){
yield return new UsedPort
{
Port = int.Parse(localAddress.Split(':').Last()),
Process = processName
};
}
}
}
}
1
Author: Bruno Costa, 2018-03-14 10:21:01