Python socket.bind() Examples

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

You may also check out all available functions/classes of the module socket , or try the search function .

Example 1
Project: Safejumper-for-Desktop   Author: proxysh   File: tcp.py    License: GNU General Public License v2.0 6 votes vote down vote up
def _resolveIPv6(ip, port):
    """
    Resolve an IPv6 literal into an IPv6 address.

    This is necessary to resolve any embedded scope identifiers to the relevant
    C{sin6_scope_id} for use with C{socket.connect()}, C{socket.listen()}, or
    C{socket.bind()}; see U{RFC 3493 <https://tools.ietf.org/html/rfc3493>} for
    more information.

    @param ip: An IPv6 address literal.
    @type ip: C{str}

    @param port: A port number.
    @type port: C{int}

    @return: a 4-tuple of C{(host, port, flow, scope)}, suitable for use as an
        IPv6 address.

    @raise socket.gaierror: if either the IP or port is not numeric as it
        should be.
    """
    return socket.getaddrinfo(ip, port, 0, 0, 0, _NUMERIC_ONLY)[0][4] 
Example 2
Project: learn_python3_spider   Author: wistbean   File: tcp.py    License: MIT License 6 votes vote down vote up
def _resolveIPv6(ip, port):
    """
    Resolve an IPv6 literal into an IPv6 address.

    This is necessary to resolve any embedded scope identifiers to the relevant
    C{sin6_scope_id} for use with C{socket.connect()}, C{socket.listen()}, or
    C{socket.bind()}; see U{RFC 3493 <https://tools.ietf.org/html/rfc3493>} for
    more information.

    @param ip: An IPv6 address literal.
    @type ip: C{str}

    @param port: A port number.
    @type port: C{int}

    @return: a 4-tuple of C{(host, port, flow, scope)}, suitable for use as an
        IPv6 address.

    @raise socket.gaierror: if either the IP or port is not numeric as it
        should be.
    """
    return socket.getaddrinfo(ip, port, 0, 0, 0, _NUMERIC_ONLY)[0][4] 
Example 3
Project: CTFCrackTools-V2   Author: Acmesec   File: test_socket.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _testTCPServerOption(self, level, option, values):
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self._testSetAndGetOption(sock, level, option, values)
            # now bind and listen on the socket i.e. cause the implementation socket to be created
            sock.bind( (HOST, PORT) )
            sock.listen(50)
            retrieved_option_value = sock.getsockopt(level, option)
            msg = "TCP server option value '(%s,%s)'='%s' did not propagate to implementation socket. Got %s" % (level, option, values[-1], retrieved_option_value)
            if option == socket.SO_RCVBUF:
                # NOTE: see similar bsd/solaris workaround above
                self.assert_(retrieved_option_value >= values[-1], msg)
            else:
                self.failUnlessEqual(retrieved_option_value, values[-1], msg)
            self._testSetAndGetOption(sock, level, option, values)
        finally:
            sock.close() 
Example 4
Project: CTFCrackTools-V2   Author: Acmesec   File: test_socket.py    License: GNU General Public License v3.0 6 votes vote down vote up
def testSO_ERROR(self):
        good = bad = None

        try:
            good = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            good.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            good.bind((HOST, PORT))
            good.listen(1)
            bad = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            bad.bind((HOST, PORT))
            bad.listen(1)
            self.fail("Listen operation against same port did not generate an expected error")
        except socket.error, se:
            self.failUnlessEqual(bad.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR), se[0])
            # try again, should now be reset
            self.failUnlessEqual(bad.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR), 0) 
Example 5
Project: CTFCrackTools   Author: Acmesec   File: test_socket.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _testTCPServerOption(self, level, option, values):
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self._testSetAndGetOption(sock, level, option, values)
            # now bind and listen on the socket i.e. cause the implementation socket to be created
            sock.bind( (HOST, PORT) )
            sock.listen(50)
            retrieved_option_value = sock.getsockopt(level, option)
            msg = "TCP server option value '(%s,%s)'='%s' did not propagate to implementation socket. Got %s" % (level, option, values[-1], retrieved_option_value)
            if option == socket.SO_RCVBUF:
                # NOTE: see similar bsd/solaris workaround above
                self.assert_(retrieved_option_value >= values[-1], msg)
            else:
                self.failUnlessEqual(retrieved_option_value, values[-1], msg)
            self._testSetAndGetOption(sock, level, option, values)
        finally:
            sock.close() 
