本文整理汇总了Python中socket.inet_ntop函数的典型用法代码示例。如果您正苦于以下问题:Python inet_ntop函数的具体用法?Python inet_ntop怎么用?Python inet_ntop使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了inet_ntop函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _ParseProcIgmp
def _ParseProcIgmp(self):
"""Returns a list of current IGMP group memberships.
/proc/net/igmp uses an unusual format:
Idx Device : Count Querier Group Users Timer Reporter
1 lo : 1 V3
010000E0 1 0:00000000 0
2 eth0 : 1 V3
010000E0 1 0:00000000 0
010000E0 is the IP multicast address as a hex number, and always
big endian.
"""
igmps = set()
with open(PROCNETIGMP, 'r') as f:
for line in f:
result = IGMPREGEX.match(line)
if result is not None:
igmp = result.group(1).strip()
igmps.add(socket.inet_ntop(
socket.AF_INET, struct.pack('<L', int(igmp, 16))))
with open(PROCNETIGMP6, 'r') as f:
for line in f:
result = IGMP6REGEX.match(line)
if result is not None:
igmp = result.group(1).strip()
ip6 = ':'.join([igmp[0:4], igmp[4:8], igmp[8:12], igmp[12:16],
igmp[16:20], igmp[20:24], igmp[24:28], igmp[28:]])
igmps.add(socket.inet_ntop(socket.AF_INET6,
socket.inet_pton(socket.AF_INET6, ip6)))
return list(igmps)
示例2: send_pcapbreak
def send_pcapbreak(pkt, stopped):
if stopped.isSet():
return
iph, tcph, tcpo, payload = parse_headers(pkt)
ipdst_str = socket.inet_ntop(socket.AF_INET, struct.pack('!L', iph.dstaddr))
ipsrc_str = socket.inet_ntop(socket.AF_INET, struct.pack('!L', iph.srcaddr))
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
s.bind(('',tcph.srcport))
s.setsockopt(socket.IPPROTO_IP, socket.IP_TTL, 1)
except (socket.error, socket.gaierror):
print "Warn: cannot operate sending packets to break pcap loop"
return
retry = 0.4
for i in range(0, 5):
s.sendto("*", (ipdst_str, PCAP_BREAK_DPORT))
stopped.wait(retry)
if stopped.isSet():
break
retry *= 2
s.close()
# if stopped.isSet() is False:
# print "Warn: break packet is not handled"
return
示例3: ping_node
def ping_node(self, node):
task = self.taskman.new_task()
msgout = codec_pb2.MsgDHTMisc()
msgout.request_id = task.task_id
if len(node.ip) == 4:
node_ip = socket.inet_ntop(socket.AF_INET, node.ip)
else:
node_ip = socket.inet_ntop(socket.AF_INET6, node.ip)
addr_tup = (node_ip, node.port)
task.addr = addr_tup
task.msg_start = msgout
# clamp to "1s ... (rtt * 10) ... 15s" range
min_timeout = datetime.timedelta(seconds=1)
max_timeout = datetime.timedelta(seconds=15)
if node.rtt is None:
task.timeout = max_timeout
else:
task.timeout = node.rtt * 10
if task.timeout > max_timeout:
task.timeout = max_timeout
if task.timeout < min_timeout:
task.timeout = min_timeout
task.timeout_actor = ping_node_timeout
task.timeout_args = [self, node]
self.send_message("ping", msgout, addr_tup)
示例4: extractRecord
def extractRecord(resolver, name, answers, level=10):
if not level:
return None
if hasattr(socket, 'inet_ntop'):
for r in answers:
if r.name == name and r.type == dns.A6:
return socket.inet_ntop(socket.AF_INET6, r.payload.address)
for r in answers:
if r.name == name and r.type == dns.AAAA:
return socket.inet_ntop(socket.AF_INET6, r.payload.address)
for r in answers:
if r.name == name and r.type == dns.A:
return socket.inet_ntop(socket.AF_INET, r.payload.address)
for r in answers:
if r.name == name and r.type == dns.CNAME:
result = extractRecord(
resolver, r.payload.name, answers, level - 1)
if not result:
return resolver.getHostByName(
str(r.payload.name), effort=level - 1)
return result
# No answers, but maybe there's a hint at who we should be asking about
# this
for r in answers:
if r.type == dns.NS:
from twisted.names import client
r = client.Resolver(servers=[(str(r.payload.name), dns.PORT)])
return r.lookupAddress(str(name)
).addCallback(
lambda records: extractRecord(
r, name,
records[_ANS] + records[_AUTH] + records[_ADD],
level - 1))
示例5: printResponse
def printResponse(self, message):
if message.HasField('response'):
response = message.response
policystr = ''
if response.HasField('appliedPolicy') and response.appliedPolicy:
policystr = ', Applied policy: ' + response.appliedPolicy
tagsstr = ''
if response.tags:
tagsstr = ', Tags: ' + ','.join(response.tags)
rrscount = len(response.rrs)
print("- Response Code: %d, RRs: %d%s%s" % (response.rcode,
rrscount,
policystr,
tagsstr))
for rr in response.rrs:
rrclass = 1
rdatastr = ''
if rr.HasField('class'):
rrclass = getattr(rr, 'class')
rrtype = rr.type
if (rrclass == 1 or rrclass == 255) and rr.HasField('rdata'):
if rrtype == 1:
rdatastr = socket.inet_ntop(socket.AF_INET, rr.rdata)
elif rrtype == 28:
rdatastr = socket.inet_ntop(socket.AF_INET6, rr.rdata)
print("\t - %d, %d, %s, %d, %s" % (rrclass,
rrtype,
rr.name,
rr.ttl,
rdatastr))
示例6: unpack_host
def unpack_host(host):
#fp=open("host.txt",'w+b')
#fp.write(host+"\n")
if len(host) == 4:
return socket.inet_ntop(socket.AF_INET, host)
elif len(host) == 16:
return socket.inet_ntop(socket.AF_INET6, host)
示例7: routes
def routes ():
links = {}
for ifi in Link.getLinks():
links[ifi.index] = ifi.attributes.get(Link.Type.Attribute.IFLA_IFNAME).strip('\0')
print('Kernel IP routing table')
print('%-18s %-18s %-18s %-7s %s' % ('Destination','Genmask','Gateway','Metric','Iface'))
for route in Network.getRoutes():
if route.family != socket.AF_INET:
continue
if route.type not in (Network.Type.Type.RTN_LOCAL,Network.Type.Type.RTN_UNICAST):
continue
if route.src_len == 32:
continue
destination = route.attributes.get(Network.Type.Attribute.RTA_DST)
gateway = route.attributes.get(Network.Type.Attribute.RTA_GATEWAY)
oif = ord(route.attributes.get(Network.Type.Attribute.RTA_OIF)[0])
metric = ord(route.attributes.get(Network.Type.Attribute.RTA_PRIORITY,'\0')[0])
dst = '%s' % socket.inet_ntop(route.family, destination) if destination else ''
gw = '%s' % socket.inet_ntop(route.family, gateway) if gateway else '0.0.0.0'
mask = NetMask.CIDR[route.src_len]
iface = links[oif]
print('%-18s %-18s %-18s %-7d %-s' % (dst or '0.0.0.0',mask,gw,metric,iface))
示例8: data_received
def data_received(self, data):
if self.state == self.INIT:
assert data[0] == 0x05
# server -> client. VER | METHOD
self.transport.write(pack('!BB', 0x05, 0x00)) # no auth
self.state = self.HOST
elif self.state == self.HOST:
# socks request info. VER | CMD | RSV | ATYP | SDT.ADDR | DST.PORT
ver, cmd, rsv, atype = data[:4]
assert ver == 0x05 and cmd == 0x01
if atype == 3: # domain
length = data[4]
hostname, nxt = data[5:5 + length], 5 + length
elif atype == 1: # ipv4
hostname, nxt = socket.inet_ntop(socket.AF_INET, data[4:8]), 8
elif atype == 4: # ipv6
hostname, nxt = socket.inet_ntop(socket.AF_INET6, data[4:20]), 20
else:
logging.warn('addr_type not suport')
return
port = unpack('!H', data[nxt:nxt + 2])[0]
logging.info('request connect to {}:{}'.format(hostname, port))
# 连接proxyserver
asyncio.ensure_future(self.connect(hostname, port))
self.state = self.DATA
elif self.state == self.DATA:
self.client_transport.write(data)
示例9: from_bytes
def from_bytes(cls, b):
services, host, port = struct.unpack('>Q16sH', b)
if host.startswith(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF'):
host = socket.inet_ntop(socket.AF_INET, host[-4:])
else:
host = socket.inet_ntop(socket.AF_INET6, host)
return cls(services, host, port)
示例10: read_address
def read_address(self, fd):
""" read a warts-style ip/mac address """
length = WartsReader.read_uint8_t(self.fd)
addr = 0
typ = 0
# an embedded (non-referenced) address
if length != 0:
typ = WartsReader.read_uint8_t(fd)
addr = self.fd.read(length)
addr_id = len(self.address_ref)
self.address_ref[addr_id] = addr
# a referenced address
else:
addr_id = WartsReader.read_uint32_t(fd)
try:
addr = self.address_ref[addr_id]
except:
print "Die: couldn't find referenced address %d" % addr_id
sys.exit(-1)
if typ == 0:
if len(addr) == 4: typ = 1
if len(addr) == 16: typ = 2
if typ == 1:
return socket.inet_ntop(socket.AF_INET, addr)
elif typ == 2:
return socket.inet_ntop(socket.AF_INET6, addr)
else:
print "Addr type:", typ, "not implemented"
assert False
示例11: ParseBmpPeerUp
def ParseBmpPeerUp(message, peer_flags, verbose=False):
"""Parse a BMP V3 Peer Up message.
Args:
header: array containing BMP peer up message.
peer_flags: from the per-peer header.
verbose: be chatty, or not.
Returns:
A list of strings to print.
Raises:
ValueError: an unexpected value was found in the message
"""
indent_str = indent.IndentLevel(indent.BMP_CONTENT_INDENT)
print_msg = []
offset = 0
if peer_flags & PEER_FLAG_IPV6:
loc_addr = socket.inet_ntop(socket.AF_INET6, message[offset : offset + 16])
else:
loc_addr = socket.inet_ntop(socket.AF_INET, message[offset + 12 : offset + 16])
offset += 16
loc_port, rem_port = struct.unpack_from(">HH", message, offset)
print_msg.append("%sloc_addr %s, loc_port %d, rem_port %d\n" % (indent_str, loc_addr, loc_port, rem_port))
return print_msg
示例12: show_dns
def show_dns(self, family):
if (family == socket.AF_INET):
ip_cfg = self.get_ip4_config()
else:
ip_cfg = self.get_ip6_config()
if ip_cfg is None:
print("None")
return
if (family == socket.AF_INET):
print ("Domains: %s") % (ip_cfg.get_domains())
print ("Searches: %s") % (ip_cfg.get_searches())
print("Nameservers:")
nameservers = ip_cfg.get_nameservers()
for dns in nameservers:
print socket.inet_ntop(family, struct.pack("=I", dns))
else:
print ("Domains: %s") % (ip_cfg.get_domains())
print ("Searches: %s") % (ip_cfg.get_searches())
print("Nameservers:")
num = ip_cfg.get_num_nameservers()
for i in range(0,num):
dns = ip_cfg.get_nameserver(i)
print socket.inet_ntop(family, dns)
示例13: show_routes
def show_routes(self, family):
if (family == socket.AF_INET):
ip_cfg = self.get_ip4_config()
else:
ip_cfg = self.get_ip6_config()
if ip_cfg is None:
print("None")
return
nm_routes = ip_cfg.get_routes()
if len(nm_routes) == 0:
print("None")
return
for nm_route in nm_routes:
dest = nm_route.get_dest()
prefix = nm_route.get_prefix()
next_hop = nm_route.get_next_hop()
metric = nm_route.get_metric()
if (family == socket.AF_INET):
dest_struct = struct.pack("=I", dest)
next_hop_struct = struct.pack("=I", next_hop)
else:
dest_struct = dest
next_hop_struct = next_hop
print("%s/%d %s %d") % (socket.inet_ntop(family, dest_struct),
prefix,
socket.inet_ntop(family, next_hop_struct),
metric)
示例14: show_addresses
def show_addresses(self, family):
if (family == socket.AF_INET):
ip_cfg = self.get_ip4_config()
else:
ip_cfg = self.get_ip6_config()
if ip_cfg is None:
print("None")
return
nm_addresses = ip_cfg.get_addresses()
if len(nm_addresses) == 0:
print("None")
return
for nm_address in nm_addresses:
addr = nm_address.get_address()
prefix = nm_address.get_prefix()
gateway = nm_address.get_gateway()
if (family == socket.AF_INET):
addr_struct = struct.pack("=I", addr)
gateway_struct = struct.pack("=I", gateway)
else:
addr_struct = addr
gateway_struct = gateway
print("%s/%d %s") % (socket.inet_ntop(family, addr_struct),
prefix,
socket.inet_ntop(family, gateway_struct))
示例15: get_random_cidr
def get_random_cidr(mask=None, af='v4'):
''' Generate a random subnet based on netmask and address family '''
if not is_valid_af(af=af):
raise ValueError("Address family not supported %s" % af)
if mask is None:
mask = SUBNET_MASK[af]['default']
if type(mask) is int:
mask = str(mask)
if not is_valid_subnet_mask(plen=mask, af=af):
raise ValueError("Invalid subnet mask %s for af %s" % (mask, af))
while (True):
if af == 'v6':
min = 0x2001000000000000
max = 0x3fffffffffffffff
address = socket.inet_ntop(socket.AF_INET6,
struct.pack('>2Q',
random.randint(min, max),
random.randint(0, 2 ** 64)))
elif af == 'v4':
address = socket.inet_ntop(socket.AF_INET,
struct.pack('>I',
random.randint(2 ** 24, 2 ** 32)))
if is_reserved_address(address):
continue
if is_valid_address(address):
return '%s/%s' % (str(IPNetwork(address + '/' + mask).network), mask)