Python socket.getservbyport() Examples
The following are 30
code examples of socket.getservbyport().
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: PortScan.py From Python-Scripts with GNU General Public License v3.0 | 7 votes |
def scan(ip,port,l): printer("Testing Port: "+str(port)) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) space = 10 - l space = " " * space if s.connect_ex((ip,port)): return None else : try: service = socket.getservbyport(port) print(str(port) + "/TCP" + space + service) except socket.error: print(str(port) + "/TCP" + space + "Unknown") except KeyboardInterrupt: print(red+"[-] Exiting!"+end) exit(1) return True
Example #2
Source File: ravello_cli.py From python-sdk with Apache License 2.0 | 6 votes |
def validate_service_arg(args, name): """Validate a service argument. Can be either a port number, a port range, or a symbolic service name from /etc/services.""" value = args.get(name) if isinstance(args, dict) else args if value.isdigit(): port = int(value) if not 1 <= port < 65536: raise ValueError('illegal port number for {0}: {1}'.format(name, value)) try: name = socket.getservbyport(port) except socket.error: name = 'p-{0}'.format(port) elif re_range.match(value): start, end = map(int, value.split('-')) if not 1 <= start < 65536 or not 1 <= end < 65536 or end <= start: raise ValueError('illegal port range for {0}: {1}'.format(name, value)) name = 'r-{0}+{1}'.format(start, end-start) else: name = value try: value = socket.getservbyname(name) except socket.error: raise ValueError('unknown service for {0}: {1}'.format(name, value)) return (name, value)
Example #3
Source File: test_socket.py From CTFCrackTools with GNU General Public License v3.0 | 5 votes |
def testGetServBy(self): eq = self.assertEqual # Find one service that exists, then check all the related interfaces. # I've ordered this by protocols that have both a tcp and udp # protocol, at least for modern Linuxes. if sys.platform in ('linux2', 'freebsd4', 'freebsd5', 'freebsd6', 'darwin') or is_bsd: # avoid the 'echo' service on this platform, as there is an # assumption breaking non-standard port/protocol entry services = ('daytime', 'qotd', 'domain') else: services = ('echo', 'daytime', 'domain') for service in services: try: port = socket.getservbyname(service, 'tcp') break except socket.error: pass else: raise socket.error # Try same call with optional protocol omitted port2 = socket.getservbyname(service) eq(port, port2) # Try udp, but don't barf it it doesn't exist try: udpport = socket.getservbyname(service, 'udp') except socket.error: udpport = None else: eq(udpport, port) # Now make sure the lookup by port returns the same service name eq(socket.getservbyport(port2), service) eq(socket.getservbyport(port, 'tcp'), service) if udpport is not None: eq(socket.getservbyport(udpport, 'udp'), service)
Example #4
Source File: test_socket.py From ironpython2 with Apache License 2.0 | 5 votes |
def testGetServBy(self): eq = self.assertEqual # Find one service that exists, then check all the related interfaces. # I've ordered this by protocols that have both a tcp and udp # protocol, at least for modern Linuxes. if (sys.platform.startswith('linux') or sys.platform.startswith('freebsd') or sys.platform.startswith('netbsd') or sys.platform == 'darwin'): # avoid the 'echo' service on this platform, as there is an # assumption breaking non-standard port/protocol entry services = ('daytime', 'qotd', 'domain') else: services = ('echo', 'daytime', 'domain') for service in services: try: port = socket.getservbyname(service, 'tcp') break except socket.error: pass else: raise socket.error # Try same call with optional protocol omitted port2 = socket.getservbyname(service) eq(port, port2) # Try udp, but don't barf if it doesn't exist try: udpport = socket.getservbyname(service, 'udp') except socket.error: udpport = None else: eq(udpport, port) # Now make sure the lookup by port returns the same service name eq(socket.getservbyport(port2), service) eq(socket.getservbyport(port, 'tcp'), service) if udpport is not None: eq(socket.getservbyport(udpport, 'udp'), service) # Make sure getservbyport does not accept out of range ports. self.assertRaises(OverflowError, socket.getservbyport, -1) self.assertRaises(OverflowError, socket.getservbyport, 65536)
Example #5
Source File: resolver.py From Tautulli with GNU General Public License v3.0 | 5 votes |
def _getnameinfo(sockaddr, flags=0): host = sockaddr[0] port = sockaddr[1] if len(sockaddr) == 4: scope = sockaddr[3] family = socket.AF_INET6 else: scope = None family = socket.AF_INET tuples = _getaddrinfo(host, port, family, socket.SOCK_STREAM, socket.SOL_TCP, 0) if len(tuples) > 1: raise socket.error('sockaddr resolved to multiple addresses') addr = tuples[0][4][0] if flags & socket.NI_DGRAM: pname = 'udp' else: pname = 'tcp' qname = dns.reversename.from_address(addr) if flags & socket.NI_NUMERICHOST == 0: try: answer = _resolver.query(qname, 'PTR') hostname = answer.rrset[0].target.to_text(True) except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer): if flags & socket.NI_NAMEREQD: raise socket.gaierror(socket.EAI_NONAME) hostname = addr if scope is not None: hostname += '%' + str(scope) else: hostname = addr if scope is not None: hostname += '%' + str(scope) if flags & socket.NI_NUMERICSERV: service = str(port) else: service = socket.getservbyport(port, pname) return (hostname, service)
Example #6
Source File: resolver.py From arissploit with GNU General Public License v3.0 | 5 votes |
def _getnameinfo(sockaddr, flags=0): host = sockaddr[0] port = sockaddr[1] if len(sockaddr) == 4: scope = sockaddr[3] family = socket.AF_INET6 else: scope = None family = socket.AF_INET tuples = _getaddrinfo(host, port, family, socket.SOCK_STREAM, socket.SOL_TCP, 0) if len(tuples) > 1: raise socket.error('sockaddr resolved to multiple addresses') addr = tuples[0][4][0] if flags & socket.NI_DGRAM: pname = 'udp' else: pname = 'tcp' qname = dns.reversename.from_address(addr) if flags & socket.NI_NUMERICHOST == 0: try: answer = _resolver.query(qname, 'PTR') hostname = answer.rrset[0].target.to_text(True) except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer): if flags & socket.NI_NAMEREQD: raise socket.gaierror(socket.EAI_NONAME) hostname = addr if scope is not None: hostname += '%' + str(scope) else: hostname = addr if scope is not None: hostname += '%' + str(scope) if flags & socket.NI_NUMERICSERV: service = str(port) else: service = socket.getservbyport(port, pname) return (hostname, service)
Example #7
Source File: 11_4_finding_service_name.py From Python-Network-Programming with MIT License | 5 votes |
def find_service_name(): protocolname = 'tcp' for port in [80, 25]: print ("Port: %s => service name: %s" %(port, socket.getservbyport(port, protocolname))) print ("Port: %s => service name: %s" %(53, socket.getservbyport(53, 'udp')))
Example #8
Source File: resolver.py From bazarr with GNU General Public License v3.0 | 5 votes |
def _getnameinfo(sockaddr, flags=0): host = sockaddr[0] port = sockaddr[1] if len(sockaddr) == 4: scope = sockaddr[3] family = socket.AF_INET6 else: scope = None family = socket.AF_INET tuples = _getaddrinfo(host, port, family, socket.SOCK_STREAM, socket.SOL_TCP, 0) if len(tuples) > 1: raise socket.error('sockaddr resolved to multiple addresses') addr = tuples[0][4][0] if flags & socket.NI_DGRAM: pname = 'udp' else: pname = 'tcp' qname = dns.reversename.from_address(addr) if flags & socket.NI_NUMERICHOST == 0: try: answer = _resolver.query(qname, 'PTR') hostname = answer.rrset[0].target.to_text(True) except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer): if flags & socket.NI_NAMEREQD: raise socket.gaierror(socket.EAI_NONAME) hostname = addr if scope is not None: hostname += '%' + str(scope) else: hostname = addr if scope is not None: hostname += '%' + str(scope) if flags & socket.NI_NUMERICSERV: service = str(port) else: service = socket.getservbyport(port, pname) return (hostname, service)
Example #9
Source File: test_socket.py From CTFCrackTools-V2 with GNU General Public License v3.0 | 5 votes |
def testGetServBy(self): eq = self.assertEqual # Find one service that exists, then check all the related interfaces. # I've ordered this by protocols that have both a tcp and udp # protocol, at least for modern Linuxes. if sys.platform in ('linux2', 'freebsd4', 'freebsd5', 'freebsd6', 'darwin') or is_bsd: # avoid the 'echo' service on this platform, as there is an # assumption breaking non-standard port/protocol entry services = ('daytime', 'qotd', 'domain') else: services = ('echo', 'daytime', 'domain') for service in services: try: port = socket.getservbyname(service, 'tcp') break except socket.error: pass else: raise socket.error # Try same call with optional protocol omitted port2 = socket.getservbyname(service) eq(port, port2) # Try udp, but don't barf it it doesn't exist try: udpport = socket.getservbyname(service, 'udp') except socket.error: udpport = None else: eq(udpport, port) # Now make sure the lookup by port returns the same service name eq(socket.getservbyport(port2), service) eq(socket.getservbyport(port, 'tcp'), service) if udpport is not None: eq(socket.getservbyport(udpport, 'udp'), service)
Example #10
Source File: 1_4_finding_service_name.py From Python-Network-Programming-Cookbook-Second-Edition with MIT License | 5 votes |
def find_service_name(): protocolname = 'tcp' for port in [80, 25]: print ("Port: %s => service name: %s" %(port, socket.getservbyport(port, protocolname))) print ("Port: %s => service name: %s" %(53, socket.getservbyport(53, 'udp')))
Example #11
Source File: network.py From PythonForWindows with BSD 3-Clause "New" or "Revised" License | 5 votes |
def remote_proto(self): """Identification of the protocol associated with the remote port. Equals ``remote_port`` if no protocol is associated with it. :type: :class:`str` or :class:`int` """ try: return socket.getservbyport(self.remote_port, 'tcp') except socket.error: return self.remote_port
Example #12
Source File: resolver.py From elasticintel with GNU General Public License v3.0 | 5 votes |
def _getnameinfo(sockaddr, flags=0): host = sockaddr[0] port = sockaddr[1] if len(sockaddr) == 4: scope = sockaddr[3] family = socket.AF_INET6 else: scope = None family = socket.AF_INET tuples = _getaddrinfo(host, port, family, socket.SOCK_STREAM, socket.SOL_TCP, 0) if len(tuples) > 1: raise socket.error('sockaddr resolved to multiple addresses') addr = tuples[0][4][0] if flags & socket.NI_DGRAM: pname = 'udp' else: pname = 'tcp' qname = dns.reversename.from_address(addr) if flags & socket.NI_NUMERICHOST == 0: try: answer = _resolver.query(qname, 'PTR') hostname = answer.rrset[0].target.to_text(True) except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer): if flags & socket.NI_NAMEREQD: raise socket.gaierror(socket.EAI_NONAME) hostname = addr if scope is not None: hostname += '%' + str(scope) else: hostname = addr if scope is not None: hostname += '%' + str(scope) if flags & socket.NI_NUMERICSERV: service = str(port) else: service = socket.getservbyport(port, pname) return (hostname, service)
Example #13
Source File: resolver.py From Cloudmare with GNU General Public License v3.0 | 5 votes |
def _getnameinfo(sockaddr, flags=0): host = sockaddr[0] port = sockaddr[1] if len(sockaddr) == 4: scope = sockaddr[3] family = socket.AF_INET6 else: scope = None family = socket.AF_INET tuples = _getaddrinfo(host, port, family, socket.SOCK_STREAM, socket.SOL_TCP, 0) if len(tuples) > 1: raise socket.error('sockaddr resolved to multiple addresses') addr = tuples[0][4][0] if flags & socket.NI_DGRAM: pname = 'udp' else: pname = 'tcp' qname = thirdparty.dns.reversename.from_address(addr) if flags & socket.NI_NUMERICHOST == 0: try: answer = _resolver.query(qname, 'PTR') hostname = answer.rrset[0].target.to_text(True) except (thirdparty.dns.resolver.NXDOMAIN, thirdparty.dns.resolver.NoAnswer): if flags & socket.NI_NAMEREQD: raise socket.gaierror(socket.EAI_NONAME) hostname = addr if scope is not None: hostname += '%' + str(scope) else: hostname = addr if scope is not None: hostname += '%' + str(scope) if flags & socket.NI_NUMERICSERV: service = str(port) else: service = socket.getservbyport(port, pname) return (hostname, service)
Example #14
Source File: test_socket.py From medicare-demo with Apache License 2.0 | 5 votes |
def testGetServBy(self): eq = self.assertEqual # Find one service that exists, then check all the related interfaces. # I've ordered this by protocols that have both a tcp and udp # protocol, at least for modern Linuxes. if sys.platform in ('linux2', 'freebsd4', 'freebsd5', 'freebsd6', 'darwin') or is_bsd: # avoid the 'echo' service on this platform, as there is an # assumption breaking non-standard port/protocol entry services = ('daytime', 'qotd', 'domain') else: services = ('echo', 'daytime', 'domain') for service in services: try: port = socket.getservbyname(service, 'tcp') break except socket.error: pass else: raise socket.error # Try same call with optional protocol omitted port2 = socket.getservbyname(service) eq(port, port2) # Try udp, but don't barf it it doesn't exist try: udpport = socket.getservbyname(service, 'udp') except socket.error: udpport = None else: eq(udpport, port) # Now make sure the lookup by port returns the same service name eq(socket.getservbyport(port2), service) eq(socket.getservbyport(port, 'tcp'), service) if udpport is not None: eq(socket.getservbyport(udpport, 'udp'), service)
Example #15
Source File: test_socket.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 5 votes |
def testGetServBy(self): eq = self.assertEqual # Find one service that exists, then check all the related interfaces. # I've ordered this by protocols that have both a tcp and udp # protocol, at least for modern Linuxes. if (sys.platform.startswith(('freebsd', 'netbsd', 'gnukfreebsd')) or sys.platform in ('linux', 'darwin')): # avoid the 'echo' service on this platform, as there is an # assumption breaking non-standard port/protocol entry services = ('daytime', 'qotd', 'domain') else: services = ('echo', 'daytime', 'domain') for service in services: try: port = socket.getservbyname(service, 'tcp') break except OSError: pass else: raise OSError # Try same call with optional protocol omitted port2 = socket.getservbyname(service) eq(port, port2) # Try udp, but don't barf if it doesn't exist try: udpport = socket.getservbyname(service, 'udp') except OSError: udpport = None else: eq(udpport, port) # Now make sure the lookup by port returns the same service name eq(socket.getservbyport(port2), service) eq(socket.getservbyport(port, 'tcp'), service) if udpport is not None: eq(socket.getservbyport(udpport, 'udp'), service) # Make sure getservbyport does not accept out of range ports. self.assertRaises(OverflowError, socket.getservbyport, -1) self.assertRaises(OverflowError, socket.getservbyport, 65536)
Example #16
Source File: misc.py From pilot with Apache License 2.0 | 5 votes |
def url_is_local (arg) : """ Returns True if the given url points to localhost. We consider all URLs which explicitly define a port as non-local, because it looks like someone wants to explicitly use some protocol -- `ssh://localost:2222/` is likely to point at an ssh tunnel. If, however, the port matches the default port for the given protocol, we consider it local again -- `ssh://localhost:22/` is most likely a real local activity. Note that the schema set operates on substring level, so that we will accept port 22 for `ssh` and also for `sge+ssh` -- this may break in corner cases (altough I can't think of any right now). """ u = saga.Url (arg) if not host_is_local (u.host) : return False # host is local, but what does the port indicate? if u.port and u.port > 0 : try : if socket.getservbyport (u.port) in u.schema : # some non-default port is used -- consider remote return False except : # unknown service port --assume this is non-standard... return False # port is not set or points to default port for service return True # -------------------------------------------------------------------- #
Example #17
Source File: test_socket.py From gcblue with BSD 3-Clause "New" or "Revised" License | 5 votes |
def testGetServBy(self): eq = self.assertEqual # Find one service that exists, then check all the related interfaces. # I've ordered this by protocols that have both a tcp and udp # protocol, at least for modern Linuxes. if (sys.platform.startswith('linux') or sys.platform.startswith('freebsd') or sys.platform.startswith('netbsd') or sys.platform == 'darwin'): # avoid the 'echo' service on this platform, as there is an # assumption breaking non-standard port/protocol entry services = ('daytime', 'qotd', 'domain') else: services = ('echo', 'daytime', 'domain') for service in services: try: port = socket.getservbyname(service, 'tcp') break except socket.error: pass else: raise socket.error # Try same call with optional protocol omitted port2 = socket.getservbyname(service) eq(port, port2) # Try udp, but don't barf if it doesn't exist try: udpport = socket.getservbyname(service, 'udp') except socket.error: udpport = None else: eq(udpport, port) # Now make sure the lookup by port returns the same service name eq(socket.getservbyport(port2), service) eq(socket.getservbyport(port, 'tcp'), service) if udpport is not None: eq(socket.getservbyport(udpport, 'udp'), service) # Make sure getservbyport does not accept out of range ports. self.assertRaises(OverflowError, socket.getservbyport, -1) self.assertRaises(OverflowError, socket.getservbyport, 65536)
Example #18
Source File: ravello_cli.py From python-sdk with Apache License 2.0 | 5 votes |
def getservbyport(port): """Like socket.getservbyport() but return a descriptive string if the service is not found.""" try: name = socket.getservbyport(port) except socket.error: name = 'port-{0}'.format(port) return name
Example #19
Source File: resolver.py From luscan-devel with GNU General Public License v2.0 | 5 votes |
def _getnameinfo(sockaddr, flags=0): host = sockaddr[0] port = sockaddr[1] if len(sockaddr) == 4: scope = sockaddr[3] family = socket.AF_INET6 else: scope = None family = socket.AF_INET tuples = _getaddrinfo(host, port, family, socket.SOCK_STREAM, socket.SOL_TCP, 0) if len(tuples) > 1: raise socket.error('sockaddr resolved to multiple addresses') addr = tuples[0][4][0] if flags & socket.NI_DGRAM: pname = 'udp' else: pname = 'tcp' qname = dns.reversename.from_address(addr) if flags & socket.NI_NUMERICHOST == 0: try: answer = _resolver.query(qname, 'PTR') hostname = answer.rrset[0].target.to_text(True) except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer): if flags & socket.NI_NAMEREQD: raise socket.gaierror(socket.EAI_NONAME) hostname = addr if scope is not None: hostname += '%' + str(scope) else: hostname = addr if scope is not None: hostname += '%' + str(scope) if flags & socket.NI_NUMERICSERV: service = str(port) else: service = socket.getservbyport(port, pname) return (hostname, service)
Example #20
Source File: test__socket.py From ironpython3 with Apache License 2.0 | 5 votes |
def test_getservbyport(self): self.assertEqual(_socket.getservbyport(80), "http")
Example #21
Source File: test_socket.py From ironpython3 with Apache License 2.0 | 5 votes |
def testGetServBy(self): eq = self.assertEqual # Find one service that exists, then check all the related interfaces. # I've ordered this by protocols that have both a tcp and udp # protocol, at least for modern Linuxes. if (sys.platform.startswith(('freebsd', 'netbsd', 'gnukfreebsd')) or sys.platform in ('linux', 'darwin')): # avoid the 'echo' service on this platform, as there is an # assumption breaking non-standard port/protocol entry services = ('daytime', 'qotd', 'domain') else: services = ('echo', 'daytime', 'domain') for service in services: try: port = socket.getservbyname(service, 'tcp') break except OSError: pass else: raise OSError # Try same call with optional protocol omitted port2 = socket.getservbyname(service) eq(port, port2) # Try udp, but don't barf if it doesn't exist try: udpport = socket.getservbyname(service, 'udp') except OSError: udpport = None else: eq(udpport, port) # Now make sure the lookup by port returns the same service name eq(socket.getservbyport(port2), service) eq(socket.getservbyport(port, 'tcp'), service) if udpport is not None: eq(socket.getservbyport(udpport, 'udp'), service) # Make sure getservbyport does not accept out of range ports. self.assertRaises(OverflowError, socket.getservbyport, -1) self.assertRaises(OverflowError, socket.getservbyport, 65536)
Example #22
Source File: resolver.py From script.elementum.burst with Do What The F*ck You Want To Public License | 5 votes |
def _getnameinfo(sockaddr, flags=0): host = sockaddr[0] port = sockaddr[1] if len(sockaddr) == 4: scope = sockaddr[3] family = socket.AF_INET6 else: scope = None family = socket.AF_INET tuples = _getaddrinfo(host, port, family, socket.SOCK_STREAM, socket.SOL_TCP, 0) if len(tuples) > 1: raise socket.error('sockaddr resolved to multiple addresses') addr = tuples[0][4][0] if flags & socket.NI_DGRAM: pname = 'udp' else: pname = 'tcp' qname = dns.reversename.from_address(addr) if flags & socket.NI_NUMERICHOST == 0: try: answer = _resolver.query(qname, 'PTR') hostname = answer.rrset[0].target.to_text(True) except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer): if flags & socket.NI_NAMEREQD: raise socket.gaierror(socket.EAI_NONAME) hostname = addr if scope is not None: hostname += '%' + str(scope) else: hostname = addr if scope is not None: hostname += '%' + str(scope) if flags & socket.NI_NUMERICSERV: service = str(port) else: service = socket.getservbyport(port, pname) return (hostname, service)
Example #23
Source File: socket_finding_service_name.py From Learning-Python-Networking-Second-Edition with MIT License | 5 votes |
def find_service_name(): protocolname = 'tcp' for port in [80, 25]: print ("Port: %s => service name: %s" %(port, socket.getservbyport(port, protocolname))) print ("Port: %s => service name: %s" %(53, socket.getservbyport(53, 'udp')))
Example #24
Source File: test_socket.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def testGetServBy(self): eq = self.assertEqual # Find one service that exists, then check all the related interfaces. # I've ordered this by protocols that have both a tcp and udp # protocol, at least for modern Linuxes. if (sys.platform.startswith(('freebsd', 'netbsd', 'gnukfreebsd')) or sys.platform in ('linux', 'darwin')): # avoid the 'echo' service on this platform, as there is an # assumption breaking non-standard port/protocol entry services = ('daytime', 'qotd', 'domain') else: services = ('echo', 'daytime', 'domain') for service in services: try: port = socket.getservbyname(service, 'tcp') break except OSError: pass else: raise OSError # Try same call with optional protocol omitted port2 = socket.getservbyname(service) eq(port, port2) # Try udp, but don't barf if it doesn't exist try: udpport = socket.getservbyname(service, 'udp') except OSError: udpport = None else: eq(udpport, port) # Now make sure the lookup by port returns the same service name eq(socket.getservbyport(port2), service) eq(socket.getservbyport(port, 'tcp'), service) if udpport is not None: eq(socket.getservbyport(udpport, 'udp'), service) # Make sure getservbyport does not accept out of range ports. self.assertRaises(OverflowError, socket.getservbyport, -1) self.assertRaises(OverflowError, socket.getservbyport, 65536)
Example #25
Source File: analyzer.py From python-netflow-v9-softflowd with MIT License | 5 votes |
def service(self): # Resolve ports to their services, if known default = "({} {})".format(self.src_port, self.dest_port) with contextlib.suppress(OSError): return socket.getservbyport(self.src_port) with contextlib.suppress(OSError): return socket.getservbyport(self.dest_port) return default
Example #26
Source File: portscan.py From FinalRecon with MIT License | 5 votes |
def sock_conn(ip, port, output, result): try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(3) s.connect((ip, port)) s.close() service = socket.getservbyport(port, 'tcp') print(G + '[+] ' + C + str(port).ljust(7) + W + service.ljust(9)) if output != 'None': result.update({str(port):service}) except: s.close() pass
Example #27
Source File: test_socket.py From oss-ftp with MIT License | 5 votes |
def testGetServBy(self): eq = self.assertEqual # Find one service that exists, then check all the related interfaces. # I've ordered this by protocols that have both a tcp and udp # protocol, at least for modern Linuxes. if (sys.platform.startswith('linux') or sys.platform.startswith('freebsd') or sys.platform.startswith('netbsd') or sys.platform == 'darwin'): # avoid the 'echo' service on this platform, as there is an # assumption breaking non-standard port/protocol entry services = ('daytime', 'qotd', 'domain') else: services = ('echo', 'daytime', 'domain') for service in services: try: port = socket.getservbyname(service, 'tcp') break except socket.error: pass else: raise socket.error # Try same call with optional protocol omitted port2 = socket.getservbyname(service) eq(port, port2) # Try udp, but don't barf if it doesn't exist try: udpport = socket.getservbyname(service, 'udp') except socket.error: udpport = None else: eq(udpport, port) # Now make sure the lookup by port returns the same service name eq(socket.getservbyport(port2), service) eq(socket.getservbyport(port, 'tcp'), service) if udpport is not None: eq(socket.getservbyport(udpport, 'udp'), service) # Make sure getservbyport does not accept out of range ports. self.assertRaises(OverflowError, socket.getservbyport, -1) self.assertRaises(OverflowError, socket.getservbyport, 65536)
Example #28
Source File: test_socket.py From BinderFilter with MIT License | 5 votes |
def testGetServBy(self): eq = self.assertEqual # Find one service that exists, then check all the related interfaces. # I've ordered this by protocols that have both a tcp and udp # protocol, at least for modern Linuxes. if (sys.platform.startswith('linux') or sys.platform.startswith('freebsd') or sys.platform.startswith('netbsd') or sys.platform == 'darwin'): # avoid the 'echo' service on this platform, as there is an # assumption breaking non-standard port/protocol entry services = ('daytime', 'qotd', 'domain') else: services = ('echo', 'daytime', 'domain') for service in services: try: port = socket.getservbyname(service, 'tcp') break except socket.error: pass else: raise socket.error # Try same call with optional protocol omitted port2 = socket.getservbyname(service) eq(port, port2) # Try udp, but don't barf if it doesn't exist try: udpport = socket.getservbyname(service, 'udp') except socket.error: udpport = None else: eq(udpport, port) # Now make sure the lookup by port returns the same service name eq(socket.getservbyport(port2), service) eq(socket.getservbyport(port, 'tcp'), service) if udpport is not None: eq(socket.getservbyport(udpport, 'udp'), service) # Make sure getservbyport does not accept out of range ports. self.assertRaises(OverflowError, socket.getservbyport, -1) self.assertRaises(OverflowError, socket.getservbyport, 65536)
Example #29
Source File: httpd.py From tsusen with MIT License | 4 votes |
def _dataset(self): result = "\n" dates = set() rows = [] indexes = {} filters = self._get_filters() for filename in sorted(glob.glob(os.path.join(LOG_DIRECTORY, "*.csv")))[-config.TRENDLINE_PERIOD:]: with open(filename, "rb") as f: match = re.search(r"([\d-]+)\.csv", filename) if match: date = match.group(1) else: continue reader = csv.DictReader(f, delimiter=' ') for row in reader: key = (row["proto"], row["dst_port"], row["dst_ip"], row["src_ip"]) if filters and not (addr_to_int(row["src_ip"]) in filters or addr_to_int(row["dst_ip"]) in filters): continue if key not in indexes: indexes[key] = len(rows) rows.append(row) else: index = indexes[key] rows[index]["first_seen"] = min(int(rows[index]["first_seen"]), int(row["first_seen"])) rows[index]["last_seen"] = max(int(rows[index]["last_seen"]), int(row["last_seen"])) rows[index]["count"] = int(rows[index]["count"]) + int(row["count"]) for row in rows: try: port = int(row['dst_port']) port_name = MISC_PORTS.get(port) or socket.getservbyport(port, row['proto'].lower()) except Exception: port_name = None finally: result += "[" for column in ("proto", "dst_port", "dst_ip", "src_ip", "first_seen", "last_seen", "count"): if "_seen" in column: result += '"%s",' % datetime.datetime.utcfromtimestamp(int(row[column])).strftime(TIME_FORMAT) elif "_port" in column and port_name: result += '"%s (%s)",' % (row[column], port_name) else: result += '"%s",' % row[column] result += "],\n" return result
Example #30
Source File: test_functional.py From pyftpdlib with MIT License | 4 votes |
def test_permit_privileged_ports(self): # Test FTPHandler.permit_privileged_ports_active attribute # try to bind a socket on a privileged port sock = None for port in reversed(range(1, 1024)): try: socket.getservbyport(port) except socket.error: # not registered port; go on try: sock = socket.socket(self.client.af, socket.SOCK_STREAM) self.addCleanup(sock.close) sock.settimeout(TIMEOUT) sock.bind((HOST, port)) break except socket.error as err: if err.errno == errno.EACCES: # root privileges needed if sock is not None: sock.close() sock = None break sock.close() continue else: # registered port found; skip to the next one continue else: # no usable privileged port was found sock = None with self.server.lock: self.server.handler.permit_privileged_ports = False self.assertRaises(ftplib.error_perm, self.client.sendport, HOST, port) if sock: port = sock.getsockname()[1] with self.server.lock: self.server.handler.permit_privileged_ports = True sock.listen(5) sock.settimeout(TIMEOUT) self.client.sendport(HOST, port) s, addr = sock.accept() s.close()