Python socket.AF_INET() Examples

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

Example 1
Project: electrum-martexcoin-server   Author: martexcoin   File: stratum_http.py    (license) View Source Project 7 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 2
Project: pycos   Author: pgiri   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def _socketpair():
                if hasattr(socket, 'socketpair'):
                    return socket.socketpair()
                srv_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                srv_sock.bind(('127.0.0.1', 0))
                srv_sock.listen(1)
                write_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                try:
                    write_sock.setblocking(False)
                    try:
                        write_sock.connect(srv_sock.getsockname()[:2])
                    except socket.error as e:
                        if e.args[0] in (EINPROGRESS, EWOULDBLOCK):
                            pass
                        else:
                            raise
                    write_sock.setblocking(True)
                    read_sock = srv_sock.accept()[0]
                except:
                    write_sock.close()
                    raise
                finally:
                    srv_sock.close()
                return (read_sock, write_sock) 
Example 3
Project: NS_Proj   Author: drstarry   File: base.py    (MIT License) View Source Project 6 votes vote down vote up
def Start(self, serverAddress, serverPort, bruteforce_file):
        """
        serverHost = string: localhost/ip address/url for server
        serverPort = int: port number to connect for server
        bruteforce_file = string: name of the file that has password guesses
        """
        serverSckt = socket(AF_INET, SOCK_STREAM)
        serverSckt.connect((serverAddress, serverPort))
        print "Client: Connected to Server at %s:%d" \
            % (serverAddress, serverPort)

        success, time_taken, attempts = self.Client(serverSckt, bruteforce_file)
        # used to close socket when client is done
        serverSckt.sendCloseSignal()

        if success:
            print "Success! Cracked the password and got in."
        else:
            print "Failure! Tried to get in but couldn't."

        print "Took %d guesses and %d seconds." \
            % (attempts, time_taken.seconds)

        serverSckt.shutdown(1)  # send close signal to server socket
        serverSckt.close()  # close connection 
Example 4
Project: NS_Proj   Author: drstarry   File: base.py    (MIT License) View Source Project 6 votes vote down vote up
def Start(self, serverAddress, serverPort, password_file):
        """
        serverAddress = string: localhost/ip address/url
        serverPort = int: port number to run server
        password_file = string: file that contains username/password pairs
        """
        serverSckt = socket(AF_INET, SOCK_STREAM)
        serverSckt.bind((serverAddress, serverPort))
        serverSckt.listen(1)  # await requests
        print "Server: Listening at %s:%d" % (serverAddress, serverPort)
        sckt, addr = serverSckt.accept()  # accept a connection (blocking)

        self.Host(sckt, password_file)

        sckt.shutdown(1)  # send close signal
        sckt.close()  # close connection 
Example 5
Project: tornado-ssdb-project   Author: ego008   File: main.py    (MIT License) View Source Project 6 votes vote down vote up
def main():
    application = get_application()
    port = get_port()

    if CONFIG.IPV4_ONLY:
        family = socket.AF_INET
    else:
        family = socket.AF_UNSPEC

    if CONFIG.DEBUG_MODE:
        address = None
    else:
        address = 'localhost'

    sockets = tornado.netutil.bind_sockets(port, address, family=family)
    server = HTTPServer(application, xheaders=CONFIG.XHEADERS)
    server.add_sockets(sockets)
    server.listen_exit_signal(CONFIG.MAX_WAIT_SECONDS_BEFORE_SHUTDOWN)

    tornado.ioloop.IOLoop.instance().start() 
Example 6
Project: spoon   Author: SpamExperts   File: server.py    (GNU General Public License v2.0) View Source Project 6 votes vote down vote up
def __init__(self, address):
        self.log = logging.getLogger(self.server_logger)
        self.socket = None
        if ":" in address[0]:
            self.address_family = socket.AF_INET6
        else:
            self.address_family = socket.AF_INET
        self.log.debug("Listening on %s", address)

        super(_SpoonMixIn, self).__init__(address, self.handler_klass,
                                          bind_and_activate=False)
        self.load_config()
        self._setup_socket()

        # Finally, set signals
        if self.signal_reload is not None:
            signal.signal(self.signal_reload, self.reload_handler)
        if self.signal_shutdown is not None:
            signal.signal(self.signal_shutdown, self.shutdown_handler) 
Example 7
Project: socket-http   Author: thisforeda   File: httpx.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def send(self,send_data):
        if self.__is_addr_reset or \
                         self._is_close_for_invoker or \
                                               self.__is_connection_closed():
            self.__connection = socket(AF_INET,SOCK_STREAM)

            if self.__is_ssl:
                self.__connection = ssl.wrap_socket(self.__connection)
                
            try :
                self.__connection.connect(self.__addr)
                
                self.__connection.settimeout(self.__timeout)
                
                self._is_close_for_invoker = False
                self.__is_addr_reset = False
                
            except Exception as exception:
                self.__recorder.write(
                    'Cannot connect %s' % str(self.__addr),
                    Exception = str(exception))
                return None
            
        self.__connection.send(send_data)
        return self 
Example 8
Project: kinect-2-libras   Author: inessadl   File: smtpd.py    (Apache License 2.0) View Source Project 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 9
Project: LFISuite   Author: D35m0nd142   File: socks.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def __init__(self, family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0, *args, **kwargs):
        if type not in (socket.SOCK_STREAM, socket.SOCK_DGRAM):
            msg = "Socket type must be stream or datagram, not {!r}"
            raise ValueError(msg.format(type))

        super(socksocket, self).__init__(family, type, proto, *args, **kwargs)
        self._proxyconn = None  # TCP connection to keep UDP relay alive

        if self.default_proxy:
            self.proxy = self.default_proxy
        else:
            self.proxy = (None, None, None, None, None, None)
        self.proxy_sockname = None
        self.proxy_peername = None

        self._timeout = None 
Example 10
Project: pscheduler   Author: perfsonar   File: api.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def api_has_bwctl(host, timeout=5, bind=None):
    """
    Determine if a host is running the BWCTL daemon
    """

    # Null implies localhost
    if host is None:
        host = "localhost"

    # HACK: BWTCLBC
    # If the environment says to bind to a certain address, do it.
    if bind is None:
        bind = os.environ.get('PSCHEDULER_LEAD_BIND_HACK', None)

    for family in [socket.AF_INET, socket.AF_INET6]:
        try:
            with closing(socket.socket(family, socket.SOCK_STREAM)) as sock:
                if bind is not None:
                    sock.bind((bind, 0))
                sock.settimeout(timeout)
                return sock.connect_ex((host, 4823)) == 0
        except socket.error:
            pass

    return False 
Example 11
Project: pscheduler   Author: perfsonar   File: interface.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def source_interface(address, port=80, ip_version=None):
    """Figure out what local interface is being used to
    reach an address.

    Returns a tuple of (address, interface_name)
    """

    sock = socket.socket(
        socket.AF_INET6 if ip_version == 6 else socket.AF_INET,
        socket.SOCK_DGRAM)
    try:
        sock.connect((address, port))
    except socket.error:
        return (None, None)

    interface_address = sock.getsockname()[0]

    sock.close()

    interface_name = address_interface(interface_address, ip_version=ip_version)

    if interface_name:
        return (interface_address, interface_name)

    return (None, None) 
Example 12
Project: deb-python-cassandra-driver   Author: openstack   File: util.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def inet_pton(address_family, ip_string):
        if address_family == socket.AF_INET:
            return socket.inet_aton(ip_string)

        addr = sockaddr()
        addr.sa_family = address_family
        addr_size = ctypes.c_int(ctypes.sizeof(addr))

        if WSAStringToAddressA(
                ip_string,
                address_family,
                None,
                ctypes.byref(addr),
                ctypes.byref(addr_size)
        ) != 0:
            raise socket.error(ctypes.FormatError())

        if address_family == socket.AF_INET6:
            return ctypes.string_at(addr.ipv6_addr, 16)

        raise socket.error('unknown address family') 
