#include <stdio.h>
#include <stdlib.h>
#define TEMP_BUFFER_SIZE 0x10000
/*
This function return a TCP port state.
The function use '/proc/net/tcp' file and parse it.
Example of /proc/net/tcp file that we are going to parse:
sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode
0: C0A8FEFD:006F 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 542 1 7e109620 300 0 0 2 -1
1: 7F000001:006F 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 541 1 7e109a80 300 0 0 2 -1
2: C0A8FEFD:EA1B 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 556 1 7e1091c0 300 0 0 2 -1
3: C0A8FEFD:EA1B C0A8FEFE:03E3 01 00000000:00000000 00:00000000 00000000 0 0 562 1 7e1084a0 21 0 0 10 -1
4: C0A8FEFD:033A C0A8FEFE:C73A 01 00000000:00000000 00:00000000 00000000 0 0 1724 1 7e108d60 21 0 0 10 -1
5: C0A8FEFD:1A04 C0A8FEFE:9223 06 00000000:00000000 03:00001682 00000000 0 0 0 3 7c0e2820
The 'st' column is the State of the connection (return value of function):
0: ???
1: ESTABLISHED
2: SYN_SENT
3: SYN_RECV
4: FIN_WAIT1
5: FIN_WAIT2
6: TIME_WAIT
7: CLOSE
8: CLOSE_WAIT
9: LAST_ACK
10: LISTEN
11: CLOSING
*/
int main()
{
char line_buffer[ TEMP_BUFFER_SIZE ];
FILE *fp;
int num;
unsigned int local_address_ip;
unsigned int rem_address_ip;
unsigned int local_address_port;
unsigned int rem_address_port;
unsigned int line_id;
unsigned int conn_state;
/* Open the mtd file */
if((fp=fopen( "/proc/net/tcp", "r" )) == NULL)
{
return 0;
}
/* Read first line of titles - ignored*/
if (fgets( line_buffer, TEMP_BUFFER_SIZE-1, fp ) == NULL)
{
fclose( fp );
return 0;
}
/* Read the file line by line*/
while ( fgets( line_buffer, TEMP_BUFFER_SIZE-1, fp ) )
{
num = sscanf(line_buffer,"%d: %X:%X %X:%X %X",&line_id,&local_address_ip,&local_address_port,&rem_address_ip,&rem_address_port,&conn_state);
printf("num (%d) line_buffer = %s\n",num,line_buffer);
printf("line_id (0x%X), local_address_ip (0x%X) , local_address_port (0x%X), rem_address_ip (0x%X), rem_address_port (0x%X), conn_state (0x%X)\n\n",line_id, local_address_ip, local_address_port, rem_address_ip, rem_address_port, conn_state);
if (num < 6)
{
fclose( fp );
return -1;
}
if (local_address_port == "0xAB19")
{
fclose( fp );
return 1;
}
}
/* close '/proc' file */
fclose( fp );
return 0;
}
0 意見:
張貼留言