progpib/vendortools/enumip.py

71 lines
1.8 KiB
Python
Raw Normal View History

2020-09-09 00:06:47 -05:00
import socket
import struct
import array
2020-09-26 00:29:14 -05:00
import sys
2020-09-09 00:06:47 -05:00
IOCTL_SIOCGIFCONF = 0x8912
# /*
# * Structure used in SIOCGIFCONF request.
# * Used to retrieve interface configuration
# * for machine (useful for programs which
# * must know all networks accessible).
# */
2020-09-26 00:29:14 -05:00
#
2020-09-09 00:06:47 -05:00
# struct ifconf {
# int ifc_len; /* size of associated buffer */
# union {
# caddr_t ifcu_buf;
# struct ifreq *ifcu_req;
# } ifc_ifcu;
2020-09-26 00:29:14 -05:00
#
2020-09-09 00:06:47 -05:00
# /*
# * Interface request structure used for socket
# * ioctl's.
# */
2020-09-26 00:29:14 -05:00
#
2020-09-09 00:06:47 -05:00
# struct ifreq {
# char ifr_name[16]; /* if name, e.g. "en0" */
# union {
# struct sockaddr ifru_addr;
# struct sockaddr ifru_dstaddr;
# struct sockaddr ifru_broadaddr;
# short ifru_flags;
# int ifru_metric;
# caddr_t ifru_data;
# } ifr_ifru;
2020-09-26 00:29:14 -05:00
#
#
2020-09-09 00:06:47 -05:00
# /* Socket address, DARPA Internet style */
# struct sockaddr_in {
# short sin_family;
# unsigned short sin_port;
# struct in_addr sin_addr;
# char sin_zero[8];
2020-09-26 00:29:14 -05:00
# };
2020-09-09 00:06:47 -05:00
#
#
# ioctl (fd, SIOCGIFCONF, &ifconf)
def enumIpUnix():
import fcntl
2020-09-26 00:29:14 -05:00
struct_size = 40 if (sys.maxsize > 2**32) else 32
inbytes = 128 * struct_size # Maximum 128 interfaces
ifreq = array.array('B', b'\0' * inbytes)
2020-09-09 00:06:47 -05:00
ifconf = struct.pack('iL', inbytes, ifreq.buffer_info()[0])
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
ifconf = fcntl.ioctl(s.fileno(), IOCTL_SIOCGIFCONF, ifconf)
2020-09-26 00:29:14 -05:00
2020-09-09 00:06:47 -05:00
outbytes = struct.unpack('iL', ifconf)[0]
2020-09-26 00:29:14 -05:00
iplist = [socket.inet_ntoa(ifreq[i+20:i+24]) for i in range(0,
outbytes,
struct_size)]
2020-09-09 00:06:47 -05:00
return [ip for ip in iplist if ip != '127.0.0.1']