Python socket.SOCK_DGRAM Examples

The following are 30 code examples of socket.SOCK_DGRAM(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module socket , or try the search function .
Example #1
Source File: tracker.py    From sagemaker-xgboost-container with Apache License 2.0 9 votes vote down vote up
def get_host_ip(hostIP=None):
    if hostIP is None or hostIP == 'auto':
        hostIP = 'ip'

    if hostIP == 'dns':
        hostIP = socket.getfqdn()
    elif hostIP == 'ip':
        from socket import gaierror
        try:
            hostIP = socket.gethostbyname(socket.getfqdn())
        except gaierror:
            logger.warn('gethostbyname(socket.getfqdn()) failed... trying on hostname()')
            hostIP = socket.gethostbyname(socket.gethostname())
        if hostIP.startswith("127."):
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            # doesn't have to be reachable
            s.connect(('10.255.255.255', 1))
            hostIP = s.getsockname()[0]
    return hostIP 
Example #2
Source File: ip.py    From pynmap with GNU General Public License v3.0 8 votes vote down vote up
def getLocalip(interface: str = "wlan0") -> str:
    """This function will return the Local IP Address of the interface"""
    if "nux" in sys.platform:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        try:
            return socket.inet_ntoa(
                fcntl.ioctl(
                    s.fileno(), 0x8915, struct.pack('256s',interface[:15])
                )[20:24]
            )
        except IOError:
            print("{}[!] Error, unable to detect local ip address.".format(Colors.FAIL))
            print("[!] Check your connection to network {}".format(Colors.ENDC))
            exit()
    elif "darwin" in sys.platform:
        return [ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][0] 
Example #3
Source File: multicast_checks.py    From rift-python with Apache License 2.0 7 votes vote down vote up
def _create_ipv4_sockets(loopback_enabled):
    # Open a multicast send socket, with IP_MULTICAST_LOOP enabled or disabled as requested.
    mcast_address = "224.0.1.195"
    port = 49501
    group = (mcast_address, port)
    txsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    txsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    if loopback_enabled:
        txsock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 1)
    else:
        txsock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 0)
    txsock.connect(group)
    # Open a multicast receive socket and join the group
    rxsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    req = struct.pack("=4sl", socket.inet_aton(mcast_address), socket.INADDR_ANY)
    rxsock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, req)
    rxsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    rxsock.bind(group)
    return (txsock, rxsock) 
Example #4
Source File: client.py    From nukemyluks with Apache License 2.0 7 votes vote down vote up
def send_packet(secret):
    try:
        broadcast_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        broadcast_socket.bind(('', 0))
        broadcast_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    except Exception as err:
        print "[!] Error creating broadcast socket: %s" % err
        sys.exit(ERROR)
    
    data = "nukemyluks_" + secret
    try:
        broadcast_socket.sendto(data, ('<broadcast>', DEFAULT_PORT))
        
    except Exception as err:
        print "[!] Error sending packet: %s" % err
        sys.exit(ERROR) 
Example #5
Source File: network.py    From python-lifx-sdk with MIT License 7 votes vote down vote up
def __init__(self, address='0.0.0.0', broadcast='255.255.255.255'):
        # Prepare a socket
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        sock.bind((address, 0))

        self._socket = sock

        self._listener = ListenerThread(sock, self._handle_packet)
        self._listener.start()

        self._packet_handlers = {}

        self._current_handler_id = 0

        self._broadcast = broadcast 
Example #6
Source File: udp_rx_handler.py    From rift-python with Apache License 2.0 6 votes vote down vote up
def create_socket_ipv4_rx_ucast(self):
        if self._local_ipv4_address is None:
            self.warning("Could not create IPv4 UDP socket: don't have a local address")
            return None
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        except (IOError, OSError) as err:
            self.warning("Could not create IPv4 UDP socket: %s", err)
            return None
        self.enable_addr_and_port_reuse(sock)
        try:
            sock.bind((self._local_ipv4_address, self._local_port))
        except (IOError, OSError) as err:
            self.warning("Could not bind IPv4 UDP socket to address %s port %d: %s",
                         self._local_ipv4_address, self._local_port, err)
            return None
        try:
            sock.setblocking(0)
        except (IOError, OSError) as err:
            self.warning("Could set unicast receive IPv4 UDP to non-blocking mode: %s", err)
            return None
        return sock 