Example 6
Project: CTFCrackTools   Author: Acmesec   File: test_socket.py    License: GNU General Public License v3.0 6 votes vote down vote up
def testSO_ERROR(self):
        good = bad = None

        try:
            good = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            good.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            good.bind((HOST, PORT))
            good.listen(1)
            bad = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            bad.bind((HOST, PORT))
            bad.listen(1)
            self.fail("Listen operation against same port did not generate an expected error")
        except socket.error, se:
            self.failUnlessEqual(bad.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR), se[0])
            # try again, should now be reset
            self.failUnlessEqual(bad.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR), 0) 
Example 7
Project: Automatic-Youtube-Reddit-Text-To-Speech-Video-Generator-and-Uploader   Author: HA6Bots   File: socketservervideogenerator.py    License: MIT License 5 votes vote down vote up
def startVideoGeneratorServer():
    server_address = (settings.server_location, int(settings.server_port_vid_gen))
    print('Starting video generator server on %s port %s' % server_address)
    socket.bind(server_address)
    socket.listen(5)
    thread = Thread(target=waitConnect)
    thread.start()
    servertick = Thread(target=serverTick)
    servertick.start() 
Example 8
Project: recruit   Author: Frank-qlu   File: serving.py    License: Apache License 2.0 5 votes vote down vote up
def get_sockaddr(host, port, family):
    """Return a fully qualified socket address that can be passed to
    :func:`socket.bind`."""
    if family == af_unix:
        return host.split("://", 1)[1]
    try:
        res = socket.getaddrinfo(
            host, port, family, socket.SOCK_STREAM, socket.IPPROTO_TCP
        )
    except socket.gaierror:
        return host, port
    return res[0][4] 
Example 9
Project: Safejumper-for-Desktop   Author: proxysh   File: tcp.py    License: GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, host, port, bindAddress, connector, reactor=None):
        # BaseClient.__init__ is invoked later
        self.connector = connector
        self.addr = (host, port)

        whenDone = self.resolveAddress
        err = None
        skt = None

        if abstract.isIPAddress(host):
            self._requiresResolution = False
        elif abstract.isIPv6Address(host):
            self._requiresResolution = False
            self.addr = _resolveIPv6(host, port)
            self.addressFamily = socket.AF_INET6
            self._addressType = address.IPv6Address
        else:
            self._requiresResolution = True
        try:
            skt = self.createInternetSocket()
        except socket.error as se:
            err = error.ConnectBindError(se.args[0], se.args[1])
            whenDone = None
        if whenDone and bindAddress is not None:
            try:
                if abstract.isIPv6Address(bindAddress[0]):
                    bindinfo = _resolveIPv6(*bindAddress)
                else:
                    bindinfo = bindAddress
                skt.bind(bindinfo)
            except socket.error as se:
                err = error.ConnectBindError(se.args[0], se.args[1])
                whenDone = None
        self._finishInit(whenDone, skt, err, reactor) 
Example 10
Project: Safejumper-for-Desktop   Author: proxysh   File: tcp.py    License: GNU General Public License v2.0 5 votes vote down vote up
def startListening(self):
        """Create and bind my socket, and begin listening on it.

        This is called on unserialization, and must be called after creating a
        server to begin listening on the specified port.
        """
        if self._preexistingSocket is None:
            # Create a new socket and make it listen
            try:
                skt = self.createInternetSocket()
                if self.addressFamily == socket.AF_INET6:
                    addr = _resolveIPv6(self.interface, self.port)
                else:
                    addr = (self.interface, self.port)
                skt.bind(addr)
            except socket.error as le:
                raise CannotListenError(self.interface, self.port, le)
            skt.listen(self.backlog)
        else:
            # Re-use the externally specified socket
            skt = self._preexistingSocket
            self._preexistingSocket = None
            # Avoid shutting it down at the end.
            self._shouldShutdown = False

        # Make sure that if we listened on port 0, we update that to
        # reflect what the OS actually assigned us.
        self._realPortNumber = skt.getsockname()[1]

        log.msg("%s starting on %s" % (
                self._getLogPrefix(self.factory), self._realPortNumber))

        # The order of the next 5 lines is kind of bizarre.  If no one
        # can explain it, perhaps we should re-arrange them.
        self.factory.doStart()
        self.connected = True
        self.socket = skt
        self.fileno = self.socket.fileno
        self.numberAccepts = 100

        self.startReading() 
