How can I get the tcp dynamicport with C# .Net Core 6?
like the result of command :
"netsh int ipv4 show dynamicport tcp" in windows
C:\Users\Zerek>netsh int ipv4 show dynamicport tcp
Protocol tcp dynamic port range
---------------------------------
Startup port : 49152
Number of ports : 16384
need the value of "Startup port" and "Number of ports"
I have checked the relevant materials of Microsoft, and found no relevant API and class provided
I'm not actually sure you can, I think you have to call netsh directly, which will only work on windows but if that's an option, maybe you could have a look at https://github.com/rpetz/SharpNetSH and extend it to your needs?
var process = new Process()
{
StartInfo = new ProcessStartInfo
{
FileName = "netsh",
Arguments = "int ipv4 show dynamicport tcp",
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true,
}
};
process.Start();
The code uses the System.Diagnostics namespace to execute the "netsh int ipv4 show dynamicport tcp" command and print the output to the console.
See this github post for the full code
Hope it helps
Related
I need to remove saved credentials of network shares from the windows cache programmatically.I searched for it but couldn't find a solution. But I solved this issue by executing the following statement in command prompt.
net use \\someloaction /del
Now i need to execute the cmd statement using asp.net c#.
I tried the following code. But its not working.
var startInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
RedirectStandardInput = true,
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
var process = new Process { StartInfo = startInfo };
process.Start();
process.StandardInput.WriteLine("net use \somelocation /del");
process.StandardInput.WriteLine("exit");
process.WaitForExit();
You should use the Arguments property of ProcessStartInfo class.
The /C flag serves to pass the arguments to the Shell Command Processor for execution otherwise it will close immediately.
var startInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = #"/C net use \\somelocation /del",
UseShellExecute = false,
CreateNoWindow = true
};
However, the NET USE .... /D command doesn't remove the CREDENTIALS stored for your user to access the network share. If you need to remove the credentials, forcing the user to reinsert them the next time that he/she wants to use the shared resource you need to work with the Credential Manager.
The problem is that this library has no official managed implementation (AFAIK). So you need to use a plugin library that you can download from here or use the NuGet install with the command Install-Package CredentialManagement
So, after removing the sharing with the previous NET USE command, you could write in your code something like this
Credential cm = new Credential(#"\\server\share","", #"server");
cm.Delete();
You could find another question about this at this link
(Tried this library and I am able to clear the credentials to access a shared network on my lan using a command prompt. I hope the same happens on your side)
I'm currently trying to pipe multiple parameters to the adb.exe file in the google sdk. an example of my inputs are:
adb shell getprop ro.build.version.release
adb shell getprop ro.product.brand
which are outputting correct from my application. Though, the problem is I want to populate a list view of information, the problem that i'm currently encountering though, is the method to pipe commands to get desired output. I've currently got:
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "Resources/adb.exe",
Arguments = "devices",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
proc.Start();
string Output = proc.StandardOutput.ReadToEnd().ToString();
This currently returns as expected, but i'm wishing to get multiple results from piping something like:
Arguments = "devices ro.build.version.release ro.product.brand"
This provides no avail, even when piping directly into command prompt.
adb shell getprop devices ro.build.version.release ro.product.brand
empty, I have come around with a (assumingly) load heavy solution, which is to move the initialization of the executional into it's own function to be called multiple times. See code below:
public string GetInfo(string CommandArg)
{
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "Resources/adb.exe",
Arguments = CommandArg,
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
proc.Start();
return proc.StandardOutput.ReadToEnd().ToString();
}
public void SetDefineInformation()
{
AndroidVersion = decimal.Parse(GetInfo("ro.build.version.release"));
DeviceModel = GetInfo("ro.product.device");
...
}
To me, this seems like a load heavy task with constantly opening a single executable for it to close then re-open until the task is complete. Is there an overall work around, which might allow one to pipe multiple parameters to an executional and get the desired results?
adb can start a shell so you could create the shell with adb shell then redirect stdin and stdout to write to it directly
No measurable performance gain would come from the "optimization" you are proposing. The adb code is pretty efficient. The overhead it introduces is very minimal. Specially in the client part. Most of the delay comes from waiting for the device's response anyway.
So stop overcomplicating things and just run multiple adb shell sessions. If loading the adb binary bothers you so much - just use sockets to talk to the adb server directly. Take a look at the Mad Bee library code to see how to do it in c#. Or just use the library.
As for optimizing querying multiple system properties - just use adb shell getprop command to pull all properties at once.
I am trying to create the following functionality in inno setup.
The user is asked to enter a port they wish my application to communicate on.
Once they have entered a port they can hit a check button.
This check button will run some code to see whether the port on the installation machine is available.
So far I am fine with creating the input box for the user to enter the port they wish to test. I have the following code to test whether the port is available.
int port = 456; //<--- This is your value
bool isAvailable = true;
// Evaluate current system tcp connections. This is the same information provided
// by the netstat command line application, just in .Net strongly-typed object
// form. We will look through the list, and if our port we would like to use
// in our TcpClient is occupied, we will set isAvailable to false.
IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();
foreach (TcpConnectionInformation tcpi in tcpConnInfoArray)
{
if (tcpi.LocalEndPoint.Port == port)
{
isAvailable = false;
break;
}
}
Console.WriteLine("Port is available");
My first question is: is it possible to return to inno setup the true or false value from the port test code? If its false then I need to let the user know.
My second question is: is the port test code correct?
My third question is: am I right in thinking I will then potentially need to open that port in the firewall.
In relation to the link below
https://stackoverflow.com/questions/5577406/enable-both-lan-intranet-and-usb-internet
Is there a way to do it using a c# programmatically ?
Here is a Code Project article that shows you how to do it:
http://www.codeproject.com/KB/IP/winnetstat.aspx
Basically, you use the IP Helper API and the SetIpForwardEntry method to accomplish this.
Here is an article that walks you through how to implement it (with accompanying code):
http://www.developer.com/ws/pc/article.php/10947_3415521_2/IP-Helper-API-ARP-Routing-and-Network-Statistics.htm
Though the question was answered about 7 years ago, I found a VERY easy way to do this in C# using netsh.exe.
This only works if you are running your program as administrator.
The command is:
netsh.exe interface ipv4 set interface "myNICsName" metric=20
To set the metric to 'Automatic' just set it to 0.
The high limit is 9999, but if you use something higher, it will just set it to 9999 for you.
To do this programatically, just use Process.Start in the following way:
System.Diagnostics.Process p = new System.Diagnostics.Process
{
StartInfo =
{
FileName = "netsh.exe",
Arguments = $"interface ipv4 set interface \"{nicName}\" metric={metric}",
UseShellExecute = false,
RedirectStandardOutput = true
}
};
bool started = p.Start();
if (started)
{
if (SpinWait.SpinUntil(() => p.HasExited, TimeSpan.FromSeconds(20)))
{
Log.Write($"Successfully set {nicName}'s metric to {metric}");
Log.Write($"Sleeping 2 seconds to allow metric change on {nicName} to take effect.");
Thread.Sleep(2000);
return true;
}
Log.Write($"Failed to set {nicName}'s metric to {metric}");
return false;
}
The above code also does some error checking to make sure the process indeed started and puts in a short delay so that the metric change can have a chance to take effect. I found that I had some problems in my code when I didn't include the delay.
Is there a managed class/method that would provide the TCP port number(s) used by a particular Windows processes?
I'm really looking for a .NET equivalent of the following CMD line:
netstat -ano |find /i "listening"
Except for PID, take a look this:
IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
IPEndPoint[] endPoints = ipProperties.GetActiveTcpListeners();
TcpConnectionInformation[] tcpConnections =
ipProperties.GetActiveTcpConnections();
foreach (TcpConnectionInformation info in tcpConnections)
{
Console.WriteLine("Local: {0}:{1}\nRemote: {2}:{3}\nState: {4}\n",
info.LocalEndPoint.Address, info.LocalEndPoint.Port,
info.RemoteEndPoint.Address, info.RemoteEndPoint.Port,
info.State.ToString());
}
Console.ReadLine();
Source: Netstat in C#
A bit more research bring this: Build your own netstat.exe with c#. This uses P/Invoke to call GetExtendedTcpTable and using same structure as netstat.
See here for an equivalent of netstat in C#: http://towardsnext.wordpess.com/2009/02/09/netstat-in-c/
Update: Link is broken, but here's an equivalent: http://www.timvw.be/2007/09/09/build-your-own-netstatexe-with-c
Update: The original page has been archived at the Wayback Machine.