Example #7
Source File: server.py    From tandem with Apache License 2.0 6 votes vote down vote up
def main():
    args = get_args()
    self_address = (socket.gethostbyname(socket.gethostname()), args.self_port)
    connected_clients = []

    print("Listening on {}".format(self_address))
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.bind(self_address)

    while(True):
        new_data, new_address = recv_data(sock)

        # Send new client information about the connected_clients
        for connected_data, connected_address in connected_clients:
            send_data(sock, (connected_data, connected_address), new_address)
            time.sleep(3)

        time.sleep(3)

        # Send connected_clients information about the new client
        for connected_data, connected_address in connected_clients:
            send_data(sock, (new_data, new_address), connected_address)

        connected_clients.append((new_data, new_address)) 
Example #8
Source File: UDP_generic.py    From XFLTReaT with MIT License 6 votes vote down vote up
def serve(self):
		server_socket = None
		try:
			common.internal_print("Starting module: {0} on {1}:{2}".format(self.get_module_name(), self.config.get("Global", "serverbind"), int(self.config.get(self.get_module_configname(), "serverport"))))
		
			server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
			server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
			whereto = (self.config.get("Global", "serverbind"), int(self.config.get(self.get_module_configname(), "serverport")))
			server_socket.bind(whereto)
			self.comms_socket = server_socket
			self.serverorclient = 1
			self.authenticated = False

			self.communication_initialization()
			self.communication(False) 
			
		except KeyboardInterrupt:

			self.cleanup()
			return

		self.cleanup()

		return 
Example #9
Source File: client.py    From tandem with Apache License 2.0 6 votes vote down vote up
def main():
    args = get_args()
    self_address = (socket.gethostbyname(socket.gethostname()), args.self_port)
    server_address = (args.target_host, args.target_port)

    print("Listening on {}".format(self_address))
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.bind(self_address)

    print("Connecting to rendezvous server")
    send_data(sock, self_address, server_address)

    while(True):
        data, address = recv_data(sock)

        if (type(data) is list and type(data[0]) is list):
            connect_to(sock, data)
        else:
            if data['type'] == 'ping':
                time.sleep(1)
                send_data(sock, create_pingback(data), address) 
Example #10
Source File: UDP_generic.py    From XFLTReaT with MIT License 6 votes vote down vote up
def connect(self):
		try:
			common.internal_print("Starting client: {0}".format(self.get_module_name()))
			server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
			self.server_tuple = (self.config.get("Global", "remoteserverip"), int(self.config.get(self.get_module_configname(), "serverport")))
			self.comms_socket = server_socket
			self.serverorclient = 0
			self.authenticated = False

			self.do_hello()
			self.communication(False)

		except KeyboardInterrupt:
			self.do_logoff()
			self.cleanup()
			raise
		except socket.error:
			self.cleanup()
			raise

		self.cleanup()

		return 
Example #11
Source File: TempServer.py    From PiClock with MIT License 6 votes vote down vote up
def t_udp():
    global temps, lock
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    server_address = ('', 53535)
    sock.bind(server_address)
    while True:
        data, address = sock.recvfrom(4096)
        (addr, temp) = data.split(':')
        saddr = [addr[i:i + 2] for i in range(0, len(addr), 2)]
        saddr.reverse()
        saddr = saddr[1:7]
        addr = ''.join(saddr)
        tempf = float(temp) * 9.0 / 5.0 + 32.0
        lock.acquire()
        temps[addr] = tempf
        temptimes[addr] = time.time()
        lock.release()
        print 'udp>' + addr + ':' + str(tempf) 
Example #12
Source File: network_feeder.py    From rex with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def worker(self, thread_id):
        print("About to fire the test case...")
        if self._delay:
            time.sleep(self._delay)

        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM if self._proto == "tcp" else socket.SOCK_DGRAM)
            sock.settimeout(self._timeout)
            sock.connect((self._host, self._port))

            sock.send(self._data)
            sock.recv(1024)

            sock.close()
        except Exception:
            _l.error("Failed to feed network data to target %s:%d.", self._host, self._port, exc_info=True)
        finally:
            # Pop the thread object
            self._threads.pop(thread_id, None) 
Example #13
Source File: socks.py    From plugin.video.kmediatorrent with GNU General Public License v3.0 6 votes vote down vote up
def sendto(self, bytes, *args):
        if self.type != socket.SOCK_DGRAM:
            return _BaseSocket.sendto(self, bytes, *args)
        if not self._proxyconn:
            self.bind(("", 0))
        
        address = args[-1]
        flags = args[:-1]
        
        header = BytesIO()
        RSV = b"\x00\x00"
        header.write(RSV)
        STANDALONE = b"\x00"
        header.write(STANDALONE)
        self._write_SOCKS5_address(address, header)
        
        sent = _BaseSocket.send(self, header.getvalue() + bytes, *flags)
        return sent - header.tell() 
Example #14
Source File: udp.py    From wio-cli with MIT License 6 votes vote down vote up
def send(cmd):
    s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    s.settimeout(1)
    flag = False
    for i in range(3):
        try:
            s.sendto(cmd, addr)
            while 1:
                data, a = s.recvfrom(1024)
                if 'ok' in data:
                    flag = True
                    break
        except socket.timeout:
            continue
        except:
            break

        if flag:
            break
    s.close()

    return flag 
Example #15
Source File: multicast_checks.py    From rift-python with Apache License 2.0 6 votes vote down vote up
def _create_ipv6_sockets(loopback_enabled):
    # Open a multicast send socket, with IP_MULTICAST_LOOP enabled or disabled as requested.
    intf_name = find_ethernet_interface()
    intf_index = socket.if_nametoindex(intf_name)
    mcast_address = "ff02::abcd:99"
    port = 30000
    group = (mcast_address, port)
    txsock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    txsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    txsock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_IF, intf_index)
    if loopback_enabled:
        txsock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_LOOP, 1)
    else:
        txsock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_LOOP, 0)
    txsock.connect(group)
    # Open a multicast receive socket and join the group
    rxsock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    req = struct.pack("=16si", socket.inet_pton(socket.AF_INET6, mcast_address), intf_index)
    if platform.system() == "Darwin":
        rxsock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, req)
    else:
        rxsock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_ADD_MEMBERSHIP, req)
    rxsock.bind(("::", port))
    return (txsock, rxsock) 
Example #16
Source File: mavlink.py    From dronekit-python with Apache License 2.0 6 votes vote down vote up
def __init__(self, device, baud=None, input=True, broadcast=False, source_system=255, source_component=0, use_native=mavutil.default_native):
        self._logger = logging.getLogger(__name__)
        a = device.split(':')
        if len(a) != 2:
            self._logger.critical("UDP ports must be specified as host:port")
            sys.exit(1)
        self.port = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.udp_server = input
        self.broadcast = False
        self.addresses = set()
        if input:
            self.port.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.port.bind((a[0], int(a[1])))
        else:
            self.destination_addr = (a[0], int(a[1]))
            if broadcast:
                self.port.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
                self.broadcast = True
        mavutil.set_close_on_exec(self.port.fileno())
        self.port.setblocking(False)
        mavutil.mavfile.__init__(self, self.port.fileno(), device, source_system=source_system, source_component=source_component, input=input, use_native=use_native) 
Example #17
Source File: Sniffer.py    From SimpleSniffer with GNU General Public License v3.0 6 votes vote down vote up
def get_ip_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15]))[20:24])

