简体   繁体   中英

Why is there TCP RST packet after sending a string and closing a socket

I try to use python socket to send char Y and after enter But when I capture wireshark i detect it error. Why? The code in python:

import socket
import re

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = (('pwnable.kr', 9009))
sock.connect((server_address))
b=sock.recv(2048)    # I must use 2 sock.recv then recv full text 
print b
b=sock.recv(2048)
print b
b=re.findall("Y/N",b)
print b
#sock.recv(1024)
if b[0]=="Y/N":
    print "OK"
    sock.send(("Y"+"\r\n").encode())
    b=sock.recv(1024)

Wireshark capture: 在此输入图像描述 How to send string and then enter? Using multiple sock.recv affect anything?


UPDATE1: I want print last b, it should is

Enter 1 to Begin the Greatest Game Ever Played.
Enter 2 to See a Complete Listing of Rules.
Enter 3 to Exit Game. (Not Recommended)
Choice: 

But i receive null list. My code:

import socket
import re

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)   
server_address = (('pwnable.kr', 9009))  
sock.connect((server_address))
b=sock.recv(2048)
print b
b=sock.recv(2048)
print b
b=re.findall("Y/N",b)
print b
#sock.recv(1024)
if b[0]=="Y/N":
    print "OK"
    sock.send(("Y"+"\r\n").encode())
    b=sock.recv(1024)
    print b
sock.close()    

In wireshark have red line: 在此输入图像描述

What's happening here?

Orderly TCP shutdown looks like this:

  • This side sends FIN meaning "I have nothing more to send".
  • The other side responds ACK meaning "OK, got all your data". From this point, reading from the socket on the other side will return empty (meaning "end of file").
  • The other side decides it has nothing more to say, sends FIN meaning "I have nothing more to send".
  • This side sends ACK meaning "OK, got all your data".
  • Now both sides can close the file descriptor.

But socket.close does not do orderly shutdown. It sends FIN , waits for an ACK , then it closes the descriptor. From this point, any TCP packet to this port will result in a RST response meaning "No such connection".

The red line is just a marker for TCP RST packet.

How to avoid the RST packet?

Assuming the remote side eventually closes the connection after its recv returns empty (0 bytes available), you can avoid the RST by doing:

sock.shutdown(socket.SHUT_WR)
buf = sock.recv(1)
if not buf:
  # Remote side sent FIN.
  sock.close()
# else: more data to handle, should recv again, until it returns empty

This way your side will handle everything the other side wants to send and only close once the other side says FIN .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM