Python 3.x Python3:从套接字读取线路时由对等方重置连接
运行此python3脚本时,我收到一条由对等方重置连接的Python 3.x Python3:从套接字读取线路时由对等方重置连接,python-3.x,sockets,Python 3.x,Sockets,运行此python3脚本时,我收到一条由对等方重置连接的错误消息: import struct, socket HOST = "127.0.0.1" PORT = 64012 # read bytes from socket and return it as ascii representation def read_line_from_socket(s): buf= "" while True: byteData =
错误消息:
import struct, socket
HOST = "127.0.0.1"
PORT = 64012
# read bytes from socket and return it as ascii representation
def read_line_from_socket(s):
buf= ""
while True:
byteData = s.recv(1)
if byteData == b"\n":
break
buf += byteData.decode("ascii")
return buf
def read_four_longs_for_addition(s):
sum = 0
counter = 1
while counter <= 4:
sum += struct.unpack("I", s.recv(4))[0]
counter += 1 # python does not support ++, += 1 has to be used
print(sum) # sum overflows int (number > 32 bit)
return sum
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST,PORT))
print(read_line_from_socket(s))
print(read_line_from_socket(s))
s.send(struct.pack("l", read_four_longs_for_addition(s)))
# print(s.recv(32)) # receives "You have succes..", NOT resulting in an Connection reset by peer which indicates success
print(read_line_from_socket(s)) # results in "Connection reset by peer"
s.close()
查看带有strace python3 nameOfPythonScript.py
的流程,我看不出任何问题,一切都应该正常工作:
recvfrom(3, "n", 1, 0, NULL, NULL) = 1
recvfrom(3, "e", 1, 0, NULL, NULL) = 1
recvfrom(3, "!", 1, 0, NULL, NULL) = 1
recvfrom(3, "\n", 1, 0, NULL, NULL) = 1
write(1, "You have successfully passed thi"..., 52You have successfully passed this level, well done!
) = 52
close(3) = 0
rt_sigaction(SIGINT, {sa_handler=SIG_DFL, sa_mask=[], sa_flags=SA_RESTORER, sa_restorer=0x7ffff7bcd0c0}, {sa_handler=0x5555557d8980, sa_mask=[], sa_flags=SA_RESTORER, sa_restorer=0x7ffff7bcd0c0}, 8) = 0
munmap(0x7ffff6c0e000, 262144) = 0
exit_group(0) = ?
+++ exited with 0 +++
我的问题:
为什么会发生连接重置?它是否与返回0有关代码>在服务器程序代码中?请注意,如果我recv
一个固定的字节数,而不是尝试读取完整的最后一行,则不会发生错误(请参阅脚本代码中的注释)
Welcome to phoenix/net-two, brought to you by https://exploit.education
For this level, sizeof(long) == 4, keep that in mind :)
9057758327
Traceback (most recent call last):
File "net-2.py", line 31, in <module>
print(read_line_from_socket(s))
File "net-2.py", line 10, in read_line_from_socket
byteData = s.recv(1)
ConnectionResetError: [Errno 104] Connection reset by peer
recvfrom(3, "n", 1, 0, NULL, NULL) = 1
recvfrom(3, "e", 1, 0, NULL, NULL) = 1
recvfrom(3, "!", 1, 0, NULL, NULL) = 1
recvfrom(3, "\n", 1, 0, NULL, NULL) = 1
write(1, "You have successfully passed thi"..., 52You have successfully passed this level, well done!
) = 52
close(3) = 0
rt_sigaction(SIGINT, {sa_handler=SIG_DFL, sa_mask=[], sa_flags=SA_RESTORER, sa_restorer=0x7ffff7bcd0c0}, {sa_handler=0x5555557d8980, sa_mask=[], sa_flags=SA_RESTORER, sa_restorer=0x7ffff7bcd0c0}, 8) = 0
munmap(0x7ffff6c0e000, 262144) = 0
exit_group(0) = ?
+++ exited with 0 +++