python网络编程(socket ) ipv6/ipv4服务端

540次阅读
没有评论
  1. IPV4服务端
    import socket
    import subprocess

ip_addr = (‘127.0.0.1’, 8000)
tcp_server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
tcp_server.bind(ip_addr)
tcp_server.listen(5)
while True:
conn, addr = tcp_server.accept()
while True:
cmd = conn.recv(1024)
if not cmd:
break

    if cmd.decode('utf-8') == 'quit':
        break

    print(cmd.decode('utf-8'))
    res = subprocess.Popen(cmd.decode('utf-8'), shell=True, 
                           stdout=subprocess.PIPE, stdin=subprocess.PIPE, 
                           stderr=subprocess.PIPE)
    err = res.stderr.read()
    out = res.stdout.read()
    print(bool(res))

    if err:
        ref = err
    elif not out:
        ref = b'12'

    else:
        ref = out

    conn.send(ref)
conn.close()

tcp_server.close()

  1. IPV6服务端
    import socket
    import subprocess

ipv6 = ‘ff15:7079:7468:6f6e:6465:6d6f:6d63:6173%eth0’
port = 8090

addrinfo = socket.getaddrinfo(ipv6, port, 0, 0)[0]
tcp_server = socket.socket(socket.AF_INET6,socket.SOCK_STREAM)
tcp_server.bind(addrinfo[-1])

tcp_server.listen(5)
while True:
conn, addr = tcp_server.accept()

while True:
    cmd = conn.recv(1024)
    if not cmd:
        break

    if cmd.decode('utf-8') == 'quit':
        break

    print(cmd.decode('utf-8'))
    res = subprocess.Popen(cmd.decode('utf-8'), shell=True, stdout=subprocess.PIPE,
                           stdin =subprocess.PIPE, stderr=subprocess.PIPE)

    err = res.stderr.read()
    out = res.stdout.read()
    print(bool(res))

    if err:
        ref = err
    elif not out:
        ref = b'12'

    else:
        ref = out
    conn.send(ref)
conn.close()

tcp_server.close()
Linux/VMware环境下使用创建ipv6socket除了::1或者::0外,其他的需要绑定对应ipv6的端口号,不然会报错Cannot assign requested address

正文完
可以使用微信扫码关注公众号(ID:xzluomor)
post-qrcode
 
评论(没有评论)