i am trying to create a windows service,in the config file i will list out various ports and their numbers,i want to monitor these ports and record the ports starting time,process id, end time whenever any request is coming for those ports listed in config file.
can anyone tell how to move to create the service?

Dani AI

Generated

Short summary and practical plan (builds on 's config idea):

You need two distinct capabilities: (A) a reliable way to discover “someone just opened a connection on port X and which process owns it” and (B) a reliable way to record start time, PID, and end time. Storing the watched ports in config (as suggests) is fine; keep the list simple (comma-separated appSetting or a small JSON blob) so the service can reload it at runtime.

Simplest, reliable approach (recommended for prototypes)

  • Poll the OS TCP/UDP tables and map entries to owning PIDs (Windows IP Helper API: GetExtendedTcpTable / GetExtendedUdpTable). Poll at a configurable interval, maintain an in-memory set of current connections, detect additions (record start time + PID + process name) and removals (record end time). This works without touching the target process and works for ports used by other processes.

Minimal algorithm (pseudocode)

timer interval = 500ms
on timer:
  entries = GetExtendedTcpTable()
  watched = entries where localPort in configuredPorts
  for each e in watched:
    key = (localIP,localPort,remoteIP,remotePort,e.pid)
    if not openConnections.ContainsKey(key):
      openConnections[key] = now
      LogStart(key, e.pid, Process.GetProcessById(e.pid).ProcessName)
  for each key in openConnections not in watched:
    LogEnd(key, start=openConnections[key], end=now)
    remove key

Notes, tradeoffs and improvements

  • Polling can miss very short connections or be CPU-heavy at very low intervals. For high-volume or production, switch to an event-driven source: ETW (kernel TCP/IP provider) or the Windows Filtering Platform (WFP) give connect/accept/close events and scale far better, but require admin privileges and more code. The TraceEvent library (TraceEvent/ETW) makes ETW consumer code simpler.
  • UDP is connectionless: packet-level capture (Npcap/WFP) or inspecting listening sockets is needed instead of TCP-table logic.
  • Always record local/remote IPs, PID, process start time (to detect PID reuse), and a unique connection key so short-lived PIDs or recycled PIDs don’t produce incorrect matches.
  • Run the monitor service with sufficient privileges to call IP helper/ETW/WFP APIs, and implement log rotation and retention to avoid unbounded disk growth.

You can create you own configurations' sections to store data in the config file then to retrieve them at the appropriate time:
open the config file then add those tags

<configuration>
  <configSections>
    <section name="Port1" 
             type="F.PortsSectionHandler.PortSectionHandler, 
             F, 
             Version=1.0.0.0, 
             Culture=neutral, 
             PublicKeyToken=null" 
             allowLocation="true" 
             allowExeDefinition="MachineToApplication" 
             restartOnExternalChanges="false"/>
  </configSections>

  <Port1 key="Account" serial="9000"/>
</configuration>

Supposing,Of Corse that the port parameters are key and serial key ="Account" and serial="9000", it's just an example you can put any other values or add/retreieve attributes according to your needs
Once the data is stored in the config file, you can retrive and manage them programmatically as so

 /* This code provides access to configuration files using OpenMappedExeConfiguration
  , method. You can use the OpenExeConfiguration method instead. For further   informatons
, consult the MSDN, it gives you more inforamtions about config files access methods*/
ExeConfigurationFileMap oConfigFile = new ExeConfigurationFileMap();
oConfigFile.ExeConfigFilename = Application.StartupPath + "\\AppConfig.exe.config";
Configuration oConfiguration = ConfigurationManager.OpenMappedExeConfiguration(oConfigFile, ConfigurationUserLevel.None);

/* create a PortSectionHandler object and use oConfiguration.GetSection method 
 to get the targeted section  */
 try
 {
  PortsSectionHandler.PortSectionHandler oSection = 
  oConfiguration.GetSection("Port1") as PortsSectionHandler.PortSectionHandler;
/* Those ares the key and the serial values of our customized section you can use them to achive your purposes */
                KeyValue = oSection.Key;
                SectionValue = oSection.Serial;
 }

// If there is not a corresponding section, then the exception is raised

catch (NullReferenceException caught) { MessageBox.Show(caught.Message); }

}

but before all that you must define a derived class from the Configuration section class witch is an abstract class and add all attributes your neeed for your port, here is an example you can modify it to suite your needs by adding or retrieving properties Of Corse.

public class PortSectionHandler : ConfigurationSection
{
   //First constructor
   public PortSectionHandler() { }
   //Second constructor
   public PortSectionHandler(string SectionName,string Key, string Serial)
            {
                this.SectionName = SectionName; this.Key = Key; this.Serial = Serial;
            }

   //First property: SectionName
            private string _SectionName;
            public string SectionName
            { get { return _SectionName; } set { _SectionName = value; }}
   //Second property: The port Key
          [ConfigurationProperty("key", DefaultValue = "Account", IsRequired = true)] 
          [StringValidator(InvalidCharacters = "|~!@#$%^&*()[]{}/;'\\",MinLength = 1)] 
            public string Key
            { get { return (string)this["key"]; }set { this["key"] = value; }}
   //Third property: The port serial
          [ConfigurationProperty("serial", DefaultValue = "9000",IsRequired = true)]
          [StringValidator(InvalidCharacters = "|~!@#$%^&*()[]{}/;'\\", MinLength = 1)]
            public string Serial
            {get { return this["serial"] as string;}set {this["serial"] = value;}}

 }

Remember that the bold parameter corespond to the namespace of the above defined class and the red colored one corespond to the above derived class name

<configSections>
    <section name="Port1" 
             type="[B]F.PortsSectionHandler[/B].[COLOR="Red"]PortSectionHandler[/COLOR], 
             F, 
             Version=1.0.0.0, 
             Culture=neutral, 
             PublicKeyToken=null" 
             allowLocation="true" 
             allowExeDefinition="MachineToApplication" 
             restartOnExternalChanges="false"/>
  </configSections>

I know it's a little bit advanced but I you need helps on that you can write me back

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.