Example 13
Project: shadowsocksR-b   Author: hao35954514   File: tcprelay.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def _socket_bind_addr(self, sock, af):
        bind_addr = ''
        if self._bind and af == socket.AF_INET:
            bind_addr = self._bind
        elif self._bindv6 and af == socket.AF_INET6:
            bind_addr = self._bindv6
        else:
            bind_addr = self._accept_address[0]

        bind_addr = bind_addr.replace("::ffff:", "")
        if bind_addr in self._ignore_bind_list:
            bind_addr = None
        if bind_addr:
            local_addrs = socket.getaddrinfo(bind_addr, 0, 0, socket.SOCK_STREAM, socket.SOL_TCP)
            if local_addrs[0][0] == af:
                logging.debug("bind %s" % (bind_addr,))
                try:
                    sock.bind((bind_addr, 0))
                except Exception as e:
                    logging.warn("bind %s fail" % (bind_addr,)) 
Example 14
Project: shadowsocksR-b   Author: hao35954514   File: asyncdns.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def handle_event(self, sock, fd, event):
        if sock != self._sock:
            return
        if event & eventloop.POLL_ERR:
            logging.error('dns socket err')
            self._loop.remove(self._sock)
            self._sock.close()
            # TODO when dns server is IPv6
            self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,
                                       socket.SOL_UDP)
            self._sock.setblocking(False)
            self._loop.add(self._sock, eventloop.POLL_IN, self)
        else:
            data, addr = sock.recvfrom(1024)
            if addr not in self._servers:
                logging.warn('received a packet other than our dns')
                return
            self._handle_data(data) 
Example 15
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: httpserver.py    (MIT License) View Source Project 6 votes vote down vote up
def __init__(self, stream, address, protocol):
        self.address = address
        # Save the socket's address family now so we know how to
        # interpret self.address even after the stream is closed
        # and its socket attribute replaced with None.
        if stream.socket is not None:
            self.address_family = stream.socket.family
        else:
            self.address_family = None
        # In HTTPServerRequest we want an IP, not a full socket address.
        if (self.address_family in (socket.AF_INET, socket.AF_INET6) and
                address is not None):
            self.remote_ip = address[0]
        else:
            # Unix (or other) socket; fake the remote address.
            self.remote_ip = '0.0.0.0'
        if protocol:
            self.protocol = protocol
        elif isinstance(stream, iostream.SSLIOStream):
            self.protocol = "https"
        else:
            self.protocol = "http"
        self._orig_remote_ip = self.remote_ip
        self._orig_protocol = self.protocol 
Example 16
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: httpserver.py    (MIT License) View Source Project 6 votes vote down vote up
def __init__(self, stream, address, protocol):
        self.address = address
        # Save the socket's address family now so we know how to
        # interpret self.address even after the stream is closed
        # and its socket attribute replaced with None.
        if stream.socket is not None:
            self.address_family = stream.socket.family
        else:
            self.address_family = None
        # In HTTPServerRequest we want an IP, not a full socket address.
        if (self.address_family in (socket.AF_INET, socket.AF_INET6) and
                address is not None):
            self.remote_ip = address[0]
        else:
            # Unix (or other) socket; fake the remote address.
            self.remote_ip = '0.0.0.0'
        if protocol:
            self.protocol = protocol
        elif isinstance(stream, iostream.SSLIOStream):
            self.protocol = "https"
        else:
            self.protocol = "http"
        self._orig_remote_ip = self.remote_ip
        self._orig_protocol = self.protocol 
Example 17
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: httpserver.py    (MIT License) View Source Project 6 votes vote down vote up
def __init__(self, stream, address, protocol):
        self.address = address
        # Save the socket's address family now so we know how to
        # interpret self.address even after the stream is closed
        # and its socket attribute replaced with None.
        if stream.socket is not None:
            self.address_family = stream.socket.family
        else:
            self.address_family = None
        # In HTTPServerRequest we want an IP, not a full socket address.
        if (self.address_family in (socket.AF_INET, socket.AF_INET6) and
                address is not None):
            self.remote_ip = address[0]
        else:
            # Unix (or other) socket; fake the remote address.
            self.remote_ip = '0.0.0.0'
        if protocol:
            self.protocol = protocol
        elif isinstance(stream, iostream.SSLIOStream):
            self.protocol = "https"
        else:
            self.protocol = "http"
        self._orig_remote_ip = self.remote_ip
        self._orig_protocol = self.protocol 