Example 11
Project: Building-Recommendation-Systems-with-Python   Author: PacktPublishing   File: serving.py    License: MIT License 5 votes vote down vote up
def get_sockaddr(host, port, family):
    """Return a fully qualified socket address that can be passed to
    :func:`socket.bind`."""
    if family == af_unix:
        return host.split("://", 1)[1]
    try:
        res = socket.getaddrinfo(
            host, port, family, socket.SOCK_STREAM, socket.IPPROTO_TCP
        )
    except socket.gaierror:
        return host, port
    return res[0][4] 
Example 12
Project: Building-Recommendation-Systems-with-Python   Author: PacktPublishing   File: serving.py    License: MIT License 5 votes vote down vote up
def get_sockaddr(host, port, family):
    """Return a fully qualified socket address that can be passed to
    :func:`socket.bind`."""
    if family == af_unix:
        return host.split("://", 1)[1]
    try:
        res = socket.getaddrinfo(
            host, port, family, socket.SOCK_STREAM, socket.IPPROTO_TCP
        )
    except socket.gaierror:
        return host, port
    return res[0][4] 
Example 13
Project: scylla   Author: acaceres2176   File: serving.py    License: Apache License 2.0 5 votes vote down vote up
def get_sockaddr(host, port, family):
    """Return a fully qualified socket address that can be passed to
    :func:`socket.bind`."""
    if family == af_unix:
        return host.split("://", 1)[1]
    try:
        res = socket.getaddrinfo(
            host, port, family, socket.SOCK_STREAM, socket.IPPROTO_TCP
        )
    except socket.gaierror:
        return host, port
    return res[0][4] 
Example 14
Project: learn_python3_spider   Author: wistbean   File: tcp.py    License: MIT License 5 votes vote down vote up
def __init__(self, host, port, bindAddress, connector, reactor=None):
        # BaseClient.__init__ is invoked later
        self.connector = connector
        self.addr = (host, port)

        whenDone = self.resolveAddress
        err = None
        skt = None

        if abstract.isIPAddress(host):
            self._requiresResolution = False
        elif abstract.isIPv6Address(host):
            self._requiresResolution = False
            self.addr = _resolveIPv6(host, port)
            self.addressFamily = socket.AF_INET6
            self._addressType = address.IPv6Address
        else:
            self._requiresResolution = True
        try:
            skt = self.createInternetSocket()
        except socket.error as se:
            err = error.ConnectBindError(se.args[0], se.args[1])
            whenDone = None
        if whenDone and bindAddress is not None:
            try:
                if abstract.isIPv6Address(bindAddress[0]):
                    bindinfo = _resolveIPv6(*bindAddress)
                else:
                    bindinfo = bindAddress
                skt.bind(bindinfo)
            except socket.error as se:
                err = error.ConnectBindError(se.args[0], se.args[1])
                whenDone = None
        self._finishInit(whenDone, skt, err, reactor) 
Example 15
Project: medicare-demo   Author: ofermend   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def setUp(self):
        self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.serv.bind((self.HOST, self.PORT))
        self.serv.listen(1) 
Example 16
Project: medicare-demo   Author: ofermend   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def setUp(self):
        self.serv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.serv.bind((self.HOST, self.PORT)) 
Example 17
Project: medicare-demo   Author: ofermend   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def testSockName(self):
        # Testing getsockname()
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.bind(("0.0.0.0", PORT+1))
        name = sock.getsockname()
        self.assertEqual(name, ("0.0.0.0", PORT+1)) 
