title: How to get the pid of a process that is listening on a certain port programmatically?
body: <p>I have to write a SNMP module which monitor a certain server application that I have written too. The problem is that I have to know if this application is running and I should be able to kill it whenever I can. </p>
  
  <p>I know the port where the application is listening (reading the application configuration file) and I can try to bind this port to a socket in order to know if it is (or isn't) being used by my application or another which is enough for my module. Here is the code:</p>
  
  <pre><code>int
  get_server_status()
  {
          struct sockaddr_in local;
          int port,sockfd;
  
          if (parse_config_file(&amp;port,NULL,CONFIG_FILE_PATH) == -1)
                  return -1; //Error
  
          if ((sockfd = socket ( AF_INET, SOCK_STREAM, 0 )) &lt; 0)
                  return -1; //Error
  
          local.sin_family = AF_INET;
          local.sin_port = htons ( port );
          local.sin_addr.s_addr = inet_addr ("127.0.0.1");
  
          if (bind(sockfd, (struct sockaddr *) &amp;local, sizeof (local) ) &lt; 0 ){
                  if(errno == EADDRINUSE)
                          return 1; //Port being used
                  else
                          return -1; //Error
          }else{
                  close(sockfd);
                  return 0;         //Port not being used
  
          }
  }
  </code></pre>
  
  <p>The problem comes when I need to kill the application, I don't know neither its <code>PID</code> nor how to get it. I can get is using <code>netstat -tln &lt;port&gt;</code>but I don't know how to do it programmatically. Any ideas??</p>