#嗅探 
Example #18
Source File: multicast-relay.py    From multicast-relay with GNU General Public License v3.0 6 votes vote down vote up
def interfaces(self):
        if self.homebrewNetifaces:
            import array
            import fcntl

            maxInterfaces = 128
            bufsiz = maxInterfaces * 40
            nullByte = b'\0'

            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            ifNames = array.array('B', nullByte * bufsiz)
            ifNameLen = struct.unpack('iL', fcntl.ioctl(
                s.fileno(),
                0x8912, # SIOCGIFCONF
                struct.pack('iL', bufsiz, ifNames.buffer_info()[0])
            ))[0]

            if ifNameLen % self.ifNameStructLen != 0:
                print('Do you need to set --ifNameStructLen? %s/%s ought to have a remainder of zero.' % (ifNameLen, self.ifNameStructLen))
                sys.exit(1)

            ifNames = ifNames.tostring()
            for i in range(0, ifNameLen, self.ifNameStructLen):
                name      = ifNames[i:i+16].split(nullByte, 1)[0].decode()
                if not name:
                    print('Cannot determine interface name: do you need to set --ifNameStructLen? %s/%s ought to have a remainder of zero.' % (ifNameLen, self.ifNameStructLen))
                    sys.exit(1)
                ip        = socket.inet_ntoa(fcntl.ioctl(socket.socket(socket.AF_INET, socket.SOCK_DGRAM), 0x8915, struct.pack('256s', str(name)))[20:24]) # SIOCGIFADDR
                netmask   = socket.inet_ntoa(fcntl.ioctl(socket.socket(socket.AF_INET, socket.SOCK_DGRAM), 0x891b, struct.pack('256s', str(name)))[20:24]) # SIOCGIFNETMASK
                broadcast = socket.inet_ntoa(fcntl.ioctl(socket.socket(socket.AF_INET, socket.SOCK_DGRAM), 0x8919, struct.pack('256s', str(name)))[20:24]) # SIOCGIFBRDADDR
                hwaddr    = ':'.join(['%02x' % ord(char) for char in fcntl.ioctl(socket.socket(socket.AF_INET, socket.SOCK_DGRAM), 0x8927, struct.pack('256s', str(name)))[18:24]]) # SIOCGIFHWADDR
                self.interfaceAttrs[name] = {Netifaces.AF_LINK: [{'addr': hwaddr}], Netifaces.AF_INET: [{'addr': ip, 'netmask': netmask, 'broadcast': broadcast}]}
            return self.interfaceAttrs.keys()
        else:
            import netifaces
            return netifaces.interfaces() 
Example #19
Source File: interface.py    From rift-python with Apache License 2.0 6 votes vote down vote up
def create_socket_ipv6_tx_ucast(self, remote_address, port):
        try:
            sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        except IOError as err:
            self.warning("Could not create IPv6 UDP socket: %s", err)
            return None
        self.enable_addr_and_port_reuse(sock)
        try:
            sock_addr = socket.getaddrinfo(remote_address, port, socket.AF_INET6,
                                           socket.SOCK_DGRAM)[0][4]
            sock.connect(sock_addr)
        except IOError as err:
            self.warning("Could not connect UDP socket to address %s port %d: %s",
                         remote_address, port, err)
            return None
        return sock 
Example #20
Source File: handlers.py    From jawfish with MIT License 6 votes vote down vote up
def _connect_unixsocket(self, address):
        use_socktype = self.socktype
        if use_socktype is None:
            use_socktype = socket.SOCK_DGRAM
        self.socket = socket.socket(socket.AF_UNIX, use_socktype)
        try:
            self.socket.connect(address)
            # it worked, so set self.socktype to the used type
            self.socktype = use_socktype
        except socket.error:
            self.socket.close()
            if self.socktype is not None:
                # user didn't specify falling back, so fail
                raise
            use_socktype = socket.SOCK_STREAM
            self.socket = socket.socket(socket.AF_UNIX, use_socktype)
            try:
                self.socket.connect(address)
                # it worked, so set self.socktype to the used type
                self.socktype = use_socktype
            except socket.error:
                self.socket.close()
                raise 
Example #21
Source File: gateway.py    From Jtyoui with MIT License 6 votes vote down vote up
def get_linux_ip(eth):
    """在Linux下获取IP"""
    assert os.name == 'posix', NotLinuxSystemError('不是Linux系统')
    import fcntl
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    ip = socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', eth[:15])))
    return ip[20:24] 
