Search code examples
socketstcpshutdownfclose

Reset a TCP socket connection from application


How to reset an accepted socket in application level either with IO::Socket::INET in perl or in C?

There is a programm binding, listening on a TCP port, and accepts a client connection, after that it reads and writes some data. If I simply close or shutdown the socket, TCP layer gracefully terminates (with FIN packet), rather than, I'd generate an RST packet.


Solution

  • You didn't specify the exact OS you are using. I found that Linux does have an API call which will reset a TCP connection, I have no idea how portable it is. The way to do it is to use the connect system call on the already connected socket but this time with family AF_UNSPEC.

    After you have reset a socket that way it is even possible to connect the socket again with another connect call.

    int main(int argc, char** argv)
    {
      int fd = socket(AF_INET6, SOCK_STREAM, 0);
    
      while (1) {
        struct sockaddr_in6 sockaddr = {
          .sin6_family = AF_INET6,
          .sin6_port = htons(80),
          .sin6_flowinfo = 0,
          .sin6_scope_id = 0,
        };
        struct timespec s = {
          .tv_sec = 2,
          .tv_nsec = 0,
        };
    
        /* Connect to port 80 on localhost */
        inet_pton(AF_INET6, "::1", &sockaddr.sin6_addr.s6_addr);
        connect(fd, (struct sockaddr*)&sockaddr,sizeof(sockaddr));
        nanosleep(&s, NULL);
    
        /* Reset previously connected socket */
        sockaddr.sin6_family = AF_UNSPEC;
        connect(fd, (struct sockaddr*)&sockaddr,sizeof(sockaddr));
        nanosleep(&s, NULL);
      }
    }