Python socket.AF_UNIX Examples
The following are 30
code examples of socket.AF_UNIX().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
socket
, or try the search function
.
Example #1
Source File: test_socketserver.py From ironpython2 with Apache License 2.0 | 8 votes |
def pickaddr(self, proto): if proto == socket.AF_INET: return (HOST, 0) else: # XXX: We need a way to tell AF_UNIX to pick its own name # like AF_INET provides port==0. dir = None if os.name == 'os2': dir = '\socket' fn = tempfile.mktemp(prefix='unix_socket.', dir=dir) if os.name == 'os2': # AF_UNIX socket names on OS/2 require a specific prefix # which can't include a drive letter and must also use # backslashes as directory separators if fn[1] == ':': fn = fn[2:] if fn[0] in (os.sep, os.altsep): fn = fn[1:] if os.sep == '/': fn = fn.replace(os.sep, os.altsep) else: fn = fn.replace(os.altsep, os.sep) self.test_files.append(fn) return fn
Example #2
Source File: usbmux.py From facebook-wda with MIT License | 7 votes |
def __init__(self, addr: Union[str, tuple, socket.socket]): """ Args: addr: can be /var/run/usbmuxd or (localhost, 27015) """ self._sock = None if isinstance(addr, socket.socket): self._sock = addr return if isinstance(addr, str): if not os.path.exists(addr): raise MuxError("socket unix:{} unable to connect".format(addr)) family = socket.AF_UNIX else: family = socket.AF_INET self._sock = socket.socket(family, socket.SOCK_STREAM) self._sock.connect(addr)
Example #3
Source File: svr_existingconn.py From Pyro5 with MIT License | 7 votes |
def init(self, daemon, connected_socket): connected_socket.getpeername() # check that it is connected if config.SSL and not isinstance(connected_socket, ssl.SSLSocket): raise socket.error("SSL configured for Pyro but existing socket is not a SSL socket") self.daemon = daemon self.sock = connected_socket log.info("starting server on user-supplied connected socket " + str(connected_socket)) sn = connected_socket.getsockname() if hasattr(socket, "AF_UNIX") and connected_socket.family == socket.AF_UNIX: self.locationStr = "./u:" + (sn or "<<not-bound>>") else: host, port = sn[:2] if ":" in host: # ipv6 self.locationStr = "[%s]:%d" % (host, port) else: self.locationStr = "%s:%d" % (host, port) self.conn = socketutil.SocketConnection(connected_socket)
Example #4
Source File: serving.py From recruit with Apache License 2.0 | 7 votes |
def select_address_family(host, port): """Return ``AF_INET4``, ``AF_INET6``, or ``AF_UNIX`` depending on the host and port.""" # disabled due to problems with current ipv6 implementations # and various operating systems. Probably this code also is # not supposed to work, but I can't come up with any other # ways to implement this. # try: # info = socket.getaddrinfo(host, port, socket.AF_UNSPEC, # socket.SOCK_STREAM, 0, # socket.AI_PASSIVE) # if info: # return info[0][0] # except socket.gaierror: # pass if host.startswith("unix://"): return socket.AF_UNIX elif ":" in host and hasattr(socket, "AF_INET6"): return socket.AF_INET6 return socket.AF_INET
Example #5
Source File: _pslinux.py From psutil with BSD 3-Clause "New" or "Revised" License | 6 votes |
def __init__(self): # The string represents the basename of the corresponding # /proc/net/{proto_name} file. tcp4 = ("tcp", socket.AF_INET, socket.SOCK_STREAM) tcp6 = ("tcp6", socket.AF_INET6, socket.SOCK_STREAM) udp4 = ("udp", socket.AF_INET, socket.SOCK_DGRAM) udp6 = ("udp6", socket.AF_INET6, socket.SOCK_DGRAM) unix = ("unix", socket.AF_UNIX, None) self.tmap = { "all": (tcp4, tcp6, udp4, udp6, unix), "tcp": (tcp4, tcp6), "tcp4": (tcp4,), "tcp6": (tcp6,), "udp": (udp4, udp6), "udp4": (udp4,), "udp6": (udp6,), "unix": (unix,), "inet": (tcp4, tcp6, udp4, udp6), "inet4": (tcp4, udp4), "inet6": (tcp6, udp6), } self._procfs_path = None
Example #6
Source File: server.py From calibre-web with GNU General Public License v3.0 | 6 votes |
def _make_gevent_unix_socket(self, socket_file): # the socket file must not exist prior to bind() if os.path.exists(socket_file): # avoid nuking regular files and symbolic links (could be a mistype or security issue) if os.path.isfile(socket_file) or os.path.islink(socket_file): raise OSError(errno.EEXIST, os.strerror(errno.EEXIST), socket_file) os.remove(socket_file) unix_sock = WSGIServer.get_listener(socket_file, family=socket.AF_UNIX) self.unix_socket_file = socket_file # ensure current user and group have r/w permissions, no permissions for other users # this way the socket can be shared in a semi-secure manner # between the user running calibre-web and the user running the fronting webserver os.chmod(socket_file, 0o660) return unix_sock
Example #7
Source File: test_socketutil.py From Pyro5 with MIT License | 6 votes |
def testSendUnix(self): if not hasattr(socket, "AF_UNIX"): pytest.skip("no unix domain sockets capability") SOCKNAME = "test_unixsocket" if os.path.exists(SOCKNAME): os.remove(SOCKNAME) ss = socketutil.create_socket(bind=SOCKNAME) cs = socketutil.create_socket(connect=SOCKNAME) socketutil.send_data(cs, b"foobar!" * 10) cs.shutdown(socket.SHUT_WR) a = ss.accept() data = socketutil.receive_data(a[0], 5) assert b"fooba" == data data = socketutil.receive_data(a[0], 5) assert b"r!foo" == data a[0].close() ss.close() cs.close() if os.path.exists(SOCKNAME): os.remove(SOCKNAME)
Example #8
Source File: _pslinux.py From teleport with Apache License 2.0 | 6 votes |
def __init__(self): tcp4 = ("tcp", socket.AF_INET, socket.SOCK_STREAM) tcp6 = ("tcp6", socket.AF_INET6, socket.SOCK_STREAM) udp4 = ("udp", socket.AF_INET, socket.SOCK_DGRAM) udp6 = ("udp6", socket.AF_INET6, socket.SOCK_DGRAM) unix = ("unix", socket.AF_UNIX, None) self.tmap = { "all": (tcp4, tcp6, udp4, udp6, unix), "tcp": (tcp4, tcp6), "tcp4": (tcp4,), "tcp6": (tcp6,), "udp": (udp4, udp6), "udp4": (udp4,), "udp6": (udp6,), "unix": (unix,), "inet": (tcp4, tcp6, udp4, udp6), "inet4": (tcp4, udp4), "inet6": (tcp6, udp6), } self._procfs_path = None
Example #9
Source File: server.py From pledgeservice with Apache License 2.0 | 6 votes |
def create_server(application, map=None, _start=True, # test shim _sock=None, # test shim _dispatcher=None, # test shim **kw # adjustments ): """ if __name__ == '__main__': server = create_server(app) server.run() """ adj = Adjustments(**kw) if adj.unix_socket and hasattr(socket, 'AF_UNIX'): cls = UnixWSGIServer else: cls = TcpWSGIServer return cls(application, map, _start, _sock, _dispatcher, adj)
Example #10
Source File: _pslinux.py From teleport with Apache License 2.0 | 6 votes |
def __init__(self): # The string represents the basename of the corresponding # /proc/net/{proto_name} file. tcp4 = ("tcp", socket.AF_INET, socket.SOCK_STREAM) tcp6 = ("tcp6", socket.AF_INET6, socket.SOCK_STREAM) udp4 = ("udp", socket.AF_INET, socket.SOCK_DGRAM) udp6 = ("udp6", socket.AF_INET6, socket.SOCK_DGRAM) unix = ("unix", socket.AF_UNIX, None) self.tmap = { "all": (tcp4, tcp6, udp4, udp6, unix), "tcp": (tcp4, tcp6), "tcp4": (tcp4,), "tcp6": (tcp6,), "udp": (udp4, udp6), "udp4": (udp4,), "udp6": (udp6,), "unix": (unix,), "inet": (tcp4, tcp6, udp4, udp6), "inet4": (tcp4, udp4), "inet6": (tcp6, udp6), } self._procfs_path = None
Example #11
Source File: _pslinux.py From vnpy_crypto with MIT License | 6 votes |
def __init__(self): tcp4 = ("tcp", socket.AF_INET, socket.SOCK_STREAM) tcp6 = ("tcp6", socket.AF_INET6, socket.SOCK_STREAM) udp4 = ("udp", socket.AF_INET, socket.SOCK_DGRAM) udp6 = ("udp6", socket.AF_INET6, socket.SOCK_DGRAM) unix = ("unix", socket.AF_UNIX, None) self.tmap = { "all": (tcp4, tcp6, udp4, udp6, unix), "tcp": (tcp4, tcp6), "tcp4": (tcp4,), "tcp6": (tcp6,), "udp": (udp4, udp6), "udp4": (udp4,), "udp6": (udp6,), "unix": (unix,), "inet": (tcp4, tcp6, udp4, udp6), "inet4": (tcp4, udp4), "inet6": (tcp6, udp6), } self._procfs_path = None
Example #12
Source File: _pslinux.py From teleport with Apache License 2.0 | 6 votes |
def __init__(self): # The string represents the basename of the corresponding # /proc/net/{proto_name} file. tcp4 = ("tcp", socket.AF_INET, socket.SOCK_STREAM) tcp6 = ("tcp6", socket.AF_INET6, socket.SOCK_STREAM) udp4 = ("udp", socket.AF_INET, socket.SOCK_DGRAM) udp6 = ("udp6", socket.AF_INET6, socket.SOCK_DGRAM) unix = ("unix", socket.AF_UNIX, None) self.tmap = { "all": (tcp4, tcp6, udp4, udp6, unix), "tcp": (tcp4, tcp6), "tcp4": (tcp4,), "tcp6": (tcp6,), "udp": (udp4, udp6), "udp4": (udp4,), "udp6": (udp6,), "unix": (unix,), "inet": (tcp4, tcp6, udp4, udp6), "inet4": (tcp4, udp4), "inet6": (tcp6, udp6), } self._procfs_path = None
Example #13
Source File: pullpipe.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def recvfd(socketfd): """ Receive a file descriptor from a L{sendmsg} message on the given C{AF_UNIX} socket. @param socketfd: An C{AF_UNIX} socket, attached to another process waiting to send sockets via the ancillary data mechanism in L{send1msg}. @param fd: C{int} @return: a 2-tuple of (new file descriptor, description). @rtype: 2-tuple of (C{int}, C{bytes}) """ ourSocket = socket.fromfd(socketfd, socket.AF_UNIX, socket.SOCK_STREAM) data, ancillary, flags = recvmsg(ourSocket) [(cmsgLevel, cmsgType, packedFD)] = ancillary # cmsgLevel and cmsgType really need to be SOL_SOCKET / SCM_RIGHTS, but # since those are the *only* standard values, there's not much point in # checking. [unpackedFD] = unpack("i", packedFD) return (unpackedFD, data)
Example #14
Source File: Rtp_proxy_client_stream.py From b2bua with BSD 2-Clause "Simplified" License | 6 votes |
def __init__(self, global_config, address = '/var/run/rtpproxy.sock', \ bind_address = None, nworkers = 1, family = socket.AF_UNIX): #print('Rtp_proxy_client_stream.__init__', address, bind_address, nworkers, family) if family == socket.AF_UNIX: self.is_local = True self.address = address else: self.is_local = False self.address = self.getdestbyaddr(address, family) self.family = family self.wi_available = Condition() self.wi = [] self.nworkers = nworkers self.workers = [] for i in range(0, self.nworkers): try: self.workers.append(_RTPPLWorker(self)) except: break self.nworkers_act = i + 1 self.delay_flt = recfilter(0.95, 0.25)
Example #15
Source File: Rtp_proxy_client_local.py From b2bua with BSD 2-Clause "Simplified" License | 5 votes |
def __init__(self, global_config, address = '/var/run/rtpproxy.sock', \ bind_address = None, nworkers = 1): Rtp_proxy_client_stream.__init__(self, global_config = global_config, \ address = address, bind_address = bind_address, nworkers = nworkers, \ family = socket.AF_UNIX)
Example #16
Source File: roomgraph.py From abusehelper with MIT License | 5 votes |
def _start_worker(self): env = dict(os.environ) env["ABUSEHELPER_SUBPROCESS"] = "" # Find out the full package & module name. Don't refer to the # variable __loader__ directly to keep flake8 (version 2.5.0) # linter happy. fullname = globals()["__loader__"].fullname own_conn, other_conn = native_socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM) try: process = subprocess.Popen( [sys.executable, "-m", fullname], preexec_fn=os.setpgrp, stdin=other_conn.fileno(), close_fds=True, env=env ) try: conn = socket.fromfd(own_conn.fileno(), socket.AF_UNIX, socket.SOCK_STREAM) except: process.terminate() process.wait() raise finally: own_conn.close() other_conn.close() return process, conn
Example #17
Source File: usbmux.py From iCloud-Bypass-via-USB with GNU General Public License v3.0 | 5 votes |
def __init__(self, socketpath: str, protoclass: type): self.socketpath = socketpath if sys.platform in ['win32', 'cygwin']: family = socket.AF_INET address = ('127.0.0.1', 27015) else: family = socket.AF_UNIX address = self.socketpath self.socket = SafeStreamSocket(address, family) self.proto = protoclass(self.socket) self.pkttag = 1 self.devices = list()
Example #18
Source File: _pslinux.py From teleport with Apache License 2.0 | 5 votes |
def process_inet(file, family, type_, inodes, filter_pid=None): """Parse /proc/net/tcp* and /proc/net/udp* files.""" if file.endswith('6') and not os.path.exists(file): # IPv6 not supported return with open_text(file, buffering=BIGFILE_BUFFERING) as f: f.readline() # skip the first line for lineno, line in enumerate(f, 1): try: _, laddr, raddr, status, _, _, _, _, _, inode = \ line.split()[:10] except ValueError: raise RuntimeError( "error while parsing %s; malformed line %s %r" % ( file, lineno, line)) if inode in inodes: # # We assume inet sockets are unique, so we error # # out if there are multiple references to the # # same inode. We won't do this for UNIX sockets. # if len(inodes[inode]) > 1 and family != socket.AF_UNIX: # raise ValueError("ambiguos inode with multiple " # "PIDs references") pid, fd = inodes[inode][0] else: pid, fd = None, -1 if filter_pid is not None and filter_pid != pid: continue else: if type_ == socket.SOCK_STREAM: status = TCP_STATUSES[status] else: status = _common.CONN_NONE try: laddr = Connections.decode_address(laddr, family) raddr = Connections.decode_address(raddr, family) except _Ipv6UnsupportedError: continue yield (fd, family, type_, laddr, raddr, status, pid)
Example #19
Source File: _pssunos.py From teleport with Apache License 2.0 | 5 votes |
def _get_unix_sockets(self, pid): """Get UNIX sockets used by process by parsing 'pfiles' output.""" # TODO: rewrite this in C (...but the damn netstat source code # does not include this part! Argh!!) cmd = "pfiles %s" % pid p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate() if PY3: stdout, stderr = [x.decode(sys.stdout.encoding) for x in (stdout, stderr)] if p.returncode != 0: if 'permission denied' in stderr.lower(): raise AccessDenied(self.pid, self._name) if 'no such process' in stderr.lower(): raise NoSuchProcess(self.pid, self._name) raise RuntimeError("%r command error\n%s" % (cmd, stderr)) lines = stdout.split('\n')[2:] for i, line in enumerate(lines): line = line.lstrip() if line.startswith('sockname: AF_UNIX'): path = line.split(' ', 2)[2] type = lines[i - 2].strip() if type == 'SOCK_STREAM': type = socket.SOCK_STREAM elif type == 'SOCK_DGRAM': type = socket.SOCK_DGRAM else: type = -1 yield (-1, socket.AF_UNIX, type, path, "", _common.CONN_NONE)
Example #20
Source File: haproxy.py From igcollect with MIT License | 5 votes |
def read_ha_proxy_stats(haproxy_stats_socket): conn = socket(AF_UNIX, SOCK_STREAM) try: conn.connect(haproxy_stats_socket) conn.sendall(b'show stat\r\n') data = conn.recv(BUFFER_SIZE) while len(data) % BUFFER_SIZE == 0: try: data += conn.recv(BUFFER_SIZE, MSG_DONTWAIT) except socket.error: break return data finally: conn.close()
Example #21
Source File: test_sendmsg.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def setUp(self): """ Create a pair of UNIX sockets. """ self.input, self.output = socketpair(AF_UNIX)
Example #22
Source File: _pssunos.py From psutil with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _get_unix_sockets(self, pid): """Get UNIX sockets used by process by parsing 'pfiles' output.""" # TODO: rewrite this in C (...but the damn netstat source code # does not include this part! Argh!!) cmd = "pfiles %s" % pid p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate() if PY3: stdout, stderr = [x.decode(sys.stdout.encoding) for x in (stdout, stderr)] if p.returncode != 0: if 'permission denied' in stderr.lower(): raise AccessDenied(self.pid, self._name) if 'no such process' in stderr.lower(): raise NoSuchProcess(self.pid, self._name) raise RuntimeError("%r command error\n%s" % (cmd, stderr)) lines = stdout.split('\n')[2:] for i, line in enumerate(lines): line = line.lstrip() if line.startswith('sockname: AF_UNIX'): path = line.split(' ', 2)[2] type = lines[i - 2].strip() if type == 'SOCK_STREAM': type = socket.SOCK_STREAM elif type == 'SOCK_DGRAM': type = socket.SOCK_DGRAM else: type = -1 yield (-1, socket.AF_UNIX, type, path, "", _common.CONN_NONE)
Example #23
Source File: test_testutils.py From psutil with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_create_sockets(self): with create_sockets() as socks: fams = collections.defaultdict(int) types = collections.defaultdict(int) for s in socks: fams[s.family] += 1 # work around http://bugs.python.org/issue30204 types[s.getsockopt(socket.SOL_SOCKET, socket.SO_TYPE)] += 1 self.assertGreaterEqual(fams[socket.AF_INET], 2) if supports_ipv6(): self.assertGreaterEqual(fams[socket.AF_INET6], 2) if POSIX and HAS_CONNECTIONS_UNIX: self.assertGreaterEqual(fams[socket.AF_UNIX], 2) self.assertGreaterEqual(types[socket.SOCK_STREAM], 2) self.assertGreaterEqual(types[socket.SOCK_DGRAM], 2)
Example #24
Source File: test_testutils.py From psutil with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_bind_unix_socket(self): name = self.get_testfn() sock = bind_unix_socket(name) with contextlib.closing(sock): self.assertEqual(sock.family, socket.AF_UNIX) self.assertEqual(sock.type, socket.SOCK_STREAM) self.assertEqual(sock.getsockname(), name) assert os.path.exists(name) assert stat.S_ISSOCK(os.stat(name).st_mode) # UDP name = self.get_testfn() sock = bind_unix_socket(name, type=socket.SOCK_DGRAM) with contextlib.closing(sock): self.assertEqual(sock.type, socket.SOCK_DGRAM)
Example #25
Source File: _pslinux.py From psutil with BSD 3-Clause "New" or "Revised" License | 5 votes |
def process_inet(file, family, type_, inodes, filter_pid=None): """Parse /proc/net/tcp* and /proc/net/udp* files.""" if file.endswith('6') and not os.path.exists(file): # IPv6 not supported return with open_text(file, buffering=BIGFILE_BUFFERING) as f: f.readline() # skip the first line for lineno, line in enumerate(f, 1): try: _, laddr, raddr, status, _, _, _, _, _, inode = \ line.split()[:10] except ValueError: raise RuntimeError( "error while parsing %s; malformed line %s %r" % ( file, lineno, line)) if inode in inodes: # # We assume inet sockets are unique, so we error # # out if there are multiple references to the # # same inode. We won't do this for UNIX sockets. # if len(inodes[inode]) > 1 and family != socket.AF_UNIX: # raise ValueError("ambiguos inode with multiple " # "PIDs references") pid, fd = inodes[inode][0] else: pid, fd = None, -1 if filter_pid is not None and filter_pid != pid: continue else: if type_ == socket.SOCK_STREAM: status = TCP_STATUSES[status] else: status = _common.CONN_NONE try: laddr = Connections.decode_address(laddr, family) raddr = Connections.decode_address(raddr, family) except _Ipv6UnsupportedError: continue yield (fd, family, type_, laddr, raddr, status, pid)
Example #26
Source File: qemu.py From grimoire with GNU Affero General Public License v3.0 | 5 votes |
def init(self): self.control = safe_socket(socket.AF_UNIX) self.control.settimeout(None) self.control.setblocking(1) while True: try: self.control.connect(self.control_filename) # self.control.connect(self.control_filename) break except socket_error: pass # time.sleep(0.01) self.kafl_shm_f = os.open(self.bitmap_filename, os.O_RDWR | os.O_SYNC | os.O_CREAT) self.fs_shm_f = os.open(self.payload_filename, os.O_RDWR | os.O_SYNC | os.O_CREAT) open(self.tracedump_filename, "wb").close() os.symlink(self.tracedump_filename, self.config.argument_values['work_dir'] + "/pt_trace_dump_" + self.qemu_id) os.symlink(self.payload_filename, self.config.argument_values['work_dir'] + "/payload_" + self.qemu_id) os.symlink(self.bitmap_filename, self.config.argument_values['work_dir'] + "/bitmap_" + self.qemu_id) # argv_fd = os.open(self.argv_filename, os.O_RDWR | os.O_SYNC | os.O_CREAT) os.ftruncate(self.kafl_shm_f, self.bitmap_size) os.ftruncate(self.fs_shm_f, (128 << 10)) # os.ftruncate(argv_fd, (4 << 10)) self.kafl_shm = mmap.mmap(self.kafl_shm_f, self.bitmap_size, mmap.MAP_SHARED, mmap.PROT_WRITE | mmap.PROT_READ) self.c_bitmap = (ctypes.c_uint8 * self.bitmap_size).from_buffer(self.kafl_shm) self.last_bitmap_wrapper = ExecutionResult(None, None, None, None) self.fs_shm = mmap.mmap(self.fs_shm_f, (128 << 10), mmap.MAP_SHARED, mmap.PROT_WRITE | mmap.PROT_READ) return True
Example #27
Source File: test_server.py From mopidy-mpd with Apache License 2.0 | 5 votes |
def test_accept_connection_unix(self): sock = Mock(spec=socket.socket) connected_sock = Mock(spec=socket.socket) connected_sock.family = socket.AF_UNIX connected_sock.getsockname.return_value = sentinel.sockname sock.accept.return_value = (connected_sock, sentinel.addr) self.mock.server_socket = sock sock, addr = network.Server.accept_connection(self.mock) assert connected_sock == sock assert (sentinel.sockname, None) == addr
Example #28
Source File: test_server.py From mopidy-mpd with Apache License 2.0 | 5 votes |
def test_stop_server_cleans_unix_socket(self): self.mock.watcher = Mock() sock = Mock() sock.family = socket.AF_UNIX self.mock.server_socket = sock network.Server.stop(self.mock) os.unlink.assert_called_once_with(sock.getsockname())
Example #29
Source File: network.py From mopidy-mpd with Apache License 2.0 | 5 votes |
def create_unix_socket(): """Create a Unix domain socket""" return socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
Example #30
Source File: network.py From mopidy-mpd with Apache License 2.0 | 5 votes |
def is_unix_socket(sock): """Check if the provided socket is a Unix domain socket""" if hasattr(socket, "AF_UNIX"): return sock.family == socket.AF_UNIX return False