Example 18
Project: medicare-demo   Author: ofermend   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def _testUDPOption(self, level, option, values):
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            self._testSetAndGetOption(sock, level, option, values)
            # now bind the socket i.e. cause the implementation socket to be created
            sock.bind( (HOST, PORT) )
            self.failUnlessEqual(sock.getsockopt(level, option), values[-1], \
                 "Option value '(%s, %s)'='%s' did not propagate to implementation socket" % (level, option, values[-1]) )
            self._testSetAndGetOption(sock, level, option, values)
        finally:
            sock.close() 
Example 19
Project: medicare-demo   Author: ofermend   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def _testTCPClientOption(self, level, option, values):
        sock = None
        try:
            # First listen on a server socket, so that the connection won't be refused.
            server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            server_sock.bind( (HOST, PORT) )
            server_sock.listen(50)
            # Now do the tests
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self._testSetAndGetOption(sock, level, option, values)
            # now connect the socket i.e. cause the implementation socket to be created
            # First bind, so that the SO_REUSEADDR setting propagates
            sock.bind( (HOST, PORT+1) )
            sock.connect( (HOST, PORT) )
            msg = "Option value '%s'='%s' did not propagate to implementation socket" % (option, values[-1])
            if option in (socket.SO_RCVBUF, socket.SO_SNDBUF):
                # NOTE: there's no guarantee that bufsize will be the
                # exact setsockopt value, particularly after
                # establishing a connection. seems it will be *at least*
                # the values we test (which are rather small) on
                # BSDs.
                self.assert_(sock.getsockopt(level, option) >= values[-1], msg)
            else:
                self.failUnlessEqual(sock.getsockopt(level, option), values[-1], msg)
            self._testSetAndGetOption(sock, level, option, values)
        finally:
            server_sock.close()
            if sock:
                sock.close() 
Example 20
Project: medicare-demo   Author: ofermend   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def testBindSpecific(self):
        self.sock.bind( (self.HOST, self.PORT) ) # Use a specific port
        actual_port = self.sock.getsockname()[1]
        self.failUnless(actual_port == self.PORT,
            "Binding to specific port number should have returned same number: %d != %d" % (actual_port, self.PORT)) 
Example 21
Project: medicare-demo   Author: ofermend   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def testBindEphemeral(self):
        self.sock.bind( (self.HOST, 0) ) # let system choose a free port
        self.failUnless(self.sock.getsockname()[1] != 0, "Binding to port zero should have allocated an ephemeral port number") 
Example 22
Project: medicare-demo   Author: ofermend   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def testShutdown(self):
        self.sock.bind( (self.HOST, self.PORT) )
        self.sock.shutdown(socket.SHUT_RDWR) 
Example 23
Project: medicare-demo   Author: ofermend   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def testBroadcast(self):
        self.serv.bind( ("", self.PORT) )
        msg = self.serv.recv(len(EIGHT_BIT_MSG))
        self.assertEqual(msg, EIGHT_BIT_MSG) 
Example 24
Project: medicare-demo   Author: ofermend   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def _testNonBlockingConnect(self):
        # Testing non-blocking connect
        self.cli.setblocking(0)
        result = self.cli.connect_ex((self.HOST, self.PORT))
        rfds, wfds, xfds = select.select([], [self.cli], [])
        self.failUnless(self.cli in wfds)
        try:
            self.cli.send(MSG)
        except socket.error:
            self.fail("Sending on connected socket should not have raised socket.error")

    #
    # AMAK: 20070518
    # Introduced a new test for connect with bind to specific local address
    # 
Example 25
Project: medicare-demo   Author: ofermend   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def testBindException(self):
        # First bind to the target port
        self.s.bind( (HOST, PORT) )
        self.s.listen(50)
        try:
            # And then try to bind again
            t = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            t.bind( (HOST, PORT) )
            t.listen(50)
        except socket.error, se:
            self.failUnlessEqual(se[0], errno.EADDRINUSE) 
Example 26
Project: medicare-demo   Author: ofermend   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def testBindException(self):
        # First bind to the target port
        self.s.bind( (HOST, PORT) )
        try:
            # And then try to bind again
            t = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            t.bind( (HOST, PORT) )
        except socket.error, se:
            self.failUnlessEqual(se[0], errno.EADDRINUSE) 
