|
I have no problem executing NETSTAT and capturing its output through the Process class, with redirected outputs, done properly (i.e. with 2 extra threads, using Read, not ReadTillEnd or whatever it is called). Works fine, e.g. on .NET 2.0 and Vista.
Luc Pattyn [My Articles] Nil Volentibus Arduum
Fed up by FireFox memory leaks I switched to Opera and now CP doesn't perform its paste magic, so links will not be offered. Sorry.
|
|
|
|
|
Do you get PIDs with your netstat? Can you pull each item individually? What I mean is could you do something like (please pardon the pseudo-code)
foreach entry in netstat
proto = protocol
LocalIP = Local Address
LocalPort = LocalIPPort
RemoteIP = Foreign Address
RemotePort = RemoteIPPort
State = State
PID = ProcessID
I was trying to use a streamreader writing to a stringbuiler.appendline but I kept getting the whole list instead of individual entries
|
|
|
|
|
Perhaps use a Regular Expression:
C:\Projects\Utilities>regex "^(?'Proto'\S+)\s+(?'LocalIP'[^:]+): ( ?'LocalPort'\S+)\s+(?'ForeignIP'[^:]+): ( ?'ForeignPort'\S+)\s+(?'State'\S+)\s+(?'PID'\S+)$" "TCP 10.37.47.44:40091 hcc-l-sqld-001:1952 ESTABLISHED 8808"
0 = TCP 10.37.47.44:40091 hcc-l-sqld-001:1952 ESTABLISHED 8808
Proto = TCP
LocalIP = 10.37.47.44
LocalPort = 40091
ForeignIP = hcc-l-sqld-001
ForeignPort = 1952
State = ESTABLISHED
PID = 8808
Only tested a little bit with a very simple utility.
Edit: Some spacing added to avoid smilies.
modified 3-Feb-12 17:39pm.
|
|
|
|
|
No there is no guarantee that you will get results line by line; all you can hope for is to get all the output almost in real-time. In reality I think you normally get one or more entire lines at a time. You could easily capture it all into one string, then apply string.Split() on '\n' (and ignore '\r' that you are likely to get as well).
Luc Pattyn [My Articles] Nil Volentibus Arduum
Fed up by FireFox memory leaks I switched to Opera and now CP doesn't perform its paste magic, so links will not be offered. Sorry.
|
|
|
|
|
CCodeNewbie wrote: I was trying to use a streamreader writing to a stringbuiler.appendline but I kept getting the whole list instead of individual entries
Building a string out of multiple lines will of course give you just a string.
Instead you use StreamReader to do one of the following
1. Process each line as it is read.
2. Put each line into a collection like a list.
|
|
|
|
|
Thanks for all you comments/ideas but I am still struggling although making progress.
@PIEBALDconsult, I really like the regex idea but can't figure out how to pipe the ouput into you code.
@Luc, jschell - prior to investigating iphlpapi I was trying the Process method and have now gone back to that thanks to your suggestions. Th issues I am having though
- I still can't get the individual items to writeline or to a list
- I can't work out why connections[1]-[6] aren't populated.
- I need to connections[1].split(':') to split the host and the local port
- I need to connections[3].split(':') to split the host and the local port
- I can't get rid of the newlines between the split entries.
My code follows:
Process Ns = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo("netstat");
startInfo.Arguments = "-ao";
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.CreateNoWindow = true;
Ns.StartInfo = startInfo;
Ns.Start();
for (int i = 0; i < 4; i++)
Ns.StandardOutput.ReadLine();
while (true)
{
string Line = (Ns.StandardOutput.ReadLine());
string[] split = Line.Split(' ');
foreach (string s in split)
{
List<string> connections = new List<string>();
connections.Add(s);
if (s != "" || s != Environment.NewLine)
{
Console.WriteLine("Protocol:", connections[0]);
Console.WriteLine("LocalIP:", connections[1]);
Console.WriteLine("LocalPort:", connections[2]);
Console.WriteLine("RemoteIP:", connections[3]);
Console.WriteLine("RemotePort:", connections[4]);
Console.WriteLine("State:", connections[5]);
Console.WriteLine("PID:", connections[6]);
}
}
}
|
|
|
|
|
All you'll get from me are a few pointers:
0. programs tend to do what you ask them to do, which might be different from what you think you asked for.
1. Part of your code is working fine, another part is not. You should inspect intermediate values to determine which parts are which. That is called debugging.
2. When a .NET class or method isn't doing what you expected from it, then it is time to read the documentation.
3. There are several ways to fix what is wrong, some will suggest using Regex. I'm not one of them.
4. I'm baffled by your use of List<string> connections ; it seems like a fancy way of turning an array into a list, then using it as if it were an array. I'm not saying anything is wrong here, however it is peculiar.
5. BTW: if (s != "" || s != Environment.NewLine) is utterly wrong for many reasons, one of them being ReadLine() normally doesn't return something that contains a NewLine string.
Luc Pattyn [My Articles] Nil Volentibus Arduum
Fed up by FireFox memory leaks I switched to Opera and now CP doesn't perform its paste magic, so links will not be offered. Sorry.
|
|
|
|
|
OK, I'm lost...
Having not worked out how to get the members of the "string Line" array, despite trying "string [] Line" I have succumbed to reducing the string though string manipulation. What I can't figure out is how to get rid of the newline-like spaces between the split strings so that I can add those strings to a List<>.
Can anyone help? Please?
Process Ns = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo("netstat");
startInfo.Arguments = "-ao";
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.CreateNoWindow = true;
Ns.StartInfo = startInfo;
Ns.Start();
for (int i = 0; i < 4; i++)
Ns.StandardOutput.ReadLine();
while (true)
{
string Line = (Ns.StandardOutput.ReadLine().Trim());
string[] s = Line.Split(':');
foreach (string a in s)
{
string[] t = a.Split(' ');
foreach (string b in t)
{
string u = b.Replace(" ","");
if (b != Environment.NewLine)
{
Console.WriteLine(b.ToString());
Console.ReadLine();
}
}
}
}
Thank you.
|
|
|
|
|
Some questions:
1. half of the code shown is about getting some process results; is that working? if it is, why still show it? if not, what is happening?
2. the other half is about dealing with some strings you got. The least you should do is show some of them so people can make suggestions.
3. why was there "P/Invoking" in the subject line?
Some facts:
1. once you do string[] t = a.Split(' '); there will not be any space in array t, therefore the one comment you have shown does not make sense.
2. the spaces are there to make the NETSTAT output look tabular; by splitting or otherwise removing the spaces, you are throwing away information. Therefore that is the wrong approach.
3. You still have a silly test for Environment.NewLine! Do you actually understand what you are doing, or are you just throwing some code together at random?
Some advice:
1. When a problem is too big to solve, split it into smaller, more manageable problems; then tackle those, one by one.
2. What you really want is replace all consecutive spaces by a single space. Then life suddenly gets easy. So work on that.
3. Do read the replies you get.
Luc Pattyn [My Articles] Nil Volentibus Arduum
Fed up by FireFox memory leaks I switched to Opera and now CP doesn't perform its paste magic, so links will not be offered. Sorry.
|
|
|
|
|
Have you tried loading the code into a VS2005 or later console app?
Qustions:
1) The process part runs perfectly and the output to console is as per a cmd-based netstat.
Process Ns = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo("netstat");
startInfo.Arguments = "-ao";
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.CreateNoWindow = true;
Ns.StartInfo = startInfo;
Ns.Start();
for (int i = 0; i < 4; i++)
Ns.StandardOutput.ReadLine();
while (true)
{
string Line = (Ns.StandardOutput.ReadLine().Trim());
Console.Writeline(Line);
produces
TCP-----robin:epmap---------robin.abc.xyz: 0-----LISTENING-----------948 (hyphens represent "spaces") as you quite rightly say, in tabular format.
what I am trying to do is separate each field (i.e. TCP / robin / epmap / robin.abc.xyz / 0 / LISTENING / 948 so that I can write each entry into a SQL db. with columns protocol/localhost/localport/remotehost/remoteport/state/PID.
2) it would probably be easier to see what the problem is if you copied and pasted the code into a console application (I am running VS2005 on WinXP), but as you may see from the above output, there are "spaces" in between the fields. Despite my best efforts in doing this:
string Line = (Ns.StandardOutput.ReadLine().Trim());
string[] s = Line.Split(':');
foreach (string a in s)
{
string[] t = a.Split(' ');
foreach (string b in t)
{
string u = b.Replace(" ","");
{
Console.WriteLine(b.ToString());
Console.ReadLine();
}
}
}
I get this:
TCP
robin
epmap
robin.abc.xyz
0
LISTENING
948
(shown here as appears in the debug console)
Only problem is that they are not spaces, tabs, newlines or anything else that I can edit out. I have to assume that the are whitespace that is actually part of the field but I need to get rid of it and don't know how (despite ~24 hours of research)
3) After days of research, nearly every net search I did on c# netstat pointed to using p/invoke to be able to get the netstat details with PID mappings, thus my referral to http://files.codes-sources.com/fichier.aspx?id=11430&f=easy_socket\iphelper.cs[^]
Facts:
1) I am doing a split so that I can separate out the fields, if there is a better way please point me to it. There does seem to be some sort of "padding" in the array as you can see from the above output.
2) The spaces contain no valuable information and need to be removed so they can be written into a db. I don't want/need to display them in a console or a form.
3) I know the previously posted code contained a newline test. The code was uploaded after I reached my wits end trying to figure out how to get rid of the "padding". I should probably have edited that line out.
Advice
1) The problem is "how do I get these pieces of information into a usable state?" I don't have the knowledge/experience in solving that problem and many hours on msdn, this site and dozens of others has not yielded a solution. That's why I asked.
2) If I knew how to do that, or could find a site that says something other that
string u = b.Replace(' ',string.Empty), string u = b.Replace(" ","") or some combination of those that actually worked, I wouldn't be asking the question.
3) I do actually read the replies. I spent hours yesterday and today trying to work out/research how to extract the individual members of the string [] Line array but could not get anything other that Console.Writeline(s[0]) to display. I expect I was initialising the array incorrectly but eventually gave up and went back to basic string manipulation to try and get a result. Unfortunately the replies are sometimes above my head (which leads me to ask more questions) or a just someone's best guess.
I hope the above has sufficient detail for you and look forward to your reply.
Thank you Luc.
|
|
|
|
|
1.
CCodeNewbie wrote: Have you tried loading the code into a VS2005 or later console app?
Nope. That is your job. However I can read code and see what it does, and where it is wrong.
2.
I can assure you the white space in NETSTAT's output consists of regular space characters, ASCII 0x20, Unicode 0x0020.
The only surprise you may get, depending on how you do things, is a single unexpected carriage-return character per line (ASCII 0x0D, or '\r'). And that is because on Windows a newline operation may consist of carriagereturn + linefeed, and you might splitting on (and swallowing) linefeeds, leaving the carriage-returns in place.
3.
How many array elements do you expect from the following:
string[] parts="ABBBC".Split('B');
Now check it.
And if you were to replace every B in the above line by a space, would that change anything?
4.
Any idea what the following code does:
string s="some silly text of arbitrary length";
s=s.Replace(" "," ");
s=s.Replace(" "," ");
s=s.Replace(" "," ");
s=s.Replace(" "," ");
s=s.Replace(" "," ");
s=s.Replace(" "," ");
string[] words=s.Split(' ');
And why the last few Replace statements are there at all?
5.
in
TCP 0.0.0.0:135 SOMENAME:0 LISTENING 1288
which one is the major separator, the colon or the space? work on the major one first.
don't even spend a second of your time on a secondary separator as long as you haven't fully mastered the major separator.
6.
This is my last entry in this thread. Text, explanations and code by far exceed what this little problem warrants already.
Luc Pattyn [My Articles] Nil Volentibus Arduum
Fed up by FireFox memory leaks I switched to Opera and now CP doesn't perform its paste magic, so links will not be offered. Sorry.
|
|
|
|
|
Thank you for your time Luc. It is appreciated.
|
|
|
|
|
Hi,
when I call SerialPort.Close() it hangs ie. it never returns.
In an attempt to get it working I tried..
try
{
_port.DiscardInBuffer();
_port.DiscardOutBuffer();
_port.BaseStream.Close();
_port.Close();
}
catch (Exception e)
{
MessageBox.Show(e.Message, @"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
Now the call to BaseStream.Close() hangs.
It is posible that data is beeing sent to the port when I make the call, I have no control over this, but I should still be able to close the port, right?
Any ideas?
Thanks - John.
“If I had asked people what they wanted, they would have said faster horses.”
― Henry Ford
|
|
|
|
|
|
|
Hi ,
What is the best method for putting a wait in execution.Thread.Sleep() will raise parasoft warnings and its not a good way to use Thread.Sleep every where.Is there any other ways ?
Waith warm regards.
|
|
|
|
|
Don't.
If you pause your application, then your UI will stop responding.
Consider instead moving any intensive work to a separate thread, or using a Timer to "wait" for when you should do something. Sleeping thread should only really be used when the thread has nothing to do until the outside world causes a change.
Ideological Purity is no substitute for being able to stick your thumb down a pipe to stop the water
|
|
|
|
|
If I use AutoResetEvent.WaitOne() , my Static Code Analysis will throw an error for making use of the returning value of WaitOne.Confused!!!!!!!!!!!
|
|
|
|
|
I can understand that. From MSDN:
Return Value
Type: System.Boolean
true if the current instance receives a signal. If the current instance is never signaled, WaitOne never returns. Clearly your SCA knows this, and deems it a waste of time checking a result that can never be false! Which of course, it is...
Ideological Purity is no substitute for being able to stick your thumb down a pipe to stop the water
|
|
|
|
|
You should almost never have an explicit wait. Instead, you should be listening for events which you want to do some action in response to. If you're waiting for another task to complete then you should use WaitHandles, but it's generally better to listen for events.
|
|
|
|
|
Waiting is in general a bad idea, and timing the actions of your software is the way to madness.
Can you tell us why you need to wait, or on what specifically? Are you waiting for a signal, such as user-input? Waiting until a process is finished? Waiting until there's data on the socket?
If you tell us what you are waiting on, we could perhaps provide an alternative that doesn't involve waiting.
Bastard Programmer from Hell
|
|
|
|
|
Hi guys,
1) Do you know if is it possible to play a Dvd in a MediaElement Control? Otherwise do you can suggest me for another way(like to convert the Dvd in a supported video format)?
2) Do you know how to cut a video fragment from a supported video format(such as myvideo.avi) and save it(such as Part1ofmyvideo.avi) ?
Thanks
PS: Sorry for my English
|
|
|
|
|
|
Now remember, this is an interview question , so stuff like databases, etc. are irrelevant... they were testing my data structure knowledge .
Say you are working for the DMV and need to write a function that checks available license plates. Valid #'s are 0000000 to ZZZZZZZ (no variable length plates). That means there will be 36^7 = 78B possible #'s. Storing that in a packed bit array would require 9GB, so thats out .
Thought about storing a linked list of ranges, but if the range struct is ~20 to 30 bytes, once you get above around ~200M ranges, the packed bit array starts to look better.
Oh yeah, you can not assume they are handing out #'s sequentially, so it is possible that you'll end up with every other # taken = 39B ranges * 30 bytes = like 1000GB or something like that haha.
Point was, they didn't like the linked list answer too much because it didn't scale to handle the worst case or even beyond 200M ranges.
I had heard of interval trees before, but didn't know if they would solve the scaling issue.
|
|
|
|
|
repost!
Luc Pattyn [My Articles] Nil Volentibus Arduum
Fed up by FireFox memory leaks I switched to Opera and now CP doesn't perform its paste magic, so links will not be offered. Sorry.
|
|
|
|
|