Example 18
Project: my-weather-indicator   Author: atareao   File: networkmanayer.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def postprocess(self, name, val):
        if name == 'GetSettings':
            if 'ssid' in val.get('802-11-wireless', {}):
                val['802-11-wireless']['ssid'] = fixups.ssid_to_python(val['802-11-wireless']['ssid'])
            for key in val:
                val_ = val[key]
                if 'mac-address' in val_:
                    val_['mac-address'] = fixups.mac_to_python(val_['mac-address'])
                if 'cloned-mac-address' in val_:
                    val_['cloned-mac-address'] = fixups.mac_to_python(val_['cloned-mac-address'])
                if 'bssid' in val_:
                    val_['bssid'] = fixups.mac_to_python(val_['bssid'])
            if 'ipv4' in val:
                val['ipv4']['addresses'] = [fixups.addrconf_to_python(addr, socket.AF_INET) for addr in val['ipv4']['addresses']]
                val['ipv4']['routes'] = [fixups.route_to_python(route, socket.AF_INET) for route in val['ipv4']['routes']]
                val['ipv4']['dns'] = [fixups.addr_to_python(addr, socket.AF_INET) for addr in val['ipv4']['dns']]
            if 'ipv6' in val:
                val['ipv6']['addresses'] = [fixups.addrconf_to_python(addr, socket.AF_INET6) for addr in val['ipv6']['addresses']]
                val['ipv6']['routes'] = [fixups.route_to_python(route, socket.AF_INET6) for route in val['ipv6']['routes']]
                val['ipv6']['dns'] = [fixups.addr_to_python(addr, socket.AF_INET6) for addr in val['ipv6']['dns']]
        return val 
Example 19
Project: sauna   Author: NicolasLM   File: simple_domain.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def request(self, check_config):
        domain = check_config.get('domain')
        if check_config.get('ip_version') == 6:
            af = socket.AF_INET6
        elif check_config.get('ip_version') == 4:
            af = socket.AF_INET
        else:
            af = 0

        try:
            result = socket.getaddrinfo(domain, 0, af)
        except Exception as e:
            return Plugin.STATUS_CRIT, '{}'.format(e)

        ips = [ip[4][0] for ip in result]
        return (
            Plugin.STATUS_OK,
            'Domain was resolved with {}'.format(', '.join(ips))
        ) 
Example 20
Project: twampy   Author: nokia   File: twampy.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 6 votes vote down vote up
def bind(self, addr, port, tos, ttl, df):
        log.debug(
            "bind(addr=%s, port=%d, tos=%d, ttl=%d)", addr, port, tos, ttl)
        self.socket = socket.socket(
            socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_TOS, tos)
        self.socket.setsockopt(socket.SOL_IP,     socket.IP_TTL, ttl)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.bind((addr, port))
        if df:
            if (sys.platform == "linux2"):
                self.socket.setsockopt(socket.SOL_IP, 10, 2)
            elif (sys.platform == "win32"):
                self.socket.setsockopt(socket.SOL_IP, 14, 1)
            elif (sys.platform == "darwin"):
                log.error("do-not-fragment can not be set on darwin")
            else:
                log.error("unsupported OS, ignore do-not-fragment option")
        else:
            if (sys.platform == "linux2"):
                self.socket.setsockopt(socket.SOL_IP, 10, 0) 
Example 21
Project: CyberScan   Author: medbenali   File: inet6.py    (license) View Source Project 6 votes vote down vote up
def _resolve_one(self, ip):
        """
        overloaded version to provide a Whois resolution on the
        embedded IPv4 address if the address is 6to4 or Teredo. 
        Otherwise, the native IPv6 address is passed.
        """

        if in6_isaddr6to4(ip): # for 6to4, use embedded @
            tmp = inet_pton(socket.AF_INET6, ip)
            addr = inet_ntop(socket.AF_INET, tmp[2:6])
        elif in6_isaddrTeredo(ip): # for Teredo, use mapped address
            addr = teredoAddrExtractInfo(ip)[2]
        else:
            addr = ip
        
        _, asn, desc = AS_resolver_riswhois._resolve_one(self, addr)

        return ip,asn,desc 
