c - How to get the pid of a process that is listening on a certain port programmatically? -


i have write snmp module monitor server application have written too. problem have know if application running , should able kill whenever can.

i know port application listening (reading application configuration file) , can try bind port socket in order know if (or isn't) being used application or enough module. here code:

int get_server_status() {         struct sockaddr_in local;         int port,sockfd;          if (parse_config_file(&port,null,config_file_path) == -1)                 return -1; //error          if ((sockfd = socket ( af_inet, sock_stream, 0 )) < 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 *) &local, sizeof (local) ) < 0 ){                 if(errno == eaddrinuse)                         return 1; //port being used                 else                         return -1; //error         }else{                 close(sockfd);                 return 0;         //port not being used          } } 

the problem comes when need kill application, don't know neither pid nor how it. can using netstat -tln <port>but don't know how programmatically. ideas??

like netstat, should read /proc/net/tcp.

interpreting it:

  1. the second field, titled local_address, ip , port. 00000000:0050 http (the port number in hex).
  2. the 4th field, titled st, state. a tcp_listen.
  3. the 10th field, titled inode inode number (decimal time).
  4. for each process, /proc/pid/fd/ contains entry each open file descriptor. ls -l socket descriptors shows it's link socket:[nnnnnn]. number nnnnnn should match inode number /proc/net/tcp.

this makes finding process quite tiresome, possible.
finding right line in /proc/net/tcp isn't difficult, , can inode number.
finding process requires scan processes, looking 1 refers inode number. know no better way.


Comments

Popular posts from this blog

django - How can I change user group without delete record -

java - Need to add SOAP security token -

java - EclipseLink JPA Object is not a known entity type -