Python socket.AF_INET() Examples

The following are code examples for showing how to use socket.AF_INET(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyblish-win   Author: pyblish   File: _pslinux.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
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),
        } 
Example 2
Project: pyblish-win   Author: pyblish   File: smtpd.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, localaddr, remoteaddr):
        self._localaddr = localaddr
        self._remoteaddr = remoteaddr
        asyncore.dispatcher.__init__(self)
        try:
            self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
            # try to re-use a server port if possible
            self.set_reuse_addr()
            self.bind(localaddr)
            self.listen(5)
        except:
            # cleanup asyncore.socket_map before raising
            self.close()
            raise
        else:
            print >> DEBUGSTREAM, \
                  '%s started at %s\n\tLocal addr: %s\n\tRemote addr:%s' % (
                self.__class__.__name__, time.ctime(time.time()),
                localaddr, remoteaddr) 
Example 3
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def testSockName(self):
        # Testing getsockname()
        port = self._get_unused_port()
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.addCleanup(sock.close)
        sock.bind(("0.0.0.0", port))
        name = sock.getsockname()
        # XXX(nnorwitz): http://tinyurl.com/os5jz seems to indicate
        # it reasonable to get the host's addr in addition to 0.0.0.0.
        # At least for eCos.  This is required for the S/390 to pass.
        try:
            my_ip_addr = socket.gethostbyname(socket.gethostname())
        except socket.error:
            # Probably name lookup wasn't set up right; skip this test
            self.skipTest('name lookup failure')
        self.assertIn(name[0], ("0.0.0.0", my_ip_addr), '%s invalid' % name[0])
        self.assertEqual(name[1], port) 
Example 4
Project: pyblish-win   Author: pyblish   File: test_socketserver.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
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 5
Project: pyblish-win   Author: pyblish   File: test_asyncore.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_issue_8594(self):
        # XXX - this test is supposed to be removed in next major Python
        # version
        d = asyncore.dispatcher(socket.socket())
        # make sure the error message no longer refers to the socket
        # object but the dispatcher instance instead
        self.assertRaisesRegexp(AttributeError, 'dispatcher instance',
                                getattr, d, 'foo')
        # cheap inheritance with the underlying socket is supposed
        # to still work but a DeprecationWarning is expected
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")
            family = d.family
            self.assertEqual(family, socket.AF_INET)
            self.assertEqual(len(w), 1)
            self.assertTrue(issubclass(w[0].category, DeprecationWarning)) 
Example 6
Project: pyblish-win   Author: pyblish   File: test_asyncore.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_handle_accept(self):
        # make sure handle_accept() is called when a client connects

        class TestListener(BaseTestHandler):

            def __init__(self):
                BaseTestHandler.__init__(self)
                self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
                self.bind((HOST, 0))
                self.listen(5)
                self.address = self.socket.getsockname()[:2]

            def handle_accept(self):
                self.flag = True

        server = TestListener()
        client = BaseClient(server.address)
        self.loop_waiting_for_flag(server) 
Example 7
Project: pyblish-win   Author: pyblish   File: test_asyncore.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_set_reuse_addr(self):
        sock = socket.socket()
        try:
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        except socket.error:
            unittest.skip("SO_REUSEADDR not supported on this platform")
        else:
            # if SO_REUSEADDR succeeded for sock we expect asyncore
            # to do the same
            s = asyncore.dispatcher(socket.socket())
            self.assertFalse(s.socket.getsockopt(socket.SOL_SOCKET,
                                                 socket.SO_REUSEADDR))
            s.create_socket(socket.AF_INET, socket.SOCK_STREAM)
            s.set_reuse_addr()
            self.assertTrue(s.socket.getsockopt(socket.SOL_SOCKET,
                                                 socket.SO_REUSEADDR))
        finally:
            sock.close() 
Example 8
Project: slidoc   Author: mitotic   File: multiproxy.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def connect_to_internal(self):
        if self.closed:
            return

        try:
            assert self.relay_address, "Relay address not defined for internal connection"
            if isinstance(self.relay_address, tuple):
                # relay_address = (host, addr)
                socket_type = socket.AF_INET
            else:
                # relay_address = unix_domain_socket_addr
                socket_type = socket.AF_UNIX
            self.internal_sock = socket.socket(socket_type, socket.SOCK_STREAM, 0)
            self.internal_stream = ChunkyIOStream(self.internal_sock)
            self.internal_stream.set_close_callback(self.internal_disconnected)
            self.internal_stream.connect(self.relay_address, self.internal_connected)
        except Exception, excp:
            logging.warning("multiproxy: Internal connect error: %s", excp)
            self.inbound_flow.error_response("502 Bad Gateway (internal connect error)") 
Example 9
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: wait_for.py    MIT License 6 votes vote down vote up
def _convert_host_to_ip(host):
    """
    Perform forward DNS resolution on host, IP will give the same IP

    Args:
        host: String with either hostname, IPv4, or IPv6 address

    Returns:
        List of tuples containing address family and IP
    """
    addrinfo = socket.getaddrinfo(host, 80, 0, 0, socket.SOL_TCP)
    ips = []
    for family, socktype, proto, canonname, sockaddr in addrinfo:
        ip = sockaddr[0]
        ips.append((family, ip))
        if family == socket.AF_INET:
            ips.append((socket.AF_INET6, "::ffff:" + ip))
    return ips 
Example 10
Project: estim2bapi   Author: fredhatt   File: estimsocket.py    MIT License 6 votes vote down vote up
def open_socket(self):
        if self._udp:
            self.serversocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        else:
            self.serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        self.serversocket.bind(('', self._port))
        if not self._udp:
            self.serversocket.listen(1) # become a server socket
        
        if self._udp:
            print('UDP Server started ({}:{})... waiting for data.'.format(self._address, self._port))
            return None, None
        else:
            print('TCP Server started ({}:{})... waiting for client to connect.'.format(self._address, self._port))
            conn, addr = self.serversocket.accept()
            print('New client {} connected.'.format(addr[0]))
            print('Running loop.')
            return conn, addr 
Example 11
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: host.py    Apache License 2.0 6 votes vote down vote up
def _init_events_pipe(self):
        """Create a self-pipe for the native thread to synchronize on.

        This code is taken from the eventlet tpool module, under terms
        of the Apache License v2.0.
        """

        self._event_queue = native_Queue.Queue()
        try:
            rpipe, wpipe = os.pipe()
            self._event_notify_send = greenio.GreenPipe(wpipe, 'wb', 0)
            self._event_notify_recv = greenio.GreenPipe(rpipe, 'rb', 0)
        except (ImportError, NotImplementedError):
            # This is Windows compatibility -- use a socket instead
            #  of a pipe because pipes don't really exist on Windows.
            sock = native_socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.bind(('localhost', 0))
            sock.listen(50)
            csock = native_socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            csock.connect(('localhost', sock.getsockname()[1]))
            nsock, addr = sock.accept()
            self._event_notify_send = nsock.makefile('wb', 0)
            gsock = greenio.GreenSocket(csock)
            self._event_notify_recv = gsock.makefile('rb', 0) 
