Python socket.SOCK_DGRAM Examples
The following are 30 code examples for showing how to use socket.SOCK_DGRAM(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.
You may also want to check out all available functions/classes of the module
socket
, or try the search function
.
Example 1
Project: python-lifx-sdk Author: smarthall File: network.py License: MIT License | 7 votes |
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 2
Project: XFLTReaT Author: earthquake File: UDP_generic.py License: MIT License | 6 votes |
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 3
Project: XFLTReaT Author: earthquake File: UDP_generic.py License: MIT License | 6 votes |
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 4
Project: wio-cli Author: Seeed-Studio File: udp.py License: MIT License | 6 votes |
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 5
Project: jawfish Author: war-and-code File: handlers.py License: MIT License | 6 votes |
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 6
Project: dronekit-python Author: dronekit File: mavlink.py License: Apache License 2.0 | 6 votes |
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 7
Project: rift-python Author: brunorijsman File: multicast_checks.py License: Apache License 2.0 | 6 votes |
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 8
Project: rift-python Author: brunorijsman File: multicast_checks.py License: Apache License 2.0 | 6 votes |
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 9
Project: rift-python Author: brunorijsman File: udp_rx_handler.py License: Apache License 2.0 | 6 votes |
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 10
Project: rift-python Author: brunorijsman File: interface.py License: Apache License 2.0 | 6 votes |
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 11
Project: plugin.video.kmediatorrent Author: jmarth File: socks.py License: GNU General Public License v3.0 | 6 votes |
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 12
Project: plugin.video.kmediatorrent Author: jmarth File: socks.py License: GNU General Public License v3.0 | 6 votes |
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 13
Project: rex Author: angr File: network_feeder.py License: BSD 2-Clause "Simplified" License | 6 votes |
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 14
Project: nukemyluks Author: juliocesarfort File: client.py License: Apache License 2.0 | 6 votes |
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 15
Project: sagemaker-xgboost-container Author: aws File: tracker.py License: Apache License 2.0 | 6 votes |
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 16
Project: tandem Author: typeintandem File: server.py License: Apache License 2.0 | 6 votes |
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 17
Project: tandem Author: typeintandem File: client.py License: Apache License 2.0 | 6 votes |
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 18
Project: pynmap Author: the-c0d3r File: ip.py License: GNU General Public License v3.0 | 6 votes |
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 19
Project: PiClock Author: n0bel File: TempServer.py License: MIT License | 6 votes |
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 20
Project: unicorn-hat-hd Author: pimoroni File: show_my_ip.py License: MIT License | 5 votes |
def get_ip(): # get IP address s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('8.8.8.8', 80)) my_ip = s.getsockname()[0] print(my_ip) s.close() return my_ip
Example 21
Project: supervisor-logging Author: infoxchange File: __init__.py License: Apache License 2.0 | 5 votes |
def main(): """ Main application loop. """ env = os.environ try: host = env['SYSLOG_SERVER'] port = int(env['SYSLOG_PORT']) socktype = socket.SOCK_DGRAM if env['SYSLOG_PROTO'] == 'udp' \ else socket.SOCK_STREAM except KeyError: sys.exit("SYSLOG_SERVER, SYSLOG_PORT and SYSLOG_PROTO are required.") handler = SysLogHandler( address=(host, port), socktype=socktype, ) handler.setFormatter(PalletFormatter()) for event_headers, event_data in supervisor_events(sys.stdin, sys.stdout): event = logging.LogRecord( name=event_headers['processname'], level=logging.INFO, pathname=None, lineno=0, msg=event_data, args=(), exc_info=None, ) event.process = int(event_headers['pid']) handler.handle(event)
Example 22
Project: wechatpy Author: wechatpy File: utils.py License: MIT License | 5 votes |
def get_external_ip(): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: wechat_ip = socket.gethostbyname("api.mch.weixin.qq.com") sock.connect((wechat_ip, 80)) addr, port = sock.getsockname() sock.close() return addr except socket.error: return "127.0.0.1"
Example 23
Project: XFLTReaT Author: earthquake File: DNS.py License: MIT License | 5 votes |
def serve(self): server_socket = None if self.zonefile: (hostname, self.ttl, self.zone) = self.DNS_common.parse_zone_file(self.zonefile) if hostname and (hostname+"." != self.hostname): common.internal_print("'hostname' in '{0}' section does not match with the zonefile's origin".format(self.get_module_configname()), -1) return try: common.internal_print("Starting module: {0} on {1}:{2}".format(self.get_module_name(), self.config.get("Global", "serverbind"), self.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"), self.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 24
Project: XFLTReaT Author: earthquake File: DNS.py License: MIT License | 5 votes |
def connect(self): try: common.internal_print("Using nameserver: {0}".format(self.nameserver)) 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.nameserver, self.serverport) self.comms_socket = server_socket self.serverorclient = 0 self.authenticated = False self.qMTU = self.DNS_proto.reverse_RR_type("A")[4](254, self.hostname, 3, self.upload_encoding_class) if self.do_autotune(server_socket): self.do_hello() self.communication(False) except KeyboardInterrupt: self.do_logoff() self.cleanup() raise except socket.error: self.cleanup() raise self.cleanup() return
Example 25
Project: XFLTReaT Author: earthquake File: DNS.py License: MIT License | 5 votes |
def check(self): try: common.internal_print("Using nameserver: {0}".format(self.nameserver)) common.internal_print("Checking module on server: {0}".format(self.get_module_name())) server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.server_tuple = (self.nameserver, self.serverport) self.comms_socket = server_socket self.serverorclient = 0 self.authenticated = False self.qMTU = self.DNS_proto.reverse_RR_type("A")[4](255, self.hostname, 4, self.upload_encoding_class) self.do_check() self.communication(True) except KeyboardInterrupt: self.cleanup() raise except socket.timeout: common.internal_print("Checking failed: {0}".format(self.get_module_name()), -1) except socket.error: self.cleanup() raise self.cleanup() return
Example 26
Project: XFLTReaT Author: earthquake File: interface.py License: MIT License | 5 votes |
def lin_set_mtu(self, dev, mtu): s = socket.socket(type=socket.SOCK_DGRAM) try: ifr = struct.pack('<16sH', dev, mtu) + '\x00'*14 fcntl.ioctl(s, self.IOCTL_LINUX_SIOCSIFMTU, ifr) except Exception as e: common.internal_print("Cannot set MTU ({0}) on interface".format(mtu), -1) sys.exit(-1) return
Example 27
Project: XFLTReaT Author: earthquake File: interface.py License: MIT License | 5 votes |
def mac_set_mtu(self, dev, mtu): s = socket.socket(type=socket.SOCK_DGRAM) try: ifr = struct.pack('<16sH', self.iface_name, 1350)+'\x00'*14 fcntl.ioctl(s, self.IOCTL_MACOSX_SIOCSIFMTU, ifr) except Exception as e: common.internal_print("Cannot set MTU ({0}) on interface".format(mtu), -1) sys.exit(-1) return
Example 28
Project: XFLTReaT Author: earthquake File: interface.py License: MIT License | 5 votes |
def freebsd_set_mtu(self, dev, mtu): s = socket.socket(type=socket.SOCK_DGRAM) try: ifr = struct.pack('<16sH', self.iface_name, mtu) + '\x00'*14 fcntl.ioctl(s, self.IOCTL_FREEBSD_SIOCSIFMTU, ifr) except Exception as e: common.internal_print("Cannot set MTU ({0}) on interface".format(mtu), -1) sys.exit(-1) return
Example 29
Project: XFLTReaT Author: earthquake File: interface.py License: MIT License | 5 votes |
def freebsd_close_tunnel(self, tun): try: os.close(tun) except: pass s = socket.socket(type=socket.SOCK_DGRAM) try: ifr = struct.pack('<16s', self.iface_name) + '\x00'*16 fcntl.ioctl(s, self.IOCTL_FREEBSD_SIOCIFDESTROY, ifr) except Exception as e: common.internal_print("Cannot destroy interface: {0}".format(dev), -1) return
Example 30
Project: ipmisim Author: rhtyd File: fakesession.py License: Apache License 2.0 | 5 votes |
def _xmit_packet(self, retry=True, delay_xmit=None): if self.sequencenumber: self.sequencenumber += 1 if delay_xmit is not None: # skip transmit, let retry timer do it's thing self.waiting_sessions[self] = {} self.waiting_sessions[self]['ipmisession'] = self self.waiting_sessions[self]['timeout'] = delay_xmit + _monotonic_time() return if self.sockaddr: self.send_data(self.netpacket, self.sockaddr) else: self.allsockaddrs = [] try: for res in socket.getaddrinfo(self.bmc, self.port, 0, socket.SOCK_DGRAM): sockaddr = res[4] if res[0] == socket.AF_INET: # convert the sockaddr to AF_INET6 newhost = '::ffff:' + sockaddr[0] sockaddr = (newhost, sockaddr[1], 0, 0) self.allsockaddrs.append(sockaddr) self.bmc_handlers[sockaddr] = self self.send_data(self.netpacket, sockaddr) except socket.gaierror: raise exc.IpmiException("Unable to transmit to specified address") if retry: self.waiting_sessions[self] = {} self.waiting_sessions[self]['ipmisession'] = self self.waiting_sessions[self]['timeout'] = self.timeout + _monotonic_time()