本文整理汇总了Python中socket.getservbyname函数的典型用法代码示例。如果您正苦于以下问题:Python getservbyname函数的具体用法?Python getservbyname怎么用?Python getservbyname使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了getservbyname函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ReplacePortNames
def ReplacePortNames(port_range_string):
"""Replace port names with port numbers in a port-range string.
Args:
port_range_string: The string to parse.
Returns:
A port range string specifying ports only by number.
Raises:
ValueError: If the port_range_string is the wrong type or malformed.
"""
if not isinstance(port_range_string, basestring):
raise ValueError('Invalid port range: %s' % port_range_string)
ports = port_range_string.split('-')
if len(ports) not in [1, 2]:
raise ValueError('Invalid port range: %s' % port_range_string)
try:
low_port = socket.getservbyname(ports[0])
except socket.error:
low_port = int(ports[0])
try:
high_port = socket.getservbyname(ports[-1])
except socket.error:
high_port = int(ports[-1])
if low_port == high_port:
return '%d' % low_port
else:
return '%d-%d' % (low_port, high_port)
示例2: testGetServBy
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',
'freebsd7', '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 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)
示例3: get_port
def get_port(p):
sport = p.sprintf("%TCP.sport%")
dport = p.sprintf("%TCP.dport%")
if not sport.isdigit():
sport = str(getservbyname(sport))
if not dport.isdigit():
dport = str(getservbyname(dport))
return sport, dport
示例4: turtle_client
def turtle_client(self):
s = socket.socket()
HOST = socket.gethostbyname("measerver")
PORT = socket.getservbyname("mea_srv")
print HOST
print PORT
#invoco el metodo connect del socket pasando como parametro la tupla IP , puerto
s.connect((HOST, PORT))
print "Turtle_com------->conectado a servidor."
message = str(self.img_mea)
print "Turtle_com----------->enviando mensaje a servidor:"
print message
s.send(message)
print "Turtle_com---------->esperando respuesta del servidor:"
recibido = s.recv(1024)
print "Turtle_com---------->recibido: "
print recibido
#cierro socket
s.close()
self.pub_Cult.publish(recibido)
return True
示例5: from_text
def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True):
address = tok.get_string()
protocol = tok.get_string()
if protocol.isdigit():
protocol = int(protocol)
else:
protocol = socket.getprotobyname(protocol)
bitmap = []
while 1:
(ttype, value) = tok.get()
if ttype == dnspython.tokenizer.EOL or ttype == dnspython.tokenizer.EOF:
break
if value.isdigit():
serv = int(value)
else:
if protocol != _proto_udp and protocol != _proto_tcp:
raise NotImplementedError, "protocol must be TCP or UDP"
if protocol == _proto_udp:
protocol_text = "udp"
else:
protocol_text = "tcp"
serv = socket.getservbyname(value, protocol_text)
i = serv // 8
l = len(bitmap)
if l < i + 1:
for j in xrange(l, i + 1):
bitmap.append('\x00')
bitmap[i] = chr(ord(bitmap[i]) | (0x80 >> (serv % 8)))
bitmap = dnspython.rdata._truncate_bitmap(bitmap)
return cls(rdclass, rdtype, address, protocol, bitmap)
示例6: __init__
def __init__(self, data, panda):
self.data = data
self.panda = panda
service = data[7].split("[")
#self.blinks = {}
print service[0]
try:
port = socket.getservbyname(service[0])
print port
except:
port = ""
if service[0] == "init":
col1 = self.panda.single_node.main_node.colorScaleInterval(1, (1, 1, 0, 0.7), (0.4, 0.2, 0.7, 0.4))
col2 = self.panda.single_node.main_node.colorScaleInterval(1, (0.4, 0.2, 0.7, 0.4), (1, 1, 0, 0.7))
col3 = self.panda.single_node.main_node.colorScaleInterval(5, (0.4, 0.2, 0.7, 0.4), (0.4, 0.2, 0.7, 0.4))
blink = Sequence(col1, col2, col3, name="blink")
#blink.loop()
for i in self.panda.single_node.services:
print ":" + str(i[0]) + ":" + str(port) + ":"
if str(i[0]) == str(port):
print "match"
self.panda.single_node.apps[i].setColorOff()
col1 = self.panda.single_node.apps[i].colorScaleInterval(1, (1, 1, 0, 1), (1, 0.4, 0.7, 1.0))
col2 = self.panda.single_node.apps[i].colorScaleInterval(1, (1, 0.4, 0.7, 1.0), (1, 1, 0, 1))
col3 = self.panda.single_node.apps[i].colorScaleInterval(2, (random.uniform(1,3), 0.4, 0.7, 1.0), (1, 0.4, 0.7, 1.0))
blink = Sequence(col1, col2, col3, name="blink")
#self.blinks[port].loop()
#looper = Parallel(name="looper")
try:
self.panda.single_node.looper.append(blink)
except:
pass
self.panda.single_node.looper.loop()
示例7: _get_storage_xml
def _get_storage_xml(params, ignore_source=False):
src_type = params.get('src_type')
disk = E.disk(type=src_type, device=params.get('type'))
disk.append(E.driver(name='qemu', type=params['format']))
disk.append(E.target(dev=params.get('dev'), bus=params['bus']))
if params.get('address'):
# ide disk target id is always '0'
disk.append(E.address(
type='drive', controller=params['address']['controller'],
bus=params['address']['bus'], target='0',
unit=params['address']['unit']))
if ignore_source:
return ET.tostring(disk)
# Working with url paths
if src_type == 'network':
output = urlparse.urlparse(params.get('path'))
host = E.host(name=output.hostname, port=
output.port or socket.getservbyname(output.scheme))
source = E.source(protocol=output.scheme, name=output.path)
source.append(host)
disk.append(source)
else:
# Fixing source attribute
source = E.source()
source.set(DEV_TYPE_SRC_ATTR_MAP[src_type], params.get('path'))
disk.append(source)
return ET.tostring(disk)
示例8: test
def test():
"""Test program for telnetlib.
Usage: python telnetlib.py [-d] ... [host [port]]
Default host is localhost; default port is 23.
"""
debuglevel = 0
while sys.argv[1:] and sys.argv[1] == '-d':
debuglevel = debuglevel+1
del sys.argv[1]
host = 'localhost'
if sys.argv[1:]:
host = sys.argv[1]
port = 0
if sys.argv[2:]:
portstr = sys.argv[2]
try:
port = int(portstr)
except ValueError:
port = socket.getservbyname(portstr, 'tcp')
tn = Telnet()
tn.set_debuglevel(debuglevel)
tn.open(host, port, timeout=0.5)
tn.interact()
tn.close()
示例9: buildOptions
def buildOptions(self, parser):
"""
Command-line options to be supported
"""
SMTP_PORT = 25
try:
SMTP_PORT = socket.getservbyname('smtp', 'tcp')
except socket.error:
pass
parser.add_option('--useFileDescriptor',
dest='useFileDescriptor',
default=-1,
type="int",
help="File descriptor to use for listening")
parser.add_option('--listenPort',
dest='listenPort',
default=SMTP_PORT,
type="int",
help="Alternative listen port to use (default %default)")
parser.add_option('--eventseverity',
dest='eventseverity',
default="2",
type="int",
help="Severity for events created")
parser.add_option('--listenip',
dest='listenip',
default='0.0.0.0',
help='IP address to listen on. Default is 0.0.0.0')
示例10: makeConnection
def makeConnection(transport):
nstHost = host
try:
try:
transport.connect(host, port)
except ValueError:
# Avoid ImportError: cannot import name dns
from untwisted import dns
nstHost = (yield dns.lookup(host)).answer[0].address
transport.connect(nstHost, port)
# tcp.Connector calls socket.getservbyname() but .connect() doesn't : (
except TypeError:
nstPort = socket.getservbyname(port, 'udp')
# Avoid RuntimeError: already connected
transport._connectedAddr = None
transport.connect(nstHost, nstPort)
raise StopIteration(transport)
示例11: passiveUDP
def passiveUDP(host, service, qlen=0, portbase=0):
'''
create and bind a UDP server socket
parametrs:
host: network interface the service to be bound
service: name (string) or port number (short) of service
qlen: queue length
portbase: a workaround for some privilege services, eg, echo,
a portbase of 7000 will shift echo service to port 7007 (7000+7)
(host, service) defines the server address
each call reuses the specified port number
'''
serv_name = str(service)
if '0' <= serv_name[:1] <= '9': # port # in integer
port = int(serv_name)
else: # resolve by service name
try:
port = socket.getservbyname(serv_name, 'udp')
except: # something wrong with port #
sys.exit('Format error in port number!\n')
port += portbase
msock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
msock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
msock.bind((host, port))
return msock
示例12: main
def main():
argc = len(sys.argv)
if argc < 3:
print("""
Usage : echo_server ipaddr port
""")
sys.exit()
ipaddr = sys.argv[1]
porttext = sys.argv[2]
#get port
try:
port = int(porttext)
except:
try:
port = socket.getservbyname(porttext)
except socket.gaierror :
print('port is illeagl')
sys.exit()
#get connection
try:
echo = EchoServer(ipaddr,port,10)
echo.run()
echo.close()
except KeyboardInterrupt:
print('server stop')
示例13: requestProcessor
def requestProcessor(self, request):
if self.include:
request_data = self.SEPARATOR % 'Request'
genHdr = []
try:
remadd = socket.gethostbyname(request.get_host()) + ':' + str(socket.getservbyname(request.get_type()))
except:
pass
else:
genHdr.append(('Remote Address', remadd))
genHdr.append(('Request Url', request.get_full_url()))
genHdr.append(('Request Method', request.get_method()))
# genHdr.append(('Status Code', str(request.getcode())))
for key, value in genHdr: request_data += '\n' + key + ': ' + str(value)
request_data += self.HEAD_SEP
request_headers = request.headers
for key, value in sorted(request_headers.items()): request_data += '\n' + key + ': ' + str(value)
if request.unredirected_hdrs:
request_data += self.HEAD_SEP
for key, value in request.unredirected_hdrs.items(): request_data += '\n' + key + ': ' + str(value)
self.log += request_data
if self.origReqMethod and self.origReqMethod not in ['GET', 'POST'] and self.errCode in [301,302,303]:
setattr(request, 'get_method', lambda: self.origReqMehod)
self.errCode = 0
return request
pass
示例14: find_service_name
def find_service_name():
protocolname = 'tcp'
try:
print ("service name: %s => port: %s" %(app_name, socket.getservbyname(app_name,'tcp')))
except Exception as err:
print (err)
示例15: get_disk_xml
def get_disk_xml(params):
"""
<disk type='file' device='cdrom'>
<driver name='qemu' type='raw'/>
[source XML according to src_type]
<target dev='%(dev)s' bus='%(bus)s'/>
<readonly/>
</disk>
"""
path = params['path']
disk_type = params.get('disk', None)
if disk_type is None:
disk_type = _get_disk_type(path) if len(path) > 0 else 'file'
disk = E.disk(type=disk_type, device=params['type'])
driver = E.driver(name='qemu', type=params['format'])
if params['type'] != 'cdrom':
driver.set('cache', 'none')
if params.get('pool_type') == "netfs":
driver.set("io", "native")
disk.append(driver)
# Get device name according to bus and index values
dev = params.get('dev', (BUS_TO_DEV_MAP[params['bus']] +
string.lowercase[params.get('index', 0)]))
disk.append(E.target(dev=dev, bus=params['bus']))
if params.get('address'):
# ide disk target id is always '0'
disk.append(E.address(
type='drive', controller=params['address']['controller'],
bus=params['address']['bus'], target='0',
unit=params['address']['unit']))
if len(params['path']) == 0:
return (dev, ET.tostring(disk, encoding='utf-8', pretty_print=True))
if disk_type == 'network':
"""
<source protocol='%(protocol)s' name='%(url_path)s'>
<host name='%(hostname)s' port='%(port)s'/>
</source>
"""
output = urlparse.urlparse(params['path'])
port = str(output.port or socket.getservbyname(output.scheme))
source = E.source(protocol=output.scheme, name=output.path)
source.append(E.host(name=output.hostname, port=port))
else:
"""
<source file='%(src)s' />
"""
source = E.source()
source.set(DEV_TYPE_SRC_ATTR_MAP[disk_type], params['path'])
disk.append(source)
return (dev, ET.tostring(disk, encoding='utf-8', pretty_print=True))