Example 27
Project: medicare-demo   Author: ofermend   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def testBindNonTupleEndpointRaisesTypeError(self):
        try:
            self.socket.bind(HOST, PORT)
        except TypeError:
            pass
        else:
            self.fail("Illegal non-tuple bind address did not raise TypeError") 
Example 28
Project: medicare-demo   Author: ofermend   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def testAddrTupleIDNAHostname(self):
        idna_domain = u"al\u00e1n.com"
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        if socket.supports('idna'):
            try:
                s.bind( (idna_domain, 80) )
            except socket.error:
                # We're not worried about socket errors, i.e. bind problems, etc.
                pass
            except Exception, x:
                self.fail("Unexpected exception raised for socket.bind(%s)" % repr(idna_domain)) 
Example 29
Project: medicare-demo   Author: ofermend   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def testGetsocknameBoundNoImpl(self):
        self.s.bind( ("localhost", 0) )
        try:
            self.s.getsockname()
        except socket.error, se:
            self.fail("getsockname() on bound socket should have not raised socket.error") 
Example 30
Project: medicare-demo   Author: ofermend   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def _create_impl_socket(self):
        self.s.bind(("localhost", 0))
        self.s.listen(5) 
Example 31
Project: medicare-demo   Author: ofermend   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def _create_impl_socket(self):
        # Binding is enough to cause socket impl creation
        self.s.bind(("localhost", 0)) 
Example 32
Project: medicare-demo   Author: ofermend   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def testGetpeernameImplCreatedAndConnected(self):
        # This test also tests that an UDP socket can be bound and connected at the same time
        self._create_impl_socket()
        # Need to connect to an UDP port
        self._udp_peer = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self._udp_peer.bind( ("localhost", 0) )
        self.s.connect(self._udp_peer.getsockname())
        try:
            try:
                self.s.getpeername()
            except socket.error, se:
                self.fail("getpeername() on connected UDP socket should not have raised socket.error")
            self.failUnlessEqual(self.s.getpeername(), self._udp_peer.getsockname()) 
Example 33
Project: CTFCrackTools-V2   Author: Acmesec   File: test_socket.py    License: GNU 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.serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.serv.bind((self.HOST, self.PORT))
        self.serv.listen(1) 
Example 34
Project: CTFCrackTools-V2   Author: Acmesec   File: test_socket.py    License: GNU 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.serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.serv.bind((self.HOST, self.PORT)) 
Example 35
Project: CTFCrackTools-V2   Author: Acmesec   File: test_socket.py    License: GNU General Public License v3.0 5 votes vote down vote up
def testSockName(self):
        # Testing getsockname()
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.bind(("0.0.0.0", PORT+1))
        name = sock.getsockname()
        self.assertEqual(name, ("0.0.0.0", PORT+1)) 
