hexdump(b,step,sep,decimal) 和 server、client 端 [北极星]

server端 代码

import socket
HOST=""
PORT=50007
with socket.socket(socket.AF_INET,socket.SOCK_STREAM) as s:
s.bind((HOST,PORT))
s.listen(1)
while True:
conn, addr = s.accept()
with conn:
print("Connected by", addr)
while True:
data = conn.recv(1024)
if not data: break
conn.sendall(data)
conn.shutdown(socket.SHUT_RDWR)
conn.close()
************************************************************************

client端 代码
import socket
HOST="localhost"
PORT=50007
with socket.socket(socket.AF_INET,socket.SOCK_STREAM) as s:
s.connect((HOST,PORT))
data=b"Hello, Python"
s.sendall(data)
data2=s.recv(1024)
print("Received",repr(data2))
************************************************************************

字节流转换16进制代码
def hexdump(b,step=16,sep=4,decimal=False):
    for i in range(0, len(b), step):
sub = b[i:i + step]
output = "%08x" % i
output += " %08d" % i if decimal else ""
output += " | "

temp = " ".join(["%02x" % c for c in sub])
temp += " " * (step - len(sub))
output += " ".join([temp[j:j + sep * 3] for j in range(0, len(temp), sep * 3)])

output += " | "
output += "".join([chr(c) if 0x20 <= c < 0x7F else "." for c in sub])

print(output)

text=b"I Love You, My Friend!"
hexdump(text,8,4,True)
------------------------------------------------------------------------------------------

00000000 00000000 | 49 20 4c 6f 76 65 20 59 | I Love Y
00000008 00000008 | 6f 75 2c 20 4d 79 20 46 | ou, My F
00000010 00000016 | 72 69 65 6e 64 21          | riend!

posted on 2019-02-24 17:56  梦中醒来  阅读(297)  评论(0编辑  收藏  举报

导航