Example 22
Project: hostapd-mana   Author: adde88   File: smtpd.py    (license) View Source Project 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 23
Project: hostapd-mana   Author: adde88   File: inet.py    (license) View Source Project 6 votes vote down vote up
def inet_pton(family, text):
    """Convert the textual form of a network address into its binary form.

    @param family: the address family
    @type family: int
    @param text: the textual address
    @type text: string
    @raises NotImplementedError: the address family specified is not
    implemented.
    @rtype: string
    """

    if family == AF_INET:
        return dns.ipv4.inet_aton(text)
    elif family == AF_INET6:
        return dns.ipv6.inet_aton(text)
    else:
        raise NotImplementedError 
Example 24
Project: hostapd-mana   Author: adde88   File: inet.py    (license) View Source Project 6 votes vote down vote up
def inet_ntop(family, address):
    """Convert the binary form of a network address into its textual form.

    @param family: the address family
    @type family: int
    @param address: the binary address
    @type address: string
    @raises NotImplementedError: the address family specified is not
    implemented.
    @rtype: string
    """
    if family == AF_INET:
        return dns.ipv4.inet_ntoa(address)
    elif family == AF_INET6:
        return dns.ipv6.inet_ntoa(address)
    else:
        raise NotImplementedError 
Example 25
Project: hostapd-mana   Author: adde88   File: inet.py    (license) View Source Project 6 votes vote down vote up
def af_for_address(text):
    """Determine the address family of a textual-form network address.

    @param text: the textual address
    @type text: string
    @raises ValueError: the address family cannot be determined from the input.
    @rtype: int
    """
    try:
        dns.ipv4.inet_aton(text)
        return AF_INET
    except:
        try:
            dns.ipv6.inet_aton(text)
            return AF_INET6
        except:
            raise ValueError 
Example 26
Project: hostapd-mana   Author: adde88   File: resolver.py    (license) View Source Project 6 votes vote down vote up
def _gethostbyaddr(ip):
    try:
        dns.ipv6.inet_aton(ip)
        sockaddr = (ip, 80, 0, 0)
        family = socket.AF_INET6
    except:
        sockaddr = (ip, 80)
        family = socket.AF_INET
    (name, port) = _getnameinfo(sockaddr, socket.NI_NAMEREQD)
    aliases = []
    addresses = []
    tuples = _getaddrinfo(name, 0, family, socket.SOCK_STREAM, socket.SOL_TCP,
                          socket.AI_CANONNAME)
    canonical = tuples[0][3]
    for item in tuples:
        addresses.append(item[4][0])
    # XXX we just ignore aliases
    return (canonical, aliases, addresses) 
Example 27
Project: hostapd-mana   Author: adde88   File: test_compat.py    (license) View Source Project 6 votes vote down vote up
def testNToP(self):
        from twisted.python.compat import inet_ntop

        f = lambda a: inet_ntop(socket.AF_INET6, a)
        g = lambda a: inet_ntop(socket.AF_INET, a)

        self.assertEquals('::', f('\x00' * 16))
        self.assertEquals('::1', f('\x00' * 15 + '\x01'))
        self.assertEquals(
            'aef:b01:506:1001:ffff:9997:55:170',
            f('\x0a\xef\x0b\x01\x05\x06\x10\x01\xff\xff\x99\x97\x00\x55\x01\x70'))

        self.assertEquals('1.0.1.0', g('\x01\x00\x01\x00'))
        self.assertEquals('170.85.170.85', g('\xaa\x55\xaa\x55'))
        self.assertEquals('255.255.255.255', g('\xff\xff\xff\xff'))

        self.assertEquals('100::', f('\x01' + '\x00' * 15))
        self.assertEquals('100::1', f('\x01' + '\x00' * 14 + '\x01')) 
Example 28
Project: hostapd-mana   Author: adde88   File: dns.py    (license) View Source Project 6 votes vote down vote up
def m2i(self, pkt, s):
        family = None
        if pkt.type == 1: # A
            family = socket.AF_INET
        elif pkt.type == 12: # PTR
            s = DNSgetstr(s, 0)[0]
        elif pkt.type == 16: # TXT
            ret_s = ""
            tmp_s = s
            # RDATA contains a list of strings, each are prepended with
            # a byte containing the size of the following string.
            while tmp_s:
                tmp_len = struct.unpack("!B", tmp_s[0])[0] + 1
                if tmp_len > len(tmp_s):
                  warning("DNS RR TXT prematured end of character-string (size=%i, remaining bytes=%i)" % (tmp_len, len(tmp_s)))
                ret_s += tmp_s[1:tmp_len]
                tmp_s = tmp_s[tmp_len:]
            s = ret_s
        elif pkt.type == 28: # AAAA
            family = socket.AF_INET6
        if family is not None:    
            s = inet_ntop(family, s)
        return s 
