本文整理汇总了Python中socket.inet_ntoa方法的典型用法代码示例。如果您正苦于以下问题:Python socket.inet_ntoa方法的具体用法?Python socket.inet_ntoa怎么用?Python socket.inet_ntoa使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类socket
的用法示例。
在下文中一共展示了socket.inet_ntoa方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: maxIpaddr
# 需要导入模块: import socket [as 别名]
# 或者: from socket import inet_ntoa [as 别名]
def maxIpaddr(ipaddr, netmask):
"""
Takes a quad dot format IP address string and makes it the largest valid value still in the same subnet.
Returns:
Max quad dot IP string or None if error
"""
try:
val = struct.unpack("!I", socket.inet_aton(ipaddr))[0]
nm = struct.unpack("!I", socket.inet_aton(netmask))[0]
inc = struct.unpack("!I", socket.inet_aton("0.0.0.254"))[0]
val &= nm
val |= inc
return socket.inet_ntoa(struct.pack('!I', val))
except Exception:
return None
示例2: findNonLoInterfaces
# 需要导入模块: import socket [as 别名]
# 或者: from socket import inet_ntoa [as 别名]
def findNonLoInterfaces(data, endianness):
lines = stripTimestamps(data)
candidates = filter(lambda l: l.startswith("__inet_insert_ifa"), lines) # logs for the inconfig process
if debug:
print("Candidate ifaces: %r" % candidates)
result = []
if endianness == "eb":
fmt = ">I"
elif endianness == "el":
fmt = "<I"
for c in candidates:
g = re.match(r"^__inet_insert_ifa\[[^\]]+\]: device:([^ ]+) ifa:0x([0-9a-f]+)", c)
if g:
(iface, addr) = g.groups()
addr = socket.inet_ntoa(struct.pack(fmt, int(addr, 16)))
if addr != "127.0.0.1" and addr != "0.0.0.0":
result.append((iface, addr))
return result
示例3: getLocalip
# 需要导入模块: import socket [as 别名]
# 或者: from socket import inet_ntoa [as 别名]
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]
示例4: get_ip_address
# 需要导入模块: import socket [as 别名]
# 或者: from socket import inet_ntoa [as 别名]
def get_ip_address(ifname):
"""
Get the ip address from the specified interface.
>>> get_ip_address('eth0')
'192.168.0.7'
@type ifname: string
@param ifname: The interface name. Typical names are C{'eth0'},
C{'wlan0'}, etc.
@rtype: string
@return: The IP address of the specified interface.
"""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15]))[20:24])
示例5: negotiate_socks
# 需要导入模块: import socket [as 别名]
# 或者: from socket import inet_ntoa [as 别名]
def negotiate_socks(sock, host, port):
"""
Negotiate with a socks4a server. Closes the socket and raises an exception on
failure.
:param socket sock: socket connected to socks4a server
:param str host: hostname/IP to connect to
:param int port: port to connect to
:raises: :class:`stem.ProtocolError` if the socks server doesn't grant our request
:returns: a list with the IP address and the port that the proxy connected to
"""
# SOCKS4a request here - http://en.wikipedia.org/wiki/SOCKS#Protocol
request = b'\x04\x01' + struct.pack('!H', port) + b'\x00\x00\x00\x01' + b'\x00' + stem.util.str_tools._to_bytes(host) + b'\x00'
sock.sendall(request)
response = sock.recv(8)
if len(response) != 8 or response[0:2] != b'\x00\x5a':
sock.close()
raise stem.ProtocolError(ERROR_MSG.get(response[1], 'SOCKS server returned unrecognized error code'))
return [socket.inet_ntoa(response[4:]), struct.unpack('!H', response[2:4])[0]]
示例6: bin2ip
# 需要导入模块: import socket [as 别名]
# 或者: from socket import inet_ntoa [as 别名]
def bin2ip(ipval):
"""Converts a 16-bytes binary blob to an IPv4 or IPv6 standard
representation. See ip2bin().
"""
try:
socket.inet_aton(ipval)
return ipval
except (TypeError, socket.error):
pass
try:
socket.inet_pton(socket.AF_INET6, ipval)
return ipval
except (TypeError, socket.error):
pass
try:
return int2ip(ipval)
except TypeError:
pass
if ipval[:12] == b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff':
return socket.inet_ntoa(ipval[12:])
return socket.inet_ntop(socket.AF_INET6, ipval)
示例7: local_ip4_addr_list
# 需要导入模块: import socket [as 别名]
# 或者: from socket import inet_ntoa [as 别名]
def local_ip4_addr_list():
"""Return a set of IPv4 address
"""
assert os.name != 'nt', 'Do not support Windows rpc yet.'
nic = set()
for if_nidx in socket.if_nameindex():
name = if_nidx[1]
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
ip_of_ni = fcntl.ioctl(sock.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', name[:15].encode("UTF-8")))
except OSError as e:
if e.errno == 99: # EADDRNOTAVAIL
print("Warning!",
"Interface: {}".format(name),
"IP address not available for interface.",
sep='\n')
continue
else:
raise e
ip_addr = socket.inet_ntoa(ip_of_ni[20:24])
nic.add(ip_addr)
return nic
示例8: getSubnet
# 需要导入模块: import socket [as 别名]
# 或者: from socket import inet_ntoa [as 别名]
def getSubnet(ipaddr, netmask):
try:
val1 = struct.unpack("!I", socket.inet_aton(ipaddr))[0]
nm = struct.unpack("!I", socket.inet_aton(netmask))[0]
res = val1 & nm
return socket.inet_ntoa(struct.pack('!I', res))
except Exception:
return None
示例9: setValue
# 需要导入模块: import socket [as 别名]
# 或者: from socket import inet_ntoa [as 别名]
def setValue(self, settings, e):
if e.index == 1:
self.logicalName = _GXCommon.toLogicalName(e.value)
elif e.index == 2:
if isinstance(e.value, str):
self.dataLinkLayerReference = e.value
else:
self.dataLinkLayerReference = _GXCommon.toLogicalName(e.value)
elif e.index == 3:
self.ipAddress = socket.inet_ntoa(struct.pack("!I", e.value))
elif e.index == 4:
self.multicastIPAddress = []
if e.value:
for it in e.value:
self.multicastIPAddress.append(socket.inet_ntoa(struct.pack("!I", it)))
elif e.index == 5:
self.ipOptions = []
if e.value:
for it in e.value:
item = GXDLMSIp4SetupIpOption()
item.type_ = it[0]
item.length = it[1]
item.data = it[2]
self.ipOptions.append(item)
elif e.index == 6:
self.subnetMask = socket.inet_ntoa(struct.pack("!I", e.value))
elif e.index == 7:
self.gatewayIPAddress = socket.inet_ntoa(struct.pack("!I", e.value))
elif e.index == 8:
self.useDHCP = e.value
elif e.index == 9:
self.primaryDNSAddress = socket.inet_ntoa(struct.pack("!I", e.value))
elif e.index == 10:
self.secondaryDNSAddress = socket.inet_ntoa(struct.pack("!I", e.value))
else:
e.error = ErrorCode.READ_WRITE_DENIED
示例10: parse_arp_packet
# 需要导入模块: import socket [as 别名]
# 或者: from socket import inet_ntoa [as 别名]
def parse_arp_packet(packet):
arp_detailed = struct.unpack("2s2s1s1s2s6s4s6s4s", packet)
arp_packet = {"htype": arp_detailed[0],
"ptype": arp_detailed[1],
"hlen": arp_detailed[2],
"plen": arp_detailed[3],
"oper": arp_detailed[4],
"src_mac": ':'.join('%02x' % ord(b) for b in arp_detailed[5]),
"src_ip": socket.inet_ntoa(arp_detailed[6]),
"dst_mac": ':'.join('%02x' % ord(b) for b in arp_detailed[7]),
"dst_ip": socket.inet_ntoa(arp_detailed[8])}
return arp_packet
示例11: long_to_ip
# 需要导入模块: import socket [as 别名]
# 或者: from socket import inet_ntoa [as 别名]
def long_to_ip(ip):
return socket.inet_ntoa(struct.pack('!L', ip))
示例12: lin_set_ip_address
# 需要导入模块: import socket [as 别名]
# 或者: from socket import inet_ntoa [as 别名]
def lin_set_ip_address(self, dev, ip, serverip, netmask):
sockfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# set IP
ifr = struct.pack('<16sH2s4s8s', dev, socket.AF_INET, "\x00"*2, socket.inet_aton(ip), "\x00"*8)
fcntl.ioctl(sockfd, self.IOCTL_LINUX_SIOCSIFADDR, ifr)
# get flags
ifr = struct.pack('<16sh', dev, 0)
flags = struct.unpack('<16sh', fcntl.ioctl(sockfd, self.IOCTL_LINUX_SIOCSIFFLAGS, ifr))[1]
# set new flags
flags = flags | self.IOCTL_LINUX_IFF_UP
ifr = struct.pack('<16sh', dev, flags)
# iface up
fcntl.ioctl(sockfd, self.IOCTL_LINUX_SIOCSIFFLAGS, ifr)
except Exception as e:
common.internal_print("Something went wrong with setting up the interface.", -1)
print(e)
sys.exit(-1)
# adding new route for forwarding packets properly.
integer_ip = struct.unpack(">I", socket.inet_pton(socket.AF_INET, serverip))[0]
rangeip = socket.inet_ntop(socket.AF_INET, struct.pack(">I", integer_ip & ((2**int(netmask))-1)<<32-int(netmask)))
integer_netmask = struct.pack(">I", ((2**int(netmask))-1)<<32-int(netmask))
netmask = socket.inet_ntoa(integer_netmask)
ps = subprocess.Popen(["route", "add", "-net", rangeip, "netmask", netmask, "dev", dev], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = ps.communicate()
if stderr:
if not "File exists" in stderr:
common.internal_print("Error: adding client route: {0}".format(stderr), -1)
sys.exit(-1)
return
示例13: get_ipaddress
# 需要导入模块: import socket [as 别名]
# 或者: from socket import inet_ntoa [as 别名]
def get_ipaddress(self):
# get's the IP address in a human readable format
ip_address = self['ip_address'].get_value()
if self['type'].get_value() == IpAddrType.MOVE_DST_IPADDR_V4:
return socket.inet_ntoa(ip_address)
else:
addr = binascii.hexlify(ip_address).decode('utf-8')
return ":".join([addr[i:i + 4] for i in range(0, len(addr), 4)])
示例14: get_ipaddress
# 需要导入模块: import socket [as 别名]
# 或者: from socket import inet_ntoa [as 别名]
def get_ipaddress(self):
addr_bytes = self['ipv4_address'].get_value()
return socket.inet_ntoa(addr_bytes)
示例15: incIpaddr
# 需要导入模块: import socket [as 别名]
# 或者: from socket import inet_ntoa [as 别名]
def incIpaddr(ipaddr, inc=1):
"""
Takes a quad dot format IP address string and adds the @inc value to it by converting it to a number.
Returns:
Incremented quad dot IP string or None if error
"""
try:
val = struct.unpack("!I", socket.inet_aton(ipaddr))[0]
val += inc
return socket.inet_ntoa(struct.pack('!I', val))
except Exception:
return None