-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlsof-lite.c
executable file
·58 lines (45 loc) · 1.42 KB
/
lsof-lite.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <errno.h>
typedef struct sockaddr *sad; /* A necesary dummy typedef */
#define PORT 48006
int main()
{
int sock; /* Socket that will be bind */
struct sockaddr_in sin; /* Address Structure */
/* Create the socket */
/* PF_INET is the option for make a TCP socket.
You can try "man socket" for more info */
sock = socket( PF_INET, SOCK_STREAM, 0 );
/* The socket creation failed */
if ( 0 > sock ) {
perror( "socket" );
return ( -1 );
}
/* Address */
sin.sin_family = AF_INET;
sin.sin_port = htons( PORT ); /* htons() convert the number
to big endian */
sin.sin_addr.s_addr = INADDR_ANY;
/* We bind the socket to the port PORT to check if
the port is in use */
if ( 0 > bind( sock, (sad)&sin, sizeof( sin ) ) ) {
/* Bind failed, now we can check if the address is
in use */
if ( EADDRINUSE == errno ) {
/* We put the code necesary to manage this case */
printf( "The TCP port %d is in use.\n", PORT );
}
else
/* If the error were other than EADDRINUSE, we print it */
perror( "bind" );
}
/* If we arrive to this point, the port weren't in use and
we have it attached to our program. We can close
the socket or use it */
close( sock ); /* Close the socket */
return 0;
}