Example 36
Project: CTFCrackTools-V2   Author: Acmesec   File: test_socket.py    License: GNU General Public License v3.0 5 votes vote down vote up
def testSockNameEphemeralV4(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.bind(('', 0))
        sock.listen(1)
        name = sock.getsockname()
        self.assertEqual(len(name), 2)
        self.assertNotEqual(name[1], 0) 
Example 37
Project: CTFCrackTools-V2   Author: Acmesec   File: test_socket.py    License: GNU General Public License v3.0 5 votes vote down vote up
def testSockNameEphemeralV6(self):
        sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
        sock.bind(('', 0, 0, 0))
        sock.listen(1)
        name = sock.getsockname()
        self.assertEqual(len(name), 4)
        self.assertNotEqual(name[1], 0) 
Example 38
Project: CTFCrackTools-V2   Author: Acmesec   File: test_socket.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _testTCPClientOption(self, level, option, values):
        sock = None
        try:
            # First listen on a server socket, so that the connection won't be refused.
            server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            server_sock.bind( (HOST, PORT) )
            server_sock.listen(50)
            # Now do the tests
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self._testSetAndGetOption(sock, level, option, values)
            # now connect the socket i.e. cause the implementation socket to be created
            # First bind, so that the SO_REUSEADDR setting propagates
            #sock.bind( (HOST, PORT+1) )
            sock.connect( (HOST, PORT) )
            retrieved_option_value = sock.getsockopt(level, option)
            msg = "TCP client option value '%s'='%s' did not propagate to implementation socket: got %s" % (option, values[-1], retrieved_option_value)
            if option in (socket.SO_RCVBUF, socket.SO_SNDBUF):
                # NOTE: there's no guarantee that bufsize will be the
                # exact setsockopt value, particularly after
                # establishing a connection. seems it will be *at least*
                # the values we test (which are rather small) on
                # BSDs.
                self.assert_(retrieved_option_value >= values[-1], msg)
            else:
                self.failUnlessEqual(retrieved_option_value, values[-1], msg)
            self._testSetAndGetOption(sock, level, option, values)
        finally:
            server_sock.close()
            if sock:
                sock.close()
            pass 
Example 39
Project: CTFCrackTools-V2   Author: Acmesec   File: test_socket.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _testTCPClientInheritedOption(self, level, option, values):
        cli_sock = accepted_sock = None
        try:
            server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self._testSetAndGetOption(server_sock, level, option, values)
            # now bind and listen on the socket i.e. cause the implementation socket to be created
            server_sock.bind( (HOST, PORT) )
            server_sock.listen(50)
            # Now create client socket to connect to server
            cli_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            cli_sock.connect( (HOST, PORT) )
            accepted_sock = server_sock.accept()[0]
            retrieved_option_value = accepted_sock.getsockopt(level, option)
            msg = "TCP client inherited option value '(%s,%s)'='%s' did not propagate to accepted socket: got %s" % (level, option, values[-1], retrieved_option_value)
            if option == socket.SO_RCVBUF:
                # NOTE: see similar bsd/solaris workaround above
                self.assert_(retrieved_option_value >= values[-1], msg)
            else:
                self.failUnlessEqual(retrieved_option_value, values[-1], msg)
            self._testSetAndGetOption(accepted_sock, level, option, values)
        finally:
            server_sock.close()
            time.sleep(1)
            if cli_sock:
                cli_sock.close()
            if accepted_sock:
                accepted_sock.close() 
Example 40
Project: CTFCrackTools-V2   Author: Acmesec   File: test_socket.py    License: GNU General Public License v3.0 5 votes vote down vote up
def testBindSpecific(self):
        self.sock.bind( (self.HOST, self.PORT) ) # Use a specific port
        actual_port = self.sock.getsockname()[1]
        self.failUnless(actual_port == self.PORT,
            "Binding to specific port number should have returned same number: %d != %d" % (actual_port, self.PORT)) 
Example 41
Project: CTFCrackTools-V2   Author: Acmesec   File: test_socket.py    License: GNU General Public License v3.0 5 votes vote down vote up
def testShutdown(self):
        self.sock.bind( (self.HOST, self.PORT) )
        self.sock.shutdown(socket.SHUT_RDWR) 
Example 42
Project: CTFCrackTools-V2   Author: Acmesec   File: test_socket.py    License: GNU General Public License v3.0 5 votes vote down vote up
def testBroadcast(self):
        self.serv.bind( ("", self.PORT) )
        msg = self.serv.recv(len(EIGHT_BIT_MSG))
        self.assertEqual(msg, EIGHT_BIT_MSG) 
Example 43
Project: CTFCrackTools-V2   Author: Acmesec   File: test_socket.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _testConnectWithLocalBind(self):
        # Testing blocking connect with local bind
        cli_port = self.PORT - 1
        start = time.time()
        while True:
            # Keep trying until a local port is available
            self.cli.settimeout(1)
            self.cli.bind( (self.HOST, cli_port) )
            try:
                self.cli.connect((self.HOST, self.PORT))
                break
            except socket.error, se:
                # cli_port is in use (maybe in TIME_WAIT state from a
                # previous test run). reset the client socket and try
                # again
                self.failUnlessEqual(se[0], errno.EADDRINUSE)
                print "Got an error in connect, will retry", se
                try:
                    self.cli.close()
                except socket.error:
                    pass
                self.clientSetUp()
                cli_port -= 1
            # Make sure we have no tests currently holding open this socket
            test_support.gc_collect()
            if time.time() - start > 5:
                self.fail("Timed out after 5 seconds") 
Example 44
Project: CTFCrackTools-V2   Author: Acmesec   File: test_socket.py    License: GNU General Public License v3.0 5 votes vote down vote up
def testBindException(self):
        # First bind to the target port
        self.s.bind( (HOST, PORT) )
        self.s.listen(50)
        try:
            # And then try to bind again
            t = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            t.bind( (HOST, PORT) )
            t.listen(50)
        except socket.error, se:
            self.failUnlessEqual(se[0], errno.EADDRINUSE) 
Example 45
Project: CTFCrackTools-V2   Author: Acmesec   File: test_socket.py    License: GNU General Public License v3.0 5 votes vote down vote up
def testBindException(self):
        # First bind to the target port
        self.s.bind( (HOST, PORT) )
        try:
            # And then try to bind again
            t = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            t.bind( (HOST, PORT) )
        except socket.error, se:
            self.failUnlessEqual(se[0], errno.EADDRINUSE) 
Example 46
Project: CTFCrackTools-V2   Author: Acmesec   File: test_socket.py    License: GNU General Public License v3.0 5 votes vote down vote up
def testAddrTupleIDNAHostname(self):
        idna_domain = u"al\u00e1n.com"
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        if socket.supports('idna'):
            try:
                s.bind( (idna_domain, 80) )
            except socket.error:
                # We're not worried about socket errors, i.e. bind problems, etc.
                pass
            except Exception, x:
                self.fail("Unexpected exception raised for socket.bind(%s)" % repr(idna_domain)) 
Example 47
Project: CTFCrackTools-V2   Author: Acmesec   File: test_socket.py    License: GNU General Public License v3.0 5 votes vote down vote up
def testGetsocknameBoundNoImpl(self):
        self.s.bind( ("localhost", 0) )
        try:
            self.s.getsockname()
        except socket.error, se:
            self.fail("getsockname() on bound socket should have not raised socket.error") 
Example 48
Project: CTFCrackTools-V2   Author: Acmesec   File: test_socket.py    License: GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # This server is not needed for all tests, but create it anyway
        # It uses an ephemeral port, so there should be no port clashes or
        # problems with reuse.
        self.server_peer = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server_peer.bind( ("localhost", 0) )
        self.server_peer.listen(5) 
Example 49
Project: CTFCrackTools-V2   Author: Acmesec   File: test_socket.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _create_impl_socket(self):
        self.s.bind(("localhost", 0))
        self.s.listen(5) 
Example 50
Project: CTFCrackTools-V2   Author: Acmesec   File: test_socket.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _create_impl_socket(self):
        # Binding is enough to cause socket impl creation
        self.s.bind(("localhost", 0)) 
Example 51
Project: CTFCrackTools   Author: Acmesec   File: test_socket.py    License: GNU 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.serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.serv.bind((self.HOST, self.PORT))
        self.serv.listen(1) 
Example 52
Project: CTFCrackTools   Author: Acmesec   File: test_socket.py    License: GNU 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.serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.serv.bind((self.HOST, self.PORT)) 
Example 53
Project: CTFCrackTools   Author: Acmesec   File: test_socket.py    License: GNU General Public License v3.0 5 votes vote down vote up
def testSockName(self):
        # Testing getsockname()
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.bind(("0.0.0.0", PORT+1))
        name = sock.getsockname()
        self.assertEqual(name, ("0.0.0.0", PORT+1)) 
Example 54
Project: CTFCrackTools   Author: Acmesec   File: test_socket.py    License: GNU General Public License v3.0 5 votes vote down vote up
def testSockNameEphemeralV4(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.bind(('', 0))
        sock.listen(1)
        name = sock.getsockname()
        self.assertEqual(len(name), 2)
        self.assertNotEqual(name[1], 0) 
Example 55
Project: CTFCrackTools   Author: Acmesec   File: test_socket.py    License: GNU General Public License v3.0 5 votes vote down vote up
def testSockNameEphemeralV6(self):
        sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
        sock.bind(('', 0, 0, 0))
        sock.listen(1)
        name = sock.getsockname()
        self.assertEqual(len(name), 4)
        self.assertNotEqual(name[1], 0) 
Example 56
Project: CTFCrackTools   Author: Acmesec   File: test_socket.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _testTCPClientOption(self, level, option, values):
        sock = None
        try:
            # First listen on a server socket, so that the connection won't be refused.
            server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            server_sock.bind( (HOST, PORT) )
            server_sock.listen(50)
            # Now do the tests
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self._testSetAndGetOption(sock, level, option, values)
            # now connect the socket i.e. cause the implementation socket to be created
            # First bind, so that the SO_REUSEADDR setting propagates
            #sock.bind( (HOST, PORT+1) )
            sock.connect( (HOST, PORT) )
            retrieved_option_value = sock.getsockopt(level, option)
            msg = "TCP client option value '%s'='%s' did not propagate to implementation socket: got %s" % (option, values[-1], retrieved_option_value)
            if option in (socket.SO_RCVBUF, socket.SO_SNDBUF):
                # NOTE: there's no guarantee that bufsize will be the
                # exact setsockopt value, particularly after
                # establishing a connection. seems it will be *at least*
                # the values we test (which are rather small) on
                # BSDs.
                self.assert_(retrieved_option_value >= values[-1], msg)
            else:
                self.failUnlessEqual(retrieved_option_value, values[-1], msg)
            self._testSetAndGetOption(sock, level, option, values)
        finally:
            server_sock.close()
            if sock:
                sock.close()
            pass 
Example 57
Project: CTFCrackTools   Author: Acmesec   File: test_socket.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _testTCPClientInheritedOption(self, level, option, values):
        cli_sock = accepted_sock = None
        try:
            server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self._testSetAndGetOption(server_sock, level, option, values)
            # now bind and listen on the socket i.e. cause the implementation socket to be created
            server_sock.bind( (HOST, PORT) )
            server_sock.listen(50)
            # Now create client socket to connect to server
            cli_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            cli_sock.connect( (HOST, PORT) )
            accepted_sock = server_sock.accept()[0]
            retrieved_option_value = accepted_sock.getsockopt(level, option)
            msg = "TCP client inherited option value '(%s,%s)'='%s' did not propagate to accepted socket: got %s" % (level, option, values[-1], retrieved_option_value)
            if option == socket.SO_RCVBUF:
                # NOTE: see similar bsd/solaris workaround above
                self.assert_(retrieved_option_value >= values[-1], msg)
            else:
                self.failUnlessEqual(retrieved_option_value, values[-1], msg)
            self._testSetAndGetOption(accepted_sock, level, option, values)
        finally:
            server_sock.close()
            time.sleep(1)
            if cli_sock:
                cli_sock.close()
            if accepted_sock:
                accepted_sock.close() 
Example 58
Project: CTFCrackTools   Author: Acmesec   File: test_socket.py    License: GNU General Public License v3.0 5 votes vote down vote up
def testBindSpecific(self):
        self.sock.bind( (self.HOST, self.PORT) ) # Use a specific port
        actual_port = self.sock.getsockname()[1]
        self.failUnless(actual_port == self.PORT,
            "Binding to specific port number should have returned same number: %d != %d" % (actual_port, self.PORT)) 
Example 59
Project: CTFCrackTools   Author: Acmesec   File: test_socket.py    License: GNU General Public License v3.0 5 votes vote down vote up
def testShutdown(self):
        self.sock.bind( (self.HOST, self.PORT) )
        self.sock.shutdown(socket.SHUT_RDWR) 
Example 60
Project: CTFCrackTools   Author: Acmesec   File: test_socket.py    License: GNU General Public License v3.0 5 votes vote down vote up
def testBroadcast(self):
        self.serv.bind( ("", self.PORT) )
        msg = self.serv.recv(len(EIGHT_BIT_MSG))
        self.assertEqual(msg, EIGHT_BIT_MSG)