Example 12
Project: XFLTReaT   Author: earthquake   File: SCTP_generic.py    MIT License 6 votes vote down vote up
def stop(self):
		self._stop = True

		if self.threads:
			for t in self.threads:
				t.stop()
		
		# not so nice solution to get rid of the block of listen()
		# unfortunately close() does not help on the block
		try:
			server_socket = self.sctp.sctpsocket_tcp(socket.AF_INET)
			if self.config.get("Global", "serverbind") == "0.0.0.0":
				server_socket.connect(("127.0.0.1", int(self.config.get(self.get_module_configname(), "serverport"))))
			else:
				server_socket.connect((self.config.get("Global", "serverbind"), int(self.config.get(self.get_module_configname(), "serverport"))))
		except:
			pass

		return 
Example 13
Project: XFLTReaT   Author: earthquake   File: SCTP_generic.py    MIT License 6 votes vote down vote up
def check(self):
		try:
			common.internal_print("Checking module on server: {0}".format(self.get_module_name()))

			server_socket = self.sctp.sctpsocket_tcp(socket.AF_INET)
			server_socket.settimeout(3)
			server_socket.connect((self.config.get("Global", "remoteserverip"), int(self.config.get(self.get_module_configname(), "serverport"))))
			client_fake_thread = SCTP_generic_thread(0, 0, None, None, server_socket, None, self.authentication, self.encryption_module, self.verbosity, self.config, self.get_module_name())
			client_fake_thread.do_check()
			client_fake_thread.communication(True)

			self.cleanup(server_socket)

		except socket.timeout:
			common.internal_print("Checking failed: {0}".format(self.get_module_name()), -1)
			self.cleanup(server_socket)
		except socket.error as exception:
			if exception.args[0] == 111:
				common.internal_print("Checking failed: {0}".format(self.get_module_name()), -1)
			else:
				common.internal_print("Connection error: {0}".format(self.get_module_name()), -1)
			self.cleanup(server_socket)

		return 
Example 14
Project: XFLTReaT   Author: earthquake   File: interface.py    MIT License 6 votes vote down vote up
def freebsd_tun_alloc(self, dev, flags):
		try:
			sockfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
			ifr = struct.pack('<16si', 'tun', 0)
			self.iface_name = fcntl.ioctl(sockfd, self.IOCTL_FREEBSD_SIOCIFCREATE2, ifr)
			self.iface_name = self.iface_name.rstrip("\x00")

			buff = array.array('c', dev+"\x00")
			caddr_t, _ = buff.buffer_info()
			ifr = struct.pack('16sP', self.iface_name, caddr_t);

			fcntl.ioctl(sockfd, self.IOCTL_FREEBSD_SIOCSIFNAME, ifr)
			tun = os.open("/dev/"+self.iface_name, os.O_RDWR | os.O_NONBLOCK)
			self.iface_name = dev

		except IOError as e:
			print e
			common.internal_print("Error: Cannot create tunnel. Is {0} in use?".format(dev), -1)
			sys.exit(-1)

		return tun 
Example 15
Project: neos-classic-electrum-server   Author: neoscoin   File: stratum_http.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, addr, requestHandler=StratumJSONRPCRequestHandler,
                 logRequests=False, encoding=None, bind_and_activate=True,
                 address_family=socket.AF_INET):
        self.logRequests = logRequests
        StratumJSONRPCDispatcher.__init__(self, encoding)
        # TCPServer.__init__ has an extra parameter on 2.6+, so
        # check Python version and decide on how to call it
        vi = sys.version_info
        self.address_family = address_family
        if USE_UNIX_SOCKETS and address_family == socket.AF_UNIX:
            # Unix sockets can't be bound if they already exist in the
            # filesystem. The convention of e.g. X11 is to unlink
            # before binding again.
            if os.path.exists(addr):
                try:
                    os.unlink(addr)
                except OSError:
                    logging.warning("Could not unlink socket %s", addr)

        SocketServer.TCPServer.__init__(self, addr, requestHandler, bind_and_activate)

        if fcntl is not None and hasattr(fcntl, 'FD_CLOEXEC'):
            flags = fcntl.fcntl(self.fileno(), fcntl.F_GETFD)
            flags |= fcntl.FD_CLOEXEC
            fcntl.fcntl(self.fileno(), fcntl.F_SETFD, flags) 
Example 16
Project: fs_image   Author: facebookincubator   File: yum_dnf_from_snapshot.py    MIT License 5 votes vote down vote up
def _make_socket_and_send_via(*, unix_sock_fd):
    '''
    Creates a TCP stream socket and sends it elsewhere via the provided Unix
    domain socket file descriptor.  This is useful for obtaining a socket
    that belongs to a different network namespace (i.e.  creating a socket
    inside a container, but binding it from outside the container).

    IMPORTANT: This code must not write anything to stdout, the fd can be 1.
    '''
    # NB: Some code here is (sort of) copy-pasta'd in `send_fds_and_run.py`,
    # but it's not obviously worthwhile to reuse it here.
    return ['python3', '-c', textwrap.dedent('''\
    import array, socket, sys

    def send_fds(sock, msg: bytes, fds: 'List[int]'):
        num_sent = sock.sendmsg([msg], [(
            socket.SOL_SOCKET, socket.SCM_RIGHTS,
            array.array('i', fds).tobytes(),
            # Future: is `flags=socket.MSG_NOSIGNAL` a good idea?
        )])
        assert len(msg) == num_sent, (msg, num_sent)

    # Make a socket in this netns, and send it to the parent.
    with socket.socket(fileno=''' + str(unix_sock_fd) + ''') as lsock:
        print(f'Sending FD to parent', file=sys.stderr)
        lsock.settimeout(''' + str(FD_UNIX_SOCK_TIMEOUT) + ''')
        with lsock.accept()[0] as csock, socket.socket(
            socket.AF_INET, socket.SOCK_STREAM
        ) as inet_sock:
            csock.settimeout(''' + str(FD_UNIX_SOCK_TIMEOUT) + ''')
            send_fds(csock, b'ohai', [inet_sock.fileno()])
    ''')] 
Example 17
Project: pyblish-win   Author: pyblish   File: ftplib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def sendeprt(self, host, port):
        '''Send a EPRT command with the current host and the given port number.'''
        af = 0
        if self.af == socket.AF_INET:
            af = 1
        if self.af == socket.AF_INET6:
            af = 2
        if af == 0:
            raise error_proto, 'unsupported address family'
        fields = ['', repr(af), host, repr(port), '']
        cmd = 'EPRT ' + '|'.join(fields)
        return self.voidcmd(cmd) 
Example 18
Project: pyblish-win   Author: pyblish   File: ftplib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def makepasv(self):
        if self.af == socket.AF_INET:
            host, port = parse227(self.sendcmd('PASV'))
        else:
            host, port = parse229(self.sendcmd('EPSV'), self.sock.getpeername())
        return host, port 
