本文整理汇总了Python中socket.getservbyname函数的典型用法代码示例。如果您正苦于以下问题:Python getservbyname函数的具体用法?Python getservbyname怎么用?Python getservbyname使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了getservbyname函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
开发者ID:Dean-Christian-Armada,项目名称:django,代码行数:33,代码来源:utils.py
示例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)
开发者ID:249550148,项目名称:gevent,代码行数:35,代码来源:test_socket.py
示例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
开发者ID:pyinx,项目名称:scripts,代码行数:8,代码来源:zookeeper-parse.py
示例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
开发者ID:mikelval1982,项目名称:turtlebot_ros,代码行数:25,代码来源:Turtle_com_03.py
示例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)
开发者ID:jwestbury,项目名称:spawncamper,代码行数:30,代码来源:WKS.py
示例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()
开发者ID:dgou,项目名称:gibson,代码行数:34,代码来源:node.py
示例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)
开发者ID:k0da,项目名称:kimchi,代码行数:31,代码来源:vmstorages.py
示例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()
开发者ID:ChowZenki,项目名称:kbengine,代码行数:27,代码来源:telnetlib.py
示例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')
开发者ID:SteelHouseLabs,项目名称:zenoss-prodbin,代码行数:29,代码来源:zenmail.py
示例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)
开发者ID:jablko,项目名称:untwisted,代码行数:26,代码来源:udp.py
示例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
开发者ID:liujay,项目名称:PyNetPG,代码行数:25,代码来源:Server_sock.py
示例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')
开发者ID:wpc062,项目名称:exercises,代码行数:25,代码来源:echo_server2.py
示例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
开发者ID:agmontesb,项目名称:kodiaddonide,代码行数:28,代码来源:network.py
示例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)
开发者ID:networkshb,项目名称:network_tools,代码行数:7,代码来源:get_service_name.py
示例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))
开发者ID:Drooids,项目名称:kimchi,代码行数:60,代码来源:disk.py
示例16: getIp
def getIp():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = socket.getservbyname('http', 'tcp')
s.connect(('www.baidu.com', port))
ip = s.getsockname()[0]
s.close()
return ip
开发者ID:zx013,项目名称:other,代码行数:7,代码来源:tools.py
示例17: test
def test():
import sys, string, socket, select
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 = string.atoi(portstr)
except string.atoi_error:
port = socket.getservbyname(portstr, 'tcp')
tn = Telnet(host, port)
tn.set_debuglevel(debuglevel)
while 1:
rfd, wfd, xfd = select.select([tn, sys.stdin], [], [])
if sys.stdin in rfd:
line = sys.stdin.readline()
tn.write(line)
if tn in rfd:
try:
text = tn.read_eager()
except EOFError:
print '*** Connection closed by remote host ***'
break
if text:
sys.stdout.write(text)
sys.stdout.flush()
tn.close()
开发者ID:asottile,项目名称:ancient-pythons,代码行数:33,代码来源:telnetlib.py
示例18: main
def main():
server = pbs.pbs_default()
c = pbs.pbs_connect(server)
nodes = pbs.pbs_statnode(c, '', 'NULL', 'NULL')
for node in nodes:
print node.name, ' :'
attrs = node.attribs
for attr in attrs:
print '\t%s = %s' %(attr.name, attr.value)
try:
mom_port = socket.getservbyname('pbs_resmon', 'tcp')
except socket.error:
mom_port = pbs.PBS_MANAGER_SERVICE_PORT
mom_id = pbs.openrm(node.name, mom_port)
mom_keys = pbs.get_mom_values(mom_id)
for key in mom_keys.keys():
print '\t%s = %s' %(key, mom_keys[key])
print '\nTesting list with user supplied keywords'
l = [ 'bas', 'ncpus', 'loadave' ]
mom_keys = pbs.get_mom_values(mom_id, l)
for key in mom_keys.keys():
print '\t%s = %s' %(key, mom_keys[key])
print ''
pbs.closerm(mom_id)
开发者ID:FRidh,项目名称:pbs_python,代码行数:31,代码来源:resmom_info.py
示例19: create_new_vm
def create_new_vm(vmdef):
image = cache.get_image(name=vmdef['image'])
image = copy.deepcopy(image)
vm = ravello.update_luids(image)
vm['name'] = vmdef['name']
vm['customVmConfigurationData'] = { 'keypair': env.public_key }
vm['hostname'] = [ vmdef['name'] ]
vm['numCpus'] = vmdef['smp']
vm['memorySize'] = { 'unit': 'MB', 'value': vmdef['memory'] }
vm.setdefault('suppliedServices', [])
for svcdef in vmdef.get('services', []):
if isinstance(svcdef, int):
port = str(svcdef)
svcdef = 'port-{0}'.format(svcdef)
else:
port = socket.getservbyname(svcdef)
svc = { 'globalService': True, 'id': ravello.random_luid(),
'ip': None, 'name': svcdef, 'portRange': port,
'protocol': 'ANY_OVER_TCP' }
vm['suppliedServices'].append({'baseService': svc})
# Set a fixed Mac. This way applications created from blueprints
# created from these VMs will have the same Mac.
# See also https://github.com/ravello/testmill/issues/15
conn = vm['networkConnections'][0]
conn['device']['mac'] = get_new_mac()
conn['device']['useAutomaticMac'] = False
return vm
开发者ID:ravello,项目名称:testmill,代码行数:27,代码来源:application.py
示例20: __init__
def __init__(self, host, port, factory, timeout, bindAddress, reactor=None):
self.host = host
if isinstance(port, types.StringTypes):
try:
port = socket.getservbyname(port, 'tcp')
except socket.error, e:
raise error.ServiceNameUnknownError(string="%s (%r)" % (e, port))
开发者ID:AndyPanda95,项目名称:python-for-android,代码行数:7,代码来源:tcp.py
注:本文中的socket.getservbyname函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论