本文整理匯總了Python中socket.AF_INET屬性的典型用法代碼示例。如果您正苦於以下問題:Python socket.AF_INET屬性的具體用法?Python socket.AF_INET怎麽用?Python socket.AF_INET使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在類socket
的用法示例。
在下文中一共展示了socket.AF_INET屬性的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: stop
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AF_INET [as 別名]
def stop(self):
self._stop = True
if self.threads:
for t in self.threads:
t.stop()
# not so nice solution to get rid of the block of listen()
# unfortunately close() does not help on the block
try:
server_socket = self.sctp.sctpsocket_tcp(socket.AF_INET)
if self.config.get("Global", "serverbind") == "0.0.0.0":
server_socket.connect(("127.0.0.1", int(self.config.get(self.get_module_configname(), "serverport"))))
else:
server_socket.connect((self.config.get("Global", "serverbind"), int(self.config.get(self.get_module_configname(), "serverport"))))
except:
pass
return
示例2: check
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AF_INET [as 別名]
def check(self):
try:
common.internal_print("Checking module on server: {0}".format(self.get_module_name()))
server_socket = self.sctp.sctpsocket_tcp(socket.AF_INET)
server_socket.settimeout(3)
server_socket.connect((self.config.get("Global", "remoteserverip"), int(self.config.get(self.get_module_configname(), "serverport"))))
client_fake_thread = SCTP_generic_thread(0, 0, None, None, server_socket, None, self.authentication, self.encryption_module, self.verbosity, self.config, self.get_module_name())
client_fake_thread.do_check()
client_fake_thread.communication(True)
self.cleanup(server_socket)
except socket.timeout:
common.internal_print("Checking failed: {0}".format(self.get_module_name()), -1)
self.cleanup(server_socket)
except socket.error as exception:
if exception.args[0] == 111:
common.internal_print("Checking failed: {0}".format(self.get_module_name()), -1)
else:
common.internal_print("Connection error: {0}".format(self.get_module_name()), -1)
self.cleanup(server_socket)
return
示例3: freebsd_tun_alloc
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AF_INET [as 別名]
def freebsd_tun_alloc(self, dev, flags):
try:
sockfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ifr = struct.pack('<16si', 'tun', 0)
self.iface_name = fcntl.ioctl(sockfd, self.IOCTL_FREEBSD_SIOCIFCREATE2, ifr)
self.iface_name = self.iface_name.rstrip("\x00")
buff = array.array('c', dev+"\x00")
caddr_t, _ = buff.buffer_info()
ifr = struct.pack('16sP', self.iface_name, caddr_t);
fcntl.ioctl(sockfd, self.IOCTL_FREEBSD_SIOCSIFNAME, ifr)
tun = os.open("/dev/"+self.iface_name, os.O_RDWR | os.O_NONBLOCK)
self.iface_name = dev
except IOError as e:
print e
common.internal_print("Error: Cannot create tunnel. Is {0} in use?".format(dev), -1)
sys.exit(-1)
return tun
示例4: __init__
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AF_INET [as 別名]
def __init__(self, addr: Union[str, tuple, socket.socket]):
"""
Args:
addr: can be /var/run/usbmuxd or (localhost, 27015)
"""
self._sock = None
if isinstance(addr, socket.socket):
self._sock = addr
return
if isinstance(addr, str):
if not os.path.exists(addr):
raise MuxError("socket unix:{} unable to connect".format(addr))
family = socket.AF_UNIX
else:
family = socket.AF_INET
self._sock = socket.socket(family, socket.SOCK_STREAM)
self._sock.connect(addr)
示例5: Create
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AF_INET [as 別名]
def Create(asyncSocketsPool, srvAddr, srvBacklog=256, bufSlots=None) :
try :
srvSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except :
raise XAsyncTCPServerException('Create : Cannot open socket (no enought memory).')
try :
srvSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srvSocket.bind(srvAddr)
srvSocket.listen(srvBacklog)
except :
raise XAsyncTCPServerException('Create : Error to binding the TCP server on this address.')
if not bufSlots :
bufSlots = XBufferSlots(256, 4096, keepAlloc=True)
xAsyncTCPServer = XAsyncTCPServer( asyncSocketsPool,
srvSocket,
srvAddr,
bufSlots )
asyncSocketsPool.NotifyNextReadyForReading(xAsyncTCPServer, True)
return xAsyncTCPServer
# ------------------------------------------------------------------------
示例6: __init__
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AF_INET [as 別名]
def __init__(self, laddress, data_callback, family = None, o = None):
if o == None:
if family == None:
if laddress != None and laddress[0].startswith('['):
family = socket.AF_INET6
laddress = (laddress[0][1:-1], laddress[1])
else:
family = socket.AF_INET
self.family = family
self.laddress = laddress
self.data_callback = data_callback
else:
self.laddress, self.data_callback, self.family, self.nworkers, self.flags, \
self.ploss_out_rate, self.pdelay_out_max, self.ploss_in_rate, \
self.pdelay_in_max = o.laddress, o.data_callback, o.family, \
o.nworkers, o.flags, o.ploss_out_rate, o.pdelay_out_max, o.ploss_in_rate, \
o.pdelay_in_max
示例7: bind_socket
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AF_INET [as 別名]
def bind_socket(host: str, port: int, *, backlog=100) -> socket.socket:
"""Create TCP server socket.
:param host: IPv4, IPv6 or hostname may be specified
:param port: TCP port number
:param backlog: Maximum number of connections to queue
:return: socket.socket object
"""
try: # IP address: family must be specified for IPv6 at least
ip = ip_address(host)
host = str(ip)
sock = socket.socket(
socket.AF_INET6 if ip.version == 6 else socket.AF_INET
)
except ValueError: # Hostname, may become AF_INET or AF_INET6
sock = socket.socket()
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((host, port))
sock.listen(backlog)
return sock
示例8: server
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AF_INET [as 別名]
def server(args):
berny = get_berny(args)
host, port = args.socket
server = socket(AF_INET, SOCK_STREAM)
server.bind((host, int(port)))
server.listen(0)
while True:
sock, addr = server.accept()
f = sock.makefile('r+')
geom = handler(berny, f)
if geom:
f.write(geom.dumps(args.format))
f.flush()
f.close()
sock.close()
if not geom:
break
示例9: is_ipaddress
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AF_INET [as 別名]
def is_ipaddress(hostname):
"""Detects whether the hostname given is an IP address.
:param str hostname: Hostname to examine.
:return: True if the hostname is an IP address, False otherwise.
"""
if six.PY3 and isinstance(hostname, bytes):
# IDN A-label bytes are ASCII compatible.
hostname = hostname.decode('ascii')
families = [socket.AF_INET]
if hasattr(socket, 'AF_INET6'):
families.append(socket.AF_INET6)
for af in families:
try:
inet_pton(af, hostname)
except (socket.error, ValueError, OSError):
pass
else:
return True
return False
示例10: kernel_route_dst_prefix_str
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AF_INET [as 別名]
def kernel_route_dst_prefix_str(route):
dst = route.get_attr('RTA_DST')
if dst is None:
family = route["family"]
if family == socket.AF_INET:
prefix_str = "0.0.0.0/0"
elif family == socket.AF_INET6:
prefix_str = "::/0"
else:
prefix_str = "Default"
else:
prefix_str = dst
dst_len = route["dst_len"]
if dst_len is not None:
prefix_str += "/" + str(dst_len)
return prefix_str
示例11: log_tx_protocol_packet
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AF_INET [as 別名]
def log_tx_protocol_packet(self, level, sock, prelude, packet_info):
if not self._tx_log.isEnabledFor(level):
return
if sock.family == socket.AF_INET:
fam_str = "IPv4"
from_str = "from {}:{}".format(sock.getsockname()[0], sock.getsockname()[1])
to_str = "to {}:{}".format(sock.getpeername()[0], sock.getpeername()[1])
else:
assert sock.family == socket.AF_INET6
fam_str = "IPv6"
from_str = "from [{}]:{}".format(sock.getsockname()[0], sock.getsockname()[1])
to_str = "to [{}]:{}".format(sock.getpeername()[0], sock.getpeername()[1])
type_str = self.protocol_packet_type(packet_info.protocol_packet)
packet_str = str(packet_info)
self._tx_log.log(level, "[%s] %s %s %s %s %s %s" %
(self._log_id, prelude, fam_str, type_str, from_str, to_str, packet_str))
示例12: __init__
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AF_INET [as 別名]
def __init__( self ):
"""Initialize variables and setup server"""
HOST = ""
PORT = 5000
self.board = []
self.currentPlayer = 0
self.turnCondition = threading.Condition()
self.gameBeginEvent = threading.Event()
for i in range( 9 ):
self.board.append( None )
# setup server socket
self.server = socket.socket( socket.AF_INET,
socket.SOCK_STREAM )
self.server.bind( ( HOST, PORT ) )
self.display( "Server awaiting connections..." )
示例13: _do_dns_lookup
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AF_INET [as 別名]
def _do_dns_lookup(hostname: str, port: int) -> str:
try:
addr_infos = socket.getaddrinfo(hostname, port, socket.AF_UNSPEC, socket.IPPROTO_IP)
except (socket.gaierror, IndexError, ConnectionError):
raise ServerHostnameCouldNotBeResolved(f"Could not resolve {hostname}")
family, socktype, proto, canonname, sockaddr = addr_infos[0]
# By default use the first DNS entry, IPv4 or IPv6
tentative_ip_addr = sockaddr[0]
# But try to use IPv4 if we have both IPv4 and IPv6 addresses, to work around buggy networks
for family, socktype, proto, canonname, sockaddr in addr_infos:
if family == socket.AF_INET:
tentative_ip_addr = sockaddr[0]
return tentative_ip_addr
示例14: __init__
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AF_INET [as 別名]
def __init__(self, stream, address, protocol):
self.address = address
# Save the socket's address family now so we know how to
# interpret self.address even after the stream is closed
# and its socket attribute replaced with None.
if stream.socket is not None:
self.address_family = stream.socket.family
else:
self.address_family = None
# In HTTPServerRequest we want an IP, not a full socket address.
if (self.address_family in (socket.AF_INET, socket.AF_INET6) and
address is not None):
self.remote_ip = address[0]
else:
# Unix (or other) socket; fake the remote address.
self.remote_ip = '0.0.0.0'
if protocol:
self.protocol = protocol
elif isinstance(stream, iostream.SSLIOStream):
self.protocol = "https"
else:
self.protocol = "http"
self._orig_remote_ip = self.remote_ip
self._orig_protocol = self.protocol
示例15: _new_socket
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AF_INET [as 別名]
def _new_socket(self):
transport_socket = socketlib.socket(
socketlib.AF_INET, socketlib.SOCK_STREAM
)
if self.certfile and self.cafile and self.keyfile:
context = ssl.create_default_context(
ssl.Purpose.SERVER_AUTH, cafile=self.cafile
)
context.check_hostname = False
context.load_cert_chain(
certfile=self.certfile,
keyfile=self.keyfile,
password=self.password,
)
sock = context.wrap_socket(transport_socket, server_side=False)
else:
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
sock = context.wrap_socket(transport_socket)
sock.settimeout(self._timeout)
return sock