Example #22
Source File: socks.py    From plugin.video.kmediatorrent with GNU General Public License v3.0 6 votes vote down vote up
def recvfrom(self, bufsize, flags=0):
        if self.type != socket.SOCK_DGRAM:
            return _BaseSocket.recvfrom(self, bufsize, flags)
        if not self._proxyconn:
            self.bind(("", 0))
        
        buf = BytesIO(_BaseSocket.recv(self, bufsize, flags))
        buf.seek(+2, SEEK_CUR)
        frag = buf.read(1)
        if ord(frag):
            raise NotImplementedError("Received UDP packet fragment")
        fromhost, fromport = self._read_SOCKS5_address(buf)
        
        peerhost, peerport = self.proxy_peername
        filterhost = socket.inet_pton(self.family, peerhost).strip(b"\x00")
        filterhost = filterhost and fromhost != peerhost
        if filterhost or peerport not in (0, fromport):
            raise socket.error(EAGAIN, "Packet filtered")
        
        return (buf.read(), (fromhost, fromport)) 
Example #23
Source File: tva.py    From movistartv2xmltv with GNU General Public License v2.0 5 votes vote down vote up
def getfiles(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.settimeout(3)
        sock.bind((self.mcast_grp, self.mcast_port))
        mreq = struct.pack("=4sl", socket.inet_aton(self.mcast_grp), socket.INADDR_ANY)
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
        loop = True
        chunk = {}
        chunk["end"] = 0
	N = 335
        #Wait for an end chunk to start by the beginning
        while not (chunk["end"]):
            chunk = self._getchunk(sock)
            firstfile = str(chunk["filetype"])+"_"+str(chunk["fileid"])
        #Loop until firstfile
        while (loop):
                xmldata=""
                chunk = self._getchunk(sock)
                #Discard headers
                body=chunk["data"]
                while not (chunk["end"]):
                        xmldata+=body
                        chunk = self._getchunk(sock)
                        body=chunk["data"]
                #Discard last 4bytes binary footer?
                xmldata+=body[:-4]
                self._files[str(chunk["filetype"])+"_"+str(chunk["fileid"])]=xmldata
		N = N - 1
                if (str(chunk["filetype"])+"_"+str(chunk["fileid"]) == firstfile or N == 0):
                    loop = False
        sock.close() 
Example #24
Source File: udp_gateway.py    From tandem with Apache License 2.0 5 votes vote down vote up
def __init__(self, host, port, handler_function, proxies=[]):
        super(UDPGateway, self).__init__(handler_function, proxies)
        self._host = host
        self._port = port
        self._socket = socket.socket(
            socket.AF_INET,
            socket.SOCK_DGRAM,
        )
        self._shutdown_requested = False 
Example #25
Source File: interface.py    From rift-python with Apache License 2.0 5 votes vote down vote up
def create_socket_ipv6_tx_mcast(self, multicast_address, port, loopback):
        if self._interface_index is None:
            self.warning("Could not create IPv6 multicast TX socket: unknown interface index")
            return None
        try:
            sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        except IOError as err:
            self.warning("Could not create IPv6 UDP socket: %s", err)
            return None
        self.enable_addr_and_port_reuse(sock)
        try:
            sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_IF, self._interface_index)
        except IOError as err:
            self.warning("Could not set IPv6 multicast interface index %d: %s",
                         self._interface_index, err)
            return None
        try:
            loop_value = 1 if loopback else 0
            sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_LOOP, loop_value)
        except IOError as err:
            self.warning("Could not set IPv6 multicast loopback value %d: %s", loop_value, err)
            return None
        try:
            scoped_ipv6_multicast_address = (
                str(multicast_address) + '%' + self.physical_interface_name)
            sock_addr = socket.getaddrinfo(scoped_ipv6_multicast_address, port,
                                           socket.AF_INET6, socket.SOCK_DGRAM)[0][4]
            sock.connect(sock_addr)
        except (IOError, OSError) as err:
            self.warning("Could not connect UDP socket to address %s port %d: %s",
                         scoped_ipv6_multicast_address, port, err)
            return None
        return sock 
