Recipe 6.12. Viewing the Network Ports a Process Has OpenProblemYou want to view the network ports on which a process is communicating. This is useful if you want to see the type of traffic a particular process is generating. SolutionUsing a graphical user interface
Using a command-line interfaceThe following command displays the open ports and the process ID of the process associated with the port. The -o option is new to netstat.exe in Windows XP and Windows Server 2003: > netstat -o The Sysinternals netstatp.exe command is similar to netstat.exe, except it displays the process name associated with each port: > netstatp And for yet another extremely useful port querying tool, check out portqry.exe (see MS KB 310099 for more information). With portqry you can get even more information than netstatp. Run this command to output all of the ports and their associated processes: > portqry -local That command also breaks port usage down by service (e.g., DnsCache). You can watch the port usage for a particular PID and log it to a file. The following command does this for PID 1234: > portqry -wpid 1234 -wt 5 -l portoutput.txt -v The -wt defines the watch time, which is how long portqry waits before examining the process again (the default is 60 seconds). The -v option is for verbose output. Using VBScriptNone of the scripting interfaces provide a way to access information about the ports a process has open. However, the netstatp tool comes with complete source that shows how to do it via IP Helper functions that can be directly accessed with a non-scripting language. DiscussionEach connection to and from a client computer is associated with a process. This connection is also associated with a particular port. Most of the open ports you'll see will be numbered above 1024. This is because well-known ports use port numbers lower than 1024 so Windows dynamically allocates ports above that. A connection has a state, which you'll see when running any of the utilities described in the solution. This state indicates the type of activity going on over the connection. Most of the connections you'll see are in the ESTABLISHED state, which simply means the connection is open and prepared to send or receive traffic. For a list of all the states, see Table 6-4.
See AlsoMS KB 137984 (TCP Connection States and Netstat Output) and MS KB 310099 (Description of the Portqry.exe Command-Line Utility) |