Example 29
Project: hostapd-mana   Author: adde88   File: inet6.py    (license) View Source Project 6 votes vote down vote up
def h2i(self, pkt, x):
        if x is tuple and type(x[0]) is int:
            return x

        val = None
        try: # Try IPv6
            inet_pton(socket.AF_INET6, x)
            val = (0, x)
        except:
            try: # Try IPv4
                inet_pton(socket.AF_INET, x)
                val = (2, x)
            except: # Try DNS
                if x is None:
                    x = ""
                x = names2dnsrepr(x)
                val = (1, x)
        return val 
Example 30
Project: hostapd-mana   Author: adde88   File: inet6.py    (license) View Source Project 6 votes vote down vote up
def _resolve_one(self, ip):
        """
        overloaded version to provide a Whois resolution on the
        embedded IPv4 address if the address is 6to4 or Teredo. 
        Otherwise, the native IPv6 address is passed.
        """

        if in6_isaddr6to4(ip): # for 6to4, use embedded @
            tmp = inet_pton(socket.AF_INET6, ip)
            addr = inet_ntop(socket.AF_INET, tmp[2:6])
        elif in6_isaddrTeredo(ip): # for Teredo, use mapped address
            addr = teredoAddrExtractInfo(ip)[2]
        else:
            addr = ip
        
        _, asn, desc = AS_resolver_riswhois._resolve_one(self, addr)

        return ip,asn,desc 
Example 31
Project: llk   Author: Tycx2ry   File: inet.py    (license) View Source Project 6 votes vote down vote up
def inet_pton(family, text):
    """Convert the textual form of a network address into its binary form.

    @param family: the address family
    @type family: int
    @param text: the textual address
    @type text: string
    @raises NotImplementedError: the address family specified is not
    implemented.
    @rtype: string
    """
    
    if family == AF_INET:
        return dns.ipv4.inet_aton(text)
    elif family == AF_INET6:
        return dns.ipv6.inet_aton(text)
    else:
        raise NotImplementedError 
Example 32
Project: llk   Author: Tycx2ry   File: inet.py    (license) View Source Project 6 votes vote down vote up
def inet_ntop(family, address):
    """Convert the binary form of a network address into its textual form.

    @param family: the address family
    @type family: int
    @param address: the binary address
    @type address: string
    @raises NotImplementedError: the address family specified is not
    implemented.
    @rtype: string
    """
    if family == AF_INET:
        return dns.ipv4.inet_ntoa(address)
    elif family == AF_INET6:
        return dns.ipv6.inet_ntoa(address)
    else:
        raise NotImplementedError 
Example 33
Project: llk   Author: Tycx2ry   File: inet.py    (license) View Source Project 6 votes vote down vote up
def af_for_address(text):
    """Determine the address family of a textual-form network address.

    @param text: the textual address
    @type text: string
    @raises ValueError: the address family cannot be determined from the input.
    @rtype: int
    """
    try:
        junk = dns.ipv4.inet_aton(text)
        return AF_INET
    except:
        try:
            junk = dns.ipv6.inet_aton(text)
            return AF_INET6
        except:
            raise ValueError 
Example 34
Project: pycos   Author: pgiri   File: netpycos.py    (license) View Source Project 5 votes vote down vote up
def discover_peers(self, port=None):
        """This method can be invoked (periodically?) to broadcast message to
        discover peers, if there is a chance initial broadcast message may be
        lost (as these messages are sent over UDP).
        """
        ping_msg = {'signature': self._signature, 'name': self._name, 'version': __version__}

        def _discover(addrinfo, port, task=None):
            ping_sock = AsyncSocket(socket.socket(addrinfo.family, socket.SOCK_DGRAM))
            ping_sock.settimeout(2)
            if addrinfo.family == socket.AF_INET:
                ping_sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
            else:  # addrinfo.family == socket.AF_INET6
                ping_sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_HOPS,
                                     struct.pack('@i', 1))
                ping_sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_IF, addrinfo.ifn)
            ping_sock.bind((addrinfo.ip, 0))
            if not port:
                port = addrinfo.udp_sock.getsockname()[1]
            ping_msg['location'] = addrinfo.location
            try:
                yield ping_sock.sendto('ping:'.encode() + serialize(ping_msg),
                                       (addrinfo.broadcast, port))
            except:
                pass
            ping_sock.close()

        for addrinfo in self._addrinfos:
            SysTask(_discover, addrinfo, port) 
Example 35
Project: pyOSC3   Author: Qirky   File: OSC3.py    (license) View Source Project 5 votes vote down vote up
def _ensureConnected(self, address):
		"""Make sure client has a socket connected to address"""
		if not self.socket:
			if len(address) == 4:
				address_family = socket.AF_INET6
			else:
				address_family = socket.AF_INET
			self._setSocket(socket.socket(address_family, socket.SOCK_DGRAM))
		self.socket.connect(address) 
Example 36
Project: pyOSC3   Author: Qirky   File: OSC3.py    (license) View Source Project 5 votes vote down vote up
def __init__(self):
		self._txMutex = threading.Lock()
		OSCAddressSpace.__init__(self)
		self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, self.sndbuf_size)
		self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, self.rcvbuf_size)
		self.socket.settimeout(1.0)
		self._running = False 
Example 37
Project: pyOSC3   Author: Qirky   File: OSC2.py    (license) View Source Project 5 votes vote down vote up
def _ensureConnected(self, address):
		"""Make sure client has a socket connected to address"""
		if not self.socket:
			if len(address) == 4:
				address_family = socket.AF_INET6
			else:
				address_family = socket.AF_INET
			self._setSocket(socket.socket(address_family, socket.SOCK_DGRAM))
		self.socket.connect(address) 
Example 38
Project: pyOSC3   Author: Qirky   File: OSC2.py    (license) View Source Project 5 votes vote down vote up
def __init__(self):
		self._txMutex = threading.Lock()
		OSCAddressSpace.__init__(self)
		self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, self.sndbuf_size)
		self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, self.rcvbuf_size)
		self.socket.settimeout(1.0)
		self._running = False 
Example 39
Project: python-   Author: secondtonone1   File: connection.py    (license) View Source Project 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 40
Project: my-first-blog   Author: AnkurBegining   File: connection.py    (license) View Source Project 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 41
Project: my-first-blog   Author: AnkurBegining   File: connection.py    (license) View Source Project 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 42
Project: dabdabrevolution   Author: harryparkdotio   File: bottle.py    (MIT License) View Source Project 5 votes vote down vote up
def run(self, app):  # pragma: no cover
        from wsgiref.simple_server import make_server
        from wsgiref.simple_server import WSGIRequestHandler, WSGIServer
        import socket

        class FixedHandler(WSGIRequestHandler):
            def address_string(self):  # Prevent reverse DNS lookups please.
                return self.client_address[0]

            def log_request(*args, **kw):
                if not self.quiet:
                    return WSGIRequestHandler.log_request(*args, **kw)

        handler_cls = self.options.get('handler_class', FixedHandler)
        server_cls = self.options.get('server_class', WSGIServer)

        if ':' in self.host:  # Fix wsgiref for IPv6 addresses.
            if getattr(server_cls, 'address_family') == socket.AF_INET:

                class server_cls(server_cls):
                    address_family = socket.AF_INET6

        self.srv = make_server(self.host, self.port, app, server_cls,
                               handler_cls)
        self.port = self.srv.server_port  # update port actual port (0 means random)
        try:
            self.srv.serve_forever()
        except KeyboardInterrupt:
            self.srv.server_close()  # Prevent ResourceWarning: unclosed socket
            raise 
Example 43
Project: BitBot   Author: crack00r   File: tcp_client.py    (license) View Source Project 5 votes vote down vote up
def _recreate_socket(self):
        if self._proxy is None:
            self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        else:
            import socks
            self._socket = socks.socksocket(socket.AF_INET, socket.SOCK_STREAM)
            if type(self._proxy) is dict:
                self._socket.set_proxy(**self._proxy)
            else:  # tuple, list, etc.
                self._socket.set_proxy(*self._proxy) 