Example #26
Source File: mitm_relay.py    From mitm_relay with Apache License 2.0 5 votes vote down vote up
def create_server(relay, cfg):
	proto, lport, rhost, rport = relay

	if proto == 'tcp':
		serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
		serv.bind((cfg.listen, lport))
		serv.listen(2)

		print('[+] Relay listening on %s %d -> %s:%d' % relay)

		while True:
			if proto == 'tcp':
				client, addr = serv.accept()
				dest_str = '%s:%d' % (relay[2], relay[3])

				print(color('[+] New client %s:%d will be relayed to %s' % (addr[0], addr[1], dest_str), 1, 39))
				thread = Thread(target=handle_tcp_client, args=(client, (rhost, rport), cfg))
				thread.start()
	else:
		serv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
		serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
		serv.bind((cfg.listen, lport))

		thread = Thread(target=do_relay_udp, args=(serv, (rhost, rport), cfg))
		thread.start() 
Example #27
Source File: utils.py    From 3vilTwinAttacker with MIT License 5 votes vote down vote up
def getHwAddr(ifname):
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        info = ioctl(s.fileno(), 0x8927,  pack('256s', ifname[:15]))
        return ':'.join(['%02x' % ord(char) for char in info[18:24]]) 
Example #28
Source File: networkmanager.py    From ffw with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, config, targetPort):
        self.config = config
        self.sock = None
        self.targetPort = int(targetPort)

        self.connectTimeout = config['connectTimeout']
        self.recvTimeout = config['recvTimeout']
        self.testServerConnectionTimeout = 1

        if config["ipproto"] is "tcp":
            logging.info("Using: TCP")
            self.openConnection = self.openConnectionTcp
            self.closeConnection = self.closeConnectionTcp
            self.sendData = self.sendDataTcp
            self.receiveData = self.receiveDataTcp
            self.testServerConnection = self.testServerConnectionTcp
        elif config["ipproto"] is "udp":
            logging.info("Using: UDP")
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            self.sock.settimeout(1.0)
            self.openConnection = self.openConnectionUdp
            self.closeConnection = self.closeConnectionUdp
            self.sendData = self.sendDataUdp
            self.receiveData = self.receiveDataUdp
            self.testServerConnection = self.testServerConnectionUdp
        else:
            logging.error("Unknown proto: -" + config["ipproto"] + "-")


    ###################################### 
Example #29
Source File: connection_manager.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def _server_discovery(self):
        
        MULTI_GROUP = ("<broadcast>", 7359)
        MESSAGE = "who is EmbyServer?"
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.settimeout(1.0) # This controls the socket.timeout exception
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 20)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        sock.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_LOOP, 1)
        sock.setsockopt(socket.IPPROTO_IP, socket.SO_REUSEADDR, 1)
        
        LOG.debug("MultiGroup      : %s", str(MULTI_GROUP))
        LOG.debug("Sending UDP Data: %s", MESSAGE)
        servers = []

        try:
            sock.sendto(MESSAGE, MULTI_GROUP)
        except Exception as error:
            LOG.error(error)

            return servers

        while True:
            try:
                data, addr = sock.recvfrom(1024) # buffer size
                servers.append(json.loads(data))
            
            except socket.timeout:
                LOG.info("Found Servers: %s", servers)

                return servers
            
            except Exception as e:
                LOG.error("Error trying to find servers: %s", e)

                return servers 
Example #30
Source File: interface.py    From rift-python with Apache License 2.0 5 votes vote down vote up
def create_socket_ipv4_tx_ucast(self, remote_address, port):
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        except IOError as err:
            self.warning("Could not create IPv4 UDP socket: %s", err)
            return None
        self.enable_addr_and_port_reuse(sock)
        try:
            sock.connect((remote_address, port))
        except IOError as err:
            self.warning("Could not connect UDP socket to address %s port %d: %s",
                         remote_address, port, err)
            return None
        return sock