14 from binascii
import unhexlify, hexlify
17 STATE_ESTABLISHED =
'01' 20 STATE_FIN_WAIT1 =
'04' 21 STATE_FIN_WAIT2 =
'05' 22 STATE_TIME_WAIT =
'06' 24 STATE_CLOSE_WAIT =
'08' 31 Get list of socket inodes for process pid. 33 base =
'/proc/%i/fd' % pid
35 for item
in os.listdir(base):
36 target = os.readlink(os.path.join(base, item))
37 if target.startswith(
'socket:'):
38 inodes.append(int(target[8:-1]))
42 return [x
for x
in array
if x !=
'']
45 host,port = array.split(
':')
47 host = unhexlify(host)
49 for x
in range(0, len(host) // 4):
50 (val,) = struct.unpack(
'=I', host[x*4:(x+1)*4])
51 host_out +=
'%08x' % val
53 return host_out,int(port,16)
57 Function to return a list with status of tcp connections at linux systems 58 To get pid of all network process running on system, you must run this script 61 with open(
'/proc/net/'+typ,
'r') as f: 62 content = f.readlines() 67 tcp_id = line_array[0]
71 inode = int(line_array[9])
72 nline = [tcp_id, l_addr, r_addr, state, inode]
78 Get bind addresses as (host,port) tuples for process pid. 83 if conn[3] == STATE_LISTEN
and conn[4]
in inodes:
84 bind_addrs.append(conn[1])
90 Return all interfaces that are up 92 is_64bits = sys.maxsize > 2**32
93 struct_size = 40
if is_64bits
else 32
94 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
97 bytes = max_possible * struct_size
98 names = array.array(
'B', b
'\0' * bytes)
99 outbytes = struct.unpack(
'iL', fcntl.ioctl(
102 struct.pack(
'iL', bytes, names.buffer_info()[0])
104 if outbytes == bytes:
108 namestr = names.tostring()
109 return [(namestr[i:i+16].split(b
'\0', 1)[0],
110 socket.inet_ntoa(namestr[i+20:i+24]))
111 for i
in range(0, outbytes, struct_size)]
115 Convert string IPv4 or IPv6 address to binary address as returned by 117 Very naive implementation that certainly doesn't work for all IPv6 variants. 120 addr = [int(x)
for x
in addr.split(
'.')]
124 addr = addr.split(
':')
125 for i,comp
in enumerate(addr):
127 if i == 0
or i == (len(addr)-1):
133 sub[x].append(val >> 8)
134 sub[x].append(val & 0xff)
135 nullbytes = 16 - len(sub[0]) - len(sub[1])
136 assert((x == 0
and nullbytes == 0)
or (x == 1
and nullbytes > 0))
137 addr = sub[0] + ([0] * nullbytes) + sub[1]
139 raise ValueError(
'Could not parse address %s' % addr)
140 return hexlify(bytearray(addr)).decode(
'ascii')
144 Check for (local) IPv6 support. 151 s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
152 s.connect((
'::1', 0))
def _convert_ip_port(array)
def get_socket_inodes(pid)