Example 44
Project: BitBot   Author: crack00r   File: threaded_tcp_client.py    (license) View Source Project 5 votes vote down vote up
def _recreate_socket(self):
        if self._proxy is None:
            self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        else:
            import socks
            self._socket = socks.socksocket(socket.AF_INET, socket.SOCK_STREAM)
            if type(self._proxy) is dict:
                self._socket.set_proxy(**self._proxy)
            else:  # tuple, list, etc.
                self._socket.set_proxy(*self._proxy) 
Example 45
Project: kinect-2-libras   Author: inessadl   File: ftplib.py    (Apache License 2.0) View Source Project 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 46
Project: kinect-2-libras   Author: inessadl   File: ftplib.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def makeport(self):
        '''Create a new socket and send a PORT command for it.'''
        msg = "getaddrinfo returns an empty list"
        sock = None
        for res in socket.getaddrinfo(None, 0, self.af, socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
            af, socktype, proto, canonname, sa = res
            try:
                sock = socket.socket(af, socktype, proto)
                sock.bind(sa)
            except socket.error, msg:
                if sock:
                    sock.close()
                sock = None
                continue
            break
        if not sock:
            raise socket.error, msg
        sock.listen(1)
        port = sock.getsockname()[1] # Get proper port
        host = self.sock.getsockname()[0] # Get proper host
        if self.af == socket.AF_INET:
            resp = self.sendport(host, port)
        else:
            resp = self.sendeprt(host, port)
        if self.timeout is not _GLOBAL_DEFAULT_TIMEOUT:
            sock.settimeout(self.timeout)
        return sock 
Example 47
Project: kinect-2-libras   Author: inessadl   File: ftplib.py    (Apache License 2.0) View Source Project 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 48
Project: LFISuite   Author: D35m0nd142   File: socks.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def _write_SOCKS5_address(self, addr, file):
        """
        Return the host and port packed for the SOCKS5 protocol,
        and the resolved address as a tuple object.
        """
        host, port = addr
        proxy_type, _, _, rdns, username, password = self.proxy
        family_to_byte = {socket.AF_INET: b"\x01", socket.AF_INET6: b"\x04"}

        # If the given destination address is an IP address, we'll
        # use the IP address request even if remote resolving was specified.
        # Detect whether the address is IPv4/6 directly.
        for family in (socket.AF_INET, socket.AF_INET6):
            try:
                addr_bytes = socket.inet_pton(family, host)
                file.write(family_to_byte[family] + addr_bytes)
                host = socket.inet_ntop(family, addr_bytes)
                file.write(struct.pack(">H", port))
                return host, port
            except socket.error:
                continue

        # Well it's not an IP number, so it's probably a DNS name.
        if rdns:
            # Resolve remotely
            host_bytes = host.encode("idna")
            file.write(b"\x03" + chr(len(host_bytes)).encode() + host_bytes)
        else:
            # Resolve locally
            addresses = socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.IPPROTO_TCP, socket.AI_ADDRCONFIG)
            # We can't really work out what IP is reachable, so just pick the
            # first.
            target_addr = addresses[0]
            family = target_addr[0]
            host = target_addr[4][0]

            addr_bytes = socket.inet_pton(family, host)
            file.write(family_to_byte[family] + addr_bytes)
            host = socket.inet_ntop(family, addr_bytes)
        file.write(struct.pack(">H", port))
        return host, port 
Example 49
Project: Bahubali---DDOS-Toolkit   Author: navanchauhan   File: socks.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def __init__(self, family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0, _sock=None):
		_orgsocket.__init__(self,family,type,proto,_sock)
		if _defaultproxy != None:
			self.__proxy = _defaultproxy
		else:
			self.__proxy = (None, None, None, None, None, None)
		self.__proxysockname = None
		self.__proxypeername = None 
Example 50
Project: network-testing   Author: crossdistro   File: test_suite.py    (BSD 2-Clause "Simplified" License) View Source Project 5 votes vote down vote up
def postprocess(self):
        self.testcase.add_property(
            IP4Listener(bool([listener for listener in self.listeners if listener.domain.value == socket.AF_INET])))
        self.testcase.add_property(
            IP6Listener(bool([listener for listener in self.listeners if listener.domain.value == socket.AF_INET6])))
        self.testcase.add_property(ParallelConnect(len(self.connections) > 1))