Example 19
Project: pyblish-win   Author: pyblish   File: __init__.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def net_if_addrs():
    """Return the addresses associated to each NIC (network interface
    card) installed on the system as a dictionary whose keys are the
    NIC names and value is a list of namedtuples for each address
    assigned to the NIC. Each namedtuple includes 4 fields:

     - family
     - address
     - netmask
     - broadcast

    'family' can be either socket.AF_INET, socket.AF_INET6 or
    psutil.AF_LINK, which refers to a MAC address.
    'address' is the primary address, 'netmask' and 'broadcast'
    may be None.
    Note: you can have more than one address of the same family
    associated with each interface.
    """
    has_enums = sys.version_info >= (3, 4)
    if has_enums:
        import socket
    rawlist = _psplatform.net_if_addrs()
    rawlist.sort(key=lambda x: x[1])  # sort by family
    ret = collections.defaultdict(list)
    for name, fam, addr, mask, broadcast in rawlist:
        if has_enums:
            try:
                fam = socket.AddressFamily(fam)
            except ValueError:
                if os.name == 'nt' and fam == -1:
                    fam = _psplatform.AF_LINK
                elif (hasattr(_psplatform, "AF_LINK") and
                        _psplatform.AF_LINK == fam):
                    # Linux defines AF_LINK as an alias for AF_PACKET.
                    # We re-set the family here so that repr(family)
                    # will show AF_LINK rather than AF_PACKET
                    fam = _psplatform.AF_LINK
        ret[name].append(_common.snic(fam, addr, mask, broadcast))
    return dict(ret) 
Example 20
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def try_address(host, port=0, family=socket.AF_INET):
    """Try to bind a socket on the given host:port and return True
    if that has been possible."""
    try:
        sock = socket.socket(family, socket.SOCK_STREAM)
        sock.bind((host, port))
    except (socket.error, socket.gaierror):
        return False
    else:
        sock.close()
        return True 
Example 21
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.port = test_support.bind_port(self.serv)
        self.serv.listen(1) 
Example 22
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.serv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.port = test_support.bind_port(self.serv) 
Example 23
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def clientSetUp(self):
        self.cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
Example 24
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_csocket_repr(self):
        s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
        try:
            expected = ('<socket object, fd=%s, family=%s, type=%s, protocol=%s>'
                        % (s.fileno(), s.family, s.type, s.proto))
            self.assertEqual(repr(s), expected)
        finally:
            s.close()
        expected = ('<socket object, fd=-1, family=%s, type=%s, protocol=%s>'
                    % (s.family, s.type, s.proto))
        self.assertEqual(repr(s), expected) 
Example 25
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_weakref(self):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        p = weakref.proxy(s)
        self.assertEqual(p.fileno(), s.fileno())
        s.close()
        s = None
        try:
            p.fileno()
        except ReferenceError:
            pass
        else:
            self.fail('Socket proxy still exists') 
Example 26
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testSendtoErrors(self):
        # Testing that sendto doens't masks failures. See #10169.
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.addCleanup(s.close)
        s.bind(('', 0))
        sockname = s.getsockname()
        # 2 args
        with self.assertRaises(UnicodeEncodeError):
            s.sendto(u'\u2620', sockname)
        with self.assertRaises(TypeError) as cm:
            s.sendto(5j, sockname)
        self.assertIn('not complex', str(cm.exception))
        with self.assertRaises(TypeError) as cm:
            s.sendto('foo', None)
        self.assertIn('not NoneType', str(cm.exception))
        # 3 args
        with self.assertRaises(UnicodeEncodeError):
            s.sendto(u'\u2620', 0, sockname)
        with self.assertRaises(TypeError) as cm:
            s.sendto(5j, 0, sockname)
        self.assertIn('not complex', str(cm.exception))
        with self.assertRaises(TypeError) as cm:
            s.sendto('foo', 0, None)
        self.assertIn('not NoneType', str(cm.exception))
        with self.assertRaises(TypeError) as cm:
            s.sendto('foo', 'bar', sockname)
        self.assertIn('an integer is required', str(cm.exception))
        with self.assertRaises(TypeError) as cm:
            s.sendto('foo', None, None)
        self.assertIn('an integer is required', str(cm.exception))
        # wrong number of args
        with self.assertRaises(TypeError) as cm:
            s.sendto('foo')
        self.assertIn('(1 given)', str(cm.exception))
        with self.assertRaises(TypeError) as cm:
            s.sendto('foo', 0, sockname, 4)
        self.assertIn('(4 given)', str(cm.exception)) 
Example 27
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testCrucialConstants(self):
        # Testing for mission critical constants
        socket.AF_INET
        socket.SOCK_STREAM
        socket.SOCK_DGRAM
        socket.SOCK_RAW
        socket.SOCK_RDM
        socket.SOCK_SEQPACKET
        socket.SOL_SOCKET
        socket.SO_REUSEADDR 
Example 28
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testIPv4toString(self):
        from socket import inet_aton as f, inet_pton, AF_INET
        g = lambda a: inet_pton(AF_INET, a)

        self.assertEqual('\x00\x00\x00\x00', f('0.0.0.0'))
        self.assertEqual('\xff\x00\xff\x00', f('255.0.255.0'))
        self.assertEqual('\xaa\xaa\xaa\xaa', f('170.170.170.170'))
        self.assertEqual('\x01\x02\x03\x04', f('1.2.3.4'))
        self.assertEqual('\xff\xff\xff\xff', f('255.255.255.255'))

        self.assertEqual('\x00\x00\x00\x00', g('0.0.0.0'))
        self.assertEqual('\xff\x00\xff\x00', g('255.0.255.0'))
        self.assertEqual('\xaa\xaa\xaa\xaa', g('170.170.170.170'))
        self.assertEqual('\xff\xff\xff\xff', g('255.255.255.255')) 
Example 29
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testGetSockOpt(self):
        # Testing getsockopt()
        # We know a socket should start without reuse==0
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.addCleanup(sock.close)
        reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
        self.assertFalse(reuse != 0, "initial mode is reuse") 
Example 30
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testSetSockOpt(self):
        # Testing setsockopt()
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.addCleanup(sock.close)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
        self.assertFalse(reuse == 0, "failed to set reuse mode") 
Example 31
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testSendAfterClose(self):
        # testing send() after close() with timeout
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(1)
        sock.close()
        self.assertRaises(socket.error, sock.send, "spam") 
Example 32
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testNewAttributes(self):
        # testing .family, .type and .protocol
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.assertEqual(sock.family, socket.AF_INET)
        self.assertEqual(sock.type, socket.SOCK_STREAM)
        self.assertEqual(sock.proto, 0)
        sock.close() 
Example 33
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_listen_backlog(self):
        for backlog in 0, -1:
            srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            srv.bind((HOST, 0))
            srv.listen(backlog)
            srv.close() 
Example 34
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_listen_backlog_overflow(self):
        # Issue 15989
        import _testcapi
        srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        srv.bind((HOST, 0))
        self.assertRaises(OverflowError, srv.listen, _testcapi.INT_MAX + 1)
        srv.close() 
Example 35
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_connect(self):
        port = test_support.find_unused_port()
        cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.addCleanup(cli.close)
        with self.assertRaises(socket.error) as cm:
            cli.connect((HOST, port))
        self.assertEqual(cm.exception.errno, errno.ECONNREFUSED) 
Example 36
Project: pyblish-win   Author: pyblish   File: test_ftplib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, address, af=socket.AF_INET):
        threading.Thread.__init__(self)
        asyncore.dispatcher.__init__(self)
        self.create_socket(af, socket.SOCK_STREAM)
        self.bind(address)
        self.listen(5)
        self.active = False
        self.active_lock = threading.Lock()
        self.host, self.port = self.socket.getsockname()[:2] 
Example 37
Project: pyblish-win   Author: pyblish   File: test_support.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def bind_port(sock, host=HOST):
    """Bind the socket to a free port and return the port number.  Relies on
    ephemeral ports in order to ensure we are using an unbound port.  This is
    important as many tests may be running simultaneously, especially in a
    buildbot environment.  This method raises an exception if the sock.family
    is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR
    or SO_REUSEPORT set on it.  Tests should *never* set these socket options
    for TCP/IP sockets.  The only case for setting these options is testing
    multicasting via multiple UDP sockets.

    Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e.
    on Windows), it will be set on the socket.  This will prevent anyone else
    from bind()'ing to our host/port for the duration of the test.
    """
    if sock.family == socket.AF_INET and sock.type == socket.SOCK_STREAM:
        if hasattr(socket, 'SO_REUSEADDR'):
            if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == 1:
                raise TestFailed("tests should never set the SO_REUSEADDR "   \
                                 "socket option on TCP/IP sockets!")
        if hasattr(socket, 'SO_REUSEPORT'):
            try:
                if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 1:
                    raise TestFailed("tests should never set the SO_REUSEPORT "   \
                                     "socket option on TCP/IP sockets!")
            except EnvironmentError:
                # Python's socket module was compiled using modern headers
                # thus defining SO_REUSEPORT but this process is running
                # under an older kernel that does not support SO_REUSEPORT.
                pass
        if hasattr(socket, 'SO_EXCLUSIVEADDRUSE'):
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)

    sock.bind((host, 0))
    port = sock.getsockname()[1]
    return port 
Example 38
Project: pyblish-win   Author: pyblish   File: test_asyncore.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_send(self):
        evt = threading.Event()
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(3)
        port = test_support.bind_port(sock)

        cap = StringIO()
        args = (evt, cap, sock)
        t = threading.Thread(target=capture_server, args=args)
        t.start()
        try:
            # wait a little longer for the server to initialize (it sometimes
            # refuses connections on slow machines without this wait)
            time.sleep(0.2)

            data = "Suppose there isn't a 16-ton weight?"
            d = dispatcherwithsend_noread()
            d.create_socket(socket.AF_INET, socket.SOCK_STREAM)
            d.connect((HOST, port))

            # give time for socket to connect
            time.sleep(0.1)

            d.send(data)
            d.send(data)
            d.send('\n')

            n = 1000
            while d.out_buffer and n > 0:
                asyncore.poll()
                n -= 1

            evt.wait()

            self.assertEqual(cap.getvalue(), data*2)
        finally:
            t.join() 
Example 39
Project: pyblish-win   Author: pyblish   File: test_asyncore.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, address):
        BaseTestHandler.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.connect(address) 
Example 40
Project: pyblish-win   Author: pyblish   File: test_asyncore.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_create_socket(self):
        s = asyncore.dispatcher()
        s.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.assertEqual(s.socket.family, socket.AF_INET)
        self.assertEqual(s.socket.type, socket.SOCK_STREAM) 
Example 41
Project: pyblish-win   Author: pyblish   File: test_asyncore.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_bind(self):
        s1 = asyncore.dispatcher()
        s1.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        s1.bind((HOST, 0))
        s1.listen(5)
        port = s1.socket.getsockname()[1]

        s2 = asyncore.dispatcher()
        s2.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        # EADDRINUSE indicates the socket was correctly bound
        self.assertRaises(socket.error, s2.bind, (HOST, port)) 
Example 42
Project: pyblish-win   Author: pyblish   File: test_poplib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, address, af=socket.AF_INET):
        threading.Thread.__init__(self)
        asyncore.dispatcher.__init__(self)
        self.create_socket(af, socket.SOCK_STREAM)
        self.bind(address)
        self.listen(5)
        self.active = False
        self.active_lock = threading.Lock()
        self.host, self.port = self.socket.getsockname()[:2] 
Example 43
Project: pyblish-win   Author: pyblish   File: test_poplib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.evt = threading.Event()
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.settimeout(60)  # Safety net. Look issue 11812
        self.port = test_support.bind_port(self.sock)
        self.thread = threading.Thread(target=self.server, args=(self.evt,self.sock))
        self.thread.setDaemon(True)
        self.thread.start()
        self.evt.wait() 
Example 44
Project: pyblish-win   Author: pyblish   File: test_asynchat.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, event):
            threading.Thread.__init__(self)
            self.event = event
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.port = test_support.bind_port(self.sock)
            # This will be set if the client wants us to wait before echoing data
            # back.
            self.start_resend_event = None 
Example 45
Project: pyblish-win   Author: pyblish   File: test_asynchat.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, terminator, server_port):
            asynchat.async_chat.__init__(self)
            self.contents = []
            self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
            self.connect((HOST, server_port))
            self.set_terminator(terminator)
            self.buffer = '' 
Example 46
Project: pyblish-win   Author: pyblish   File: rpc.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, address, family=socket.AF_INET, type=socket.SOCK_STREAM):
        self.listening_sock = socket.socket(family, type)
        self.listening_sock.bind(address)
        self.listening_sock.listen(1) 
Example 47
Project: AutoDL   Author: tanguofu   File: request.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _get_address(self):
        sock = self.transport.get_extra_info('socket')

        if sock.family == socket.AF_INET:
            self._socket = (self.transport.get_extra_info('peername') or
                            (None, None))
            self._ip, self._port = self._socket
        elif sock.family == socket.AF_INET6:
            self._socket = (self.transport.get_extra_info('peername') or
                            (None, None, None, None))
            self._ip, self._port, *_ = self._socket
        else:
            self._ip, self._port = (None, None) 
Example 48
Project: iSDX   Author: sdn-ixp   File: logServer.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, host, port):
        asyncore.dispatcher.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.set_reuse_addr()
        self.bind((host, port))
        self.listen(5) 
Example 49
Project: sklearn2docker   Author: KhaledSharif   File: base_unit_test.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_free_tcp_port():
        from socket import socket, AF_INET, SOCK_STREAM
        tcp = socket(AF_INET, SOCK_STREAM)
        tcp.bind(('', 0))
        addr, port = tcp.getsockname()
        tcp.close()
        return port 
Example 50
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: x509.py    MIT License 5 votes vote down vote up
def native(self):
        """
        The a native Python datatype representation of this value

        :return:
            A unicode string or None
        """

        if self.contents is None:
            return None

        if self._native is None:
            byte_string = self.__bytes__()
            byte_len = len(byte_string)
            cidr_int = None
            if byte_len in set([32, 16]):
                value = inet_ntop(socket.AF_INET6, byte_string[0:16])
                if byte_len > 16:
                    cidr_int = int_from_bytes(byte_string[16:])
            elif byte_len in set([8, 4]):
                value = inet_ntop(socket.AF_INET, byte_string[0:4])
                if byte_len > 4:
                    cidr_int = int_from_bytes(byte_string[4:])
            if cidr_int is not None:
                cidr_bits = '{0:b}'.format(cidr_int)
                cidr = len(cidr_bits.rstrip('0'))
                value = value + '/' + str_cls(cidr)
            self._native = value
        return self._native 
Example 51
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: connection.py    MIT License 5 votes vote down vote up
def allowed_gai_family():
    """This function is designed to work in the context of
    getaddrinfo, where family=socket.AF_UNSPEC is the default and
    will perform a DNS search for both IPv6 and IPv4 records."""

    family = socket.AF_INET
    if HAS_IPV6:
        family = socket.AF_UNSPEC
    return family 
Example 52
Project: astost_search   Author: littleneko   File: sphinxapi.py    GNU General Public License v3.0 5 votes vote down vote up
def _Connect (self):
        """
        INTERNAL METHOD, DO NOT CALL. Connects to searchd server.
        """
        if self._socket:
            # we have a socket, but is it still alive?
            sr, sw, _ = select.select ( [self._socket], [self._socket], [], 0 )

            # this is how alive socket should look
            if len(sr)==0 and len(sw)==1:
                return self._socket

            # oops, looks like it was closed, lets reopen
            self._socket.close()
            self._socket = None

        try:
            if self._path:
                af = socket.AF_UNIX
                addr = self._path
                desc = self._path
            else:
                af = socket.AF_INET
                addr = ( self._host, self._port )
                desc = '%s;%s' % addr
            sock = socket.socket ( af, socket.SOCK_STREAM )
            sock.settimeout ( self._timeout )
            sock.connect ( addr )
        except socket.error, msg:
            if sock:
                sock.close()
            self._error = 'connection to %s failed (%s)' % ( desc, msg )
            return 
Example 53
Project: estim2bapi   Author: fredhatt   File: estimsocket.py    MIT License 5 votes vote down vote up
def client_connect(self):
        self.clientsocket = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
        self.clientsocket.connect( (self._address, self._port) ) 
Example 54
Project: fishroom   Author: tuna   File: telegram_tg.py    GNU General Public License v3.0 5 votes vote down vote up
def _socket_init(self, ip_addr, port):
        s = socket(AF_INET, SOCK_STREAM)
        s.connect((ip_addr, port))
        self.sock = s 
Example 55
Project: XFLTReaT   Author: earthquake   File: SCTP_generic.py    MIT License 5 votes vote down vote up
def serve(self):
		client_socket = server_socket = None
		self.threads = []
		threadsnum = 0

		common.internal_print("Starting module: {0} on {1}:{2}".format(self.get_module_name(), self.config.get("Global", "serverbind"), int(self.config.get(self.get_module_configname(), "serverport"))))
		
		server_socket = self.sctp.sctpsocket_tcp(socket.AF_INET)
		server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
		try:
			server_socket.bind((self.config.get("Global", "serverbind"), int(self.config.get(self.get_module_configname(), "serverport"))))
			while not self._stop:
				server_socket.listen(1) #?? 1 ??
				client_socket, client_addr = server_socket.accept()
				common.internal_print(("Client connected: {0}".format(client_addr)), 0, self.verbosity, common.DEBUG)

				threadsnum = threadsnum + 1
				thread = SCTP_generic_thread(threadsnum, 1, self.tunnel, self.packetselector, client_socket, client_addr, self.authentication, self.encryption_module, self.verbosity, self.config, self.get_module_name())
				thread.start()
				self.threads.append(thread)
			if self._stop:
				self.stop()

		except socket.error as exception:
			# [Errno 98] Address already in use
			if exception.args[0] != 98:
				raise
			else:
				common.internal_print("Starting failed, port is in use: {0} on {1}:{2}".format(self.get_module_name(), self.config.get("Global", "serverbind"), int(self.config.get(self.get_module_configname(), "serverport"))), -1)

		self.cleanup(server_socket)

		return 
Example 56
Project: XFLTReaT   Author: earthquake   File: SCTP_generic.py    MIT License 5 votes vote down vote up
def connect(self):
		try:
			common.internal_print("Starting client: {0}".format(self.get_module_name()))

			client_fake_thread = None

			server_socket = self.sctp.sctpsocket_tcp(socket.AF_INET)
			server_socket.settimeout(3)
			server_socket.connect((self.config.get("Global", "remoteserverip"), int(self.config.get(self.get_module_configname(), "serverport"))))

			client_fake_thread = SCTP_generic_thread(0, 0, self.tunnel, None, server_socket, None, self.authentication, self.encryption_module, self.verbosity, self.config, self.get_module_name())
			client_fake_thread.do_hello()
			client_fake_thread.communication(False)

		except KeyboardInterrupt:
			if client_fake_thread:
				client_fake_thread.do_logoff()
			self.cleanup(server_socket)
			raise
		except socket.error:
			common.internal_print("Connection error: {0}".format(self.get_module_name()), -1)
			self.cleanup(server_socket)
			raise

		self.cleanup(server_socket)

		return 
Example 57
Project: XFLTReaT   Author: earthquake   File: interface.py    MIT License 5 votes vote down vote up
def lin_set_ip_address(self, dev, ip, serverip, netmask):
		sockfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		try:
			# set IP
			ifr  = struct.pack('<16sH2s4s8s', dev, socket.AF_INET, "\x00"*2, socket.inet_aton(ip), "\x00"*8)
			fcntl.ioctl(sockfd, self.IOCTL_LINUX_SIOCSIFADDR, ifr)

			# get flags
			ifr = struct.pack('<16sh', dev, 0)
			flags = struct.unpack('<16sh', fcntl.ioctl(sockfd, self.IOCTL_LINUX_SIOCSIFFLAGS, ifr))[1]

			# set new flags
			flags = flags | self.IOCTL_LINUX_IFF_UP
			ifr = struct.pack('<16sh', dev, flags)

			# iface up
			fcntl.ioctl(sockfd, self.IOCTL_LINUX_SIOCSIFFLAGS, ifr)
		except Exception as e:
			common.internal_print("Something went wrong with setting up the interface.", -1)
			print(e)
			sys.exit(-1)

		# adding new route for forwarding packets properly.
		integer_ip = struct.unpack(">I", socket.inet_pton(socket.AF_INET, serverip))[0]
		rangeip = socket.inet_ntop(socket.AF_INET, struct.pack(">I", integer_ip & ((2**int(netmask))-1)<<32-int(netmask)))

		integer_netmask = struct.pack(">I", ((2**int(netmask))-1)<<32-int(netmask))
		netmask = socket.inet_ntoa(integer_netmask)

		ps = subprocess.Popen(["route", "add", "-net", rangeip, "netmask", netmask, "dev", dev], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
		(stdout, stderr) = ps.communicate()
		if stderr:
			if not "File exists" in stderr:
				common.internal_print("Error: adding client route: {0}".format(stderr), -1)
				sys.exit(-1)

		return 
Example 58
Project: XFLTReaT   Author: earthquake   File: interface.py    MIT License 5 votes vote down vote up
def freebsd_set_ip_address(self, dev, ip, serverip, netmask):
		sockfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		try:
			#set ip, serverip and netmask
			ifaliasreq = struct.pack('<16sBBHI8sBBHI8sBBHI8sI', self.iface_name,
				16, socket.AF_INET, 0, struct.unpack('<I', socket.inet_aton(ip))[0], '\x00'*8,
				16, socket.AF_INET, 0, struct.unpack('<I', socket.inet_aton(serverip))[0], '\x00'*8,
				16, socket.AF_INET, 0, struct.unpack('<I', socket.inet_aton('255.255.255.255'))[0],
				'\x00'*8,
				0)
			fcntl.ioctl(sockfd, self.IOCTL_FREEBSD_SIOCAIFADDR, ifaliasreq)

			# get flags
			ifr = struct.pack('<16sh', self.iface_name, 0)
			flags = struct.unpack('<16sh', fcntl.ioctl(sockfd, self.IOCTL_FREEBSD_SIOCGIFFLAGS, ifr))[1]

			# set new flags
			flags = flags | self.IOCTL_FREEBSD_IFF_UP
			ifr = struct.pack('<16sh', self.iface_name, flags)

			# iface up
			fcntl.ioctl(sockfd, self.IOCTL_FREEBSD_SIOCSIFFLAGS, ifr)
		except Exception as e:
			common.internal_print("Something went wrong with setting up the interface.", -1)
			print(e)
			sys.exit(-1)

		# adding new route for forwarding packets properly.
		integer_ip = struct.unpack(">I", socket.inet_pton(socket.AF_INET, serverip))[0]
		rangeip = socket.inet_ntop(socket.AF_INET, struct.pack(">I", integer_ip & ((2**int(netmask))-1)<<32-int(netmask)))

		ps = subprocess.Popen(["route", "add", "-net", rangeip+"/"+netmask, serverip], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
		(stdout, stderr) = ps.communicate()
		if stderr:
			if not "File exists" in stderr:
				common.internal_print("Error: adding client route: {0}".format(stderr), -1)
				sys.exit(-1)

		return 
Example 59
Project: sic   Author: Yanixos   File: connection.py    GNU General Public License v3.0 5 votes vote down vote up
def allowed_gai_family():
    """This function is designed to work in the context of
    getaddrinfo, where family=socket.AF_UNSPEC is the default and
    will perform a DNS search for both IPv6 and IPv4 records."""

    family = socket.AF_INET
    if HAS_IPV6:
        family = socket.AF_UNSPEC
    return family 
Example 60
Project: neos-classic-electrum-server   Author: neoscoin   File: stratum_http.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, addr, certfile, keyfile,
                 requestHandler=SSLRequestHandler,
                 logRequests=False, encoding=None, bind_and_activate=True,
                 address_family=socket.AF_INET):

        self.logRequests = logRequests
        StratumJSONRPCDispatcher.__init__(self, encoding)
        # TCPServer.__init__ has an extra parameter on 2.6+, so
        # check Python version and decide on how to call it
        vi = sys.version_info
        self.address_family = address_family
        if USE_UNIX_SOCKETS and address_family == socket.AF_UNIX:
            # Unix sockets can't be bound if they already exist in the
            # filesystem. The convention of e.g. X11 is to unlink
            # before binding again.
            if os.path.exists(addr):
                try:
                    os.unlink(addr)
                except OSError:
                    logging.warning("Could not unlink socket %s", addr)

        SSLTCPServer.__init__(self, addr, certfile, keyfile, requestHandler, bind_and_activate)

        if fcntl is not None and hasattr(fcntl, 'FD_CLOEXEC'):
            flags = fcntl.fcntl(self.fileno(), fcntl.F_GETFD)
            flags |= fcntl.FD_CLOEXEC
            fcntl.fcntl(self.fileno(), fcntl.F_SETFD, flags) 
Example 61
Project: bigquerylayers   Author: smandaric   File: connection.py    GNU General Public License v3.0 5 votes vote down vote up
def allowed_gai_family():
    """This function is designed to work in the context of
    getaddrinfo, where family=socket.AF_UNSPEC is the default and
    will perform a DNS search for both IPv6 and IPv4 records."""

    family = socket.AF_INET
    if HAS_IPV6:
        family = socket.AF_UNSPEC
    return family 
Example 62
Project: ipmisim   Author: rhtyd   File: fakesession.py    Apache License 2.0 5 votes vote down vote up
def _xmit_packet(self, retry=True, delay_xmit=None):
        if self.sequencenumber:
            self.sequencenumber += 1
        if delay_xmit is not None:
            # skip transmit, let retry timer do it's thing
            self.waiting_sessions[self] = {}
            self.waiting_sessions[self]['ipmisession'] = self
            self.waiting_sessions[self]['timeout'] = delay_xmit +  _monotonic_time()
            return  
        if self.sockaddr:
            self.send_data(self.netpacket, self.sockaddr)
        else:
            self.allsockaddrs = []
            try:
                for res in socket.getaddrinfo(self.bmc, self.port, 0, socket.SOCK_DGRAM):
                    sockaddr = res[4]
                    if res[0] == socket.AF_INET:
                        # convert the sockaddr to AF_INET6
                        newhost = '::ffff:' + sockaddr[0]
                        sockaddr = (newhost, sockaddr[1], 0, 0)
                    self.allsockaddrs.append(sockaddr)
                    self.bmc_handlers[sockaddr] = self
                    self.send_data(self.netpacket, sockaddr)
            except socket.gaierror:
                raise exc.IpmiException("Unable to transmit to specified address")
        if retry:
            self.waiting_sessions[self] = {}
            self.waiting_sessions[self]['ipmisession'] = self
            self.waiting_sessions[self]['timeout'] = self.timeout + _monotonic_time() 
Example 63
Project: AshsSDK   Author: thehappydinoa   File: connection.py    MIT License 5 votes vote down vote up
def allowed_gai_family():
    """This function is designed to work in the context of
    getaddrinfo, where family=socket.AF_UNSPEC is the default and
    will perform a DNS search for both IPv6 and IPv4 records."""

    family = socket.AF_INET
    if HAS_IPV6:
        family = socket.AF_UNSPEC
    return family 
Example 64
Project: Kitsu.Bundle   Author: AeonLucid   File: connection.py    MIT License 5 votes vote down vote up
def allowed_gai_family():
    """This function is designed to work in the context of
    getaddrinfo, where family=socket.AF_UNSPEC is the default and
    will perform a DNS search for both IPv6 and IPv4 records."""

    family = socket.AF_INET
    if HAS_IPV6:
        family = socket.AF_UNSPEC
    return family 
Example 65
Project: storjnode   Author: StorjOld   File: util.py    MIT License 5 votes vote down vote up
def get_inet_facing_ip():
    # source http://stackoverflow.com/a/1267524/90351
    try:
        return [l for l in ([ip for ip in socket.gethostbyname_ex(
            socket.gethostname())[2] if not ip.startswith("127.")][:1],
            [[(s.connect(('8.8.8.8', 80)), s.getsockname()[0], s.close())
                for s in [socket.socket(
                    socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0]
    except:  # pragma: no cover
        # inet not reachable
        return None  # pragma: no cover 
Example 66
Project: storjnode   Author: StorjOld   File: util.py    MIT License 5 votes vote down vote up
def valid_ipv4(ip):
    """Returns True if the given string is a valid IPv4 address."""
    try:
        socket.inet_pton(socket.AF_INET, ip)
        return True
    except AttributeError:  # no inet_pton
        try:
            socket.inet_aton(ip)
            return True
        except socket.error:
            return False
    except (socket.error, ValueError) as e:
        return False 
Example 67
Project: storjnode   Author: StorjOld   File: util.py    MIT License 5 votes vote down vote up
def get_unused_port(port):
    """Checks if port is already in use."""
    if port is None or port < 1024 or port > 49151:
        port = random.randint(1024, 49151)
    while True:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            s.bind(('', port))  # Try to open port
        except socket.error as e:
            if e.errno is 98:  # Errorno 98 means address already bound
                port += 1
                continue
            raise e
        s.close()
        return port 
Example 68
Project: ethergeniee   Author: codepaji2006   File: Linux.py    GNU General Public License v2.0 5 votes vote down vote up
def get_family_and_address_for_dev(sa):
        family = sa.sa_family
        addr = None
        if family == AF_INET:
            sa = cast(pointer(sa), POINTER(bsd_sockaddr_in)).contents
            addr = inet_ntop(family, sa.sin_addr)
        elif family == AF_INET6:
            sa = cast(pointer(sa), POINTER(bsd_sockaddr_in6)).contents
            addr = inet_ntop(family, sa.sin6_addr)
        return family, addr 
Example 69
Project: ethergeniee   Author: codepaji2006   File: Linux.py    GNU General Public License v2.0 5 votes vote down vote up
def __str__(self):
            return "%s [index=%d, IPv4=%s, IPv6=%s]" % (
                self.name, self.index,
                self.addresses.get(AF_INET),
                self.addresses.get(AF_INET6)) 
Example 70
Project: calico-upgrade   Author: projectcalico   File: utils.py    Apache License 2.0 5 votes vote down vote up
def get_ip(v6=False):
    """
    Return a string of the IP of the hosts interface.
    Try to get the local IP from the environment variables.  This allows
    testers to specify the IP address in cases where there is more than one
    configured IP address for the test system.
    """
    env = LOCAL_IPv6_ENV if v6 else LOCAL_IP_ENV
    ip = os.environ.get(env)
    if not ip:
        logger.debug("%s not set; try to auto detect IP.", env)
        socket_type = socket.AF_INET6 if v6 else socket.AF_INET
        s = socket.socket(socket_type, socket.SOCK_DGRAM)
        remote_ip = "2001:4860:4860::8888" if v6 else "8.8.8.8"
        s.connect((remote_ip, 0))
        ip = s.getsockname()[0]
        s.close()
    else:
        logger.debug("Got local IP from %s=%s", env, ip)

    return ip


# Some of the commands we execute like to mess with the TTY configuration,
# which can break the output formatting. As a workaround, save off the
# terminal settings and restore them after each command. 
Example 71
Project: robot   Author: meyer-net   File: socket.py    MIT License 5 votes vote down vote up
def run(self):
        serversocket = socket.socket(
            socket.AF_INET, socket.SOCK_STREAM)
        serversocket.bind((self._host, self._port))
        serversocket.listen(5)
        (clientsocket, address) = serversocket.accept()

        try:
            all_data = []
            while True:
                data = clientsocket.recv(1024)
                if not data:
                    break

                all_data.append(data)
                print(bytes.decode(data))
                # for v in msg.split('|')[:-1]:
                #     print(v)

                #     try:
                #         file.seek(0)
                #         file.write(v)
                #         file.flush()
                #     except Exception as err:
                #         print(err)
        except Exception as err:
            print(err)

        print("*** Done receiving ***")
        clientsocket.close()
        serversocket.close() 
Example 72
Project: ngo-addons-backport   Author: camptocamp   File: tiny_socket.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, sock=None):
        if sock is None:
            self.sock = socket.socket(
            socket.AF_INET, socket.SOCK_STREAM)
        else:
            self.sock = sock
        self.sock.settimeout(120) 
Example 73
Project: dvrip   Author: alexshpilkin   File: time.py    Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def run(host: str,
        serv: int,
        username: str,
        password: str,
        args: List[str]
       ) -> None:
	if args:
		from dateparser import parse  # type: ignore
		time = parse(args[0])
		if len(args) > 2 or time is None or time.tzinfo is not None:
			usage()

	conn = DVRIPClient(Socket(AF_INET, SOCK_STREAM))
	conn.connect((host, serv), username, password)
	print((conn.time(time) if args else conn.time()).isoformat()) 
Example 74
Project: dvrip   Author: alexshpilkin   File: reboot.py    Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def run(host: str,
        serv: int,
        username: str,
        password: str,
        args: List[str]
       ) -> None:
	if args:
		usage()

	conn = DVRIPClient(Socket(AF_INET, SOCK_STREAM))
	conn.connect((host, serv), username, password)
	conn.reboot() 
Example 75
Project: dvrip   Author: alexshpilkin   File: log.py    Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def run(host: str,
        serv: int,
        username: str,
        password: str,
        args: List[str]
       ) -> None:
	try:
		opts, args = getopt(args, 's:e:')
	except GetoptError:
		usage()
	if args:
		usage()

	start = EPOCH
	end = datetime.now()
	for opt, arg in opts:
		if opt == '-s':
			from dateparser import parse  # type: ignore
			start = parse(arg)
			if start is None:
				usage()
		if opt == '-e':
			from dateparser import parse  # type: ignore
			end = parse(arg)
			if end is None:
				usage()

	conn = DVRIPClient(Socket(AF_INET, SOCK_STREAM))
	conn.connect((host, serv), username, password)
	try:
		for entry in conn.log(start=start, end=end):
			print('{:>8} {} {:>12} {}'
			      .format(entry.number,
			              entry.time.isoformat(),
			              entry.type.name.lower(),
			              entry.data))
	finally:
		conn.logout() 
Example 76
Project: pyblish-win   Author: pyblish   File: _pslinux.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def decode_address(self, addr, family):
        """Accept an "ip:port" address as displayed in /proc/net/*
        and convert it into a human readable form, like:

        "0500000A:0016" -> ("10.0.0.5", 22)
        "0000000000000000FFFF00000100007F:9E49" -> ("::ffff:127.0.0.1", 40521)

        The IP address portion is a little or big endian four-byte
        hexadecimal number; that is, the least significant byte is listed
        first, so we need to reverse the order of the bytes to convert it
        to an IP address.
        The port is represented as a two-byte hexadecimal number.

        Reference:
        http://linuxdevcenter.com/pub/a/linux/2000/11/16/LinuxAdmin.html
        """
        ip, port = addr.split(':')
        port = int(port, 16)
        # this usually refers to a local socket in listen mode with
        # no end-points connected
        if not port:
            return ()
        if PY3:
            ip = ip.encode('ascii')
        if family == socket.AF_INET:
            # see: https://github.com/giampaolo/psutil/issues/201
            if sys.byteorder == 'little':
                ip = socket.inet_ntop(family, base64.b16decode(ip)[::-1])
            else:
                ip = socket.inet_ntop(family, base64.b16decode(ip))
        else:  # IPv6
            # old version - let's keep it, just in case...
            # ip = ip.decode('hex')
            # return socket.inet_ntop(socket.AF_INET6,
            #          ''.join(ip[i:i+4][::-1] for i in xrange(0, 16, 4)))
            ip = base64.b16decode(ip)
            # see: https://github.com/giampaolo/psutil/issues/201
            if sys.byteorder == 'little':
                ip = socket.inet_ntop(
                    socket.AF_INET6,
                    struct.pack('>4I', *struct.unpack('<4I', ip)))
            else:
                ip = socket.inet_ntop(
                    socket.AF_INET6,
                    struct.pack('<4I', *struct.unpack('<4I', ip)))
        return (ip, port) 
Example 77
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def testFromFd(self):
        # Testing fromfd()
        fd = self.cli_conn.fileno()
        sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
        self.addCleanup(sock.close)
        msg = sock.recv(1024)
        self.assertEqual(msg, MSG) 
Example 78
Project: pyblish-win   Author: pyblish   File: test_support.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM):
    """Returns an unused port that should be suitable for binding.  This is
    achieved by creating a temporary socket with the same family and type as
    the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to
    the specified host address (defaults to 0.0.0.0) with the port set to 0,
    eliciting an unused ephemeral port from the OS.  The temporary socket is
    then closed and deleted, and the ephemeral port is returned.

    Either this method or bind_port() should be used for any tests where a
    server socket needs to be bound to a particular port for the duration of
    the test.  Which one to use depends on whether the calling code is creating
    a python socket, or if an unused port needs to be provided in a constructor
    or passed to an external program (i.e. the -accept argument to openssl's
    s_server mode).  Always prefer bind_port() over find_unused_port() where
    possible.  Hard coded ports should *NEVER* be used.  As soon as a server
    socket is bound to a hard coded port, the ability to run multiple instances
    of the test simultaneously on the same host is compromised, which makes the
    test a ticking time bomb in a buildbot environment. On Unix buildbots, this
    may simply manifest as a failed test, which can be recovered from without
    intervention in most cases, but on Windows, the entire python process can
    completely and utterly wedge, requiring someone to log in to the buildbot
    and manually kill the affected process.

    (This is easy to reproduce on Windows, unfortunately, and can be traced to
    the SO_REUSEADDR socket option having different semantics on Windows versus
    Unix/Linux.  On Unix, you can't have two AF_INET SOCK_STREAM sockets bind,
    listen and then accept connections on identical host/ports.  An EADDRINUSE
    socket.error will be raised at some point (depending on the platform and
    the order bind and listen were called on each socket).

    However, on Windows, if SO_REUSEADDR is set on the sockets, no EADDRINUSE
    will ever be raised when attempting to bind two identical host/ports. When
    accept() is called on each socket, the second caller's process will steal
    the port from the first caller, leaving them both in an awkwardly wedged
    state where they'll no longer respond to any signals or graceful kills, and
    must be forcibly killed via OpenProcess()/TerminateProcess().

    The solution on Windows is to use the SO_EXCLUSIVEADDRUSE socket option
    instead of SO_REUSEADDR, which effectively affords the same semantics as
    SO_REUSEADDR on Unix.  Given the propensity of Unix developers in the Open
    Source world compared to Windows ones, this is a common mistake.  A quick
    look over OpenSSL's 0.9.8g source shows that they use SO_REUSEADDR when
    openssl.exe is called with the 's_server' option, for example. See
    http://bugs.python.org/issue2550 for more info.  The following site also
    has a very thorough description about the implications of both REUSEADDR
    and EXCLUSIVEADDRUSE on Windows:
    http://msdn2.microsoft.com/en-us/library/ms740621(VS.85).aspx)

    XXX: although this approach is a vast improvement on previous attempts to
    elicit unused ports, it rests heavily on the assumption that the ephemeral
    port returned to us by the OS won't immediately be dished back out to some
    other process when we close and delete our temporary socket but before our
    calling code has a chance to bind the returned port.  We can deal with this
    issue if/when we come across it."""
    tempsock = socket.socket(family, socktype)
    port = bind_port(tempsock)
    tempsock.close()
    del tempsock
    return port 
Example 79
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: wsgi.py    Apache License 2.0 4 votes vote down vote up
def __init__(self, name, app, host='0.0.0.0', port=0, pool_size=None,
                       protocol=eventlet.wsgi.HttpProtocol, backlog=128,
                       use_ssl=False, max_url_len=None):
        """Initialize, but do not start, a WSGI server.

        :param name: Pretty name for logging.
        :param app: The WSGI application to serve.
        :param host: IP address to serve the application.
        :param port: Port number to server the application.
        :param pool_size: Maximum number of eventlets to spawn concurrently.
        :param backlog: Maximum number of queued connections.
        :param max_url_len: Maximum length of permitted URLs.
        :returns: None
        :raises: nova.exception.InvalidInput
        """
        # Allow operators to customize http requests max header line size.
        eventlet.wsgi.MAX_HEADER_LINE = CONF.wsgi.max_header_line
        self.name = name
        self.app = app
        self._server = None
        self._protocol = protocol
        self.pool_size = pool_size or self.default_pool_size
        self._pool = eventlet.GreenPool(self.pool_size)
        self._logger = logging.getLogger("nova.%s.wsgi.server" % self.name)
        self._use_ssl = use_ssl
        self._max_url_len = max_url_len
        self.client_socket_timeout = CONF.wsgi.client_socket_timeout or None

        if backlog < 1:
            raise exception.InvalidInput(
                    reason=_('The backlog must be more than 0'))

        bind_addr = (host, port)
        # TODO(dims): eventlet's green dns/socket module does not actually
        # support IPv6 in getaddrinfo(). We need to get around this in the
        # future or monitor upstream for a fix
        try:
            info = socket.getaddrinfo(bind_addr[0],
                                      bind_addr[1],
                                      socket.AF_UNSPEC,
                                      socket.SOCK_STREAM)[0]
            family = info[0]
            bind_addr = info[-1]
        except Exception:
            family = socket.AF_INET

        try:
            self._socket = eventlet.listen(bind_addr, family, backlog=backlog)
        except EnvironmentError:
            LOG.error(_LE("Could not bind to %(host)s:%(port)s"),
                      {'host': host, 'port': port})
            raise

        (self.host, self.port) = self._socket.getsockname()[0:2]
        LOG.info(_LI("%(name)s listening on %(host)s:%(port)s"),
                 {'name': self.name, 'host': self.host, 'port': self.port}) 
Example 80
Project: dvrip   Author: alexshpilkin   File: info.py    Creative Commons Zero v1.0 Universal 4 votes vote down vote up
def run(host: str,  # pylint: disable=too-many-branches,too-many-locals
        serv: int,
        username: str,
        password: str,
        args: List[str]
       ) -> None:
	if args:
		usage()

	conn = DVRIPClient(Socket(AF_INET, SOCK_STREAM))
	conn.connect((host, serv), username, password)

	info = conn.systeminfo()
	line = [info.chassis, info.board, info.serial]
	for attr in ('hardware', 'eeprom', 'software', 'build', 'videoin',
	             'videoout', 'commin', 'commout', 'triggerin',
	             'triggerout', 'audioin', 'views'):
		value = getattr(info, attr)
		if value:
			line.append('{} {}'.format(attr, value))
	print(' '.join(line))  # system line

	for disk in conn.storageinfo():
		print('disk {}:'.format(disk.number))  # disk group
		for i, part in zip(range(disk.parts), disk.partinfo):
			line = ['  part {}'.format(i)]
			if part.current:
				line.append('current')
			line.append('size {}M free {}M'
			            .format(part.size, part.free))
			for attr in ('viewedstart', 'viewedend',
			             'unviewedstart', 'unviewedend'):
				date = getattr(part, attr)
				line.append('{} {}'
				            .format(attr, date.isoformat()))
			print(' '.join(line))  # partition line

	actv = conn.activityinfo()
	line = []
	for i, chan in zip(range(info.videoin), actv.channels):
		print('channel {} bitrate {}K/s'.format(i, chan.bitrate) +
		      (' recording' if chan.recording else ''))

	line = []
	line.append(conn.time().isoformat())
	minutes = info.uptime
	hours, minutes = divmod(minutes, 60)
	days, hours = divmod(hours, 24)
	if days:
		line.append("up P{}dT{:02}h{:02}m".format(days, hours, minutes))
	else:
		line.append("up PT{}h{:02}m".format(hours, minutes))
	line.append('triggers')
	for attr in ('in_', 'out', 'obscure', 'disconnect', 'motion'):
		value = getattr(actv.triggers, attr)
		if value:
			line.append('{} {}'.format(attr.rstrip('_'), value))
	if len(line) <= 3:
		line.append('none')
	print(' '.join(line))  # status line