从应用程序重置TCP套接字连接 [英] Reset a TCP socket connection from application

查看:209
本文介绍了从应用程序重置TCP套接字连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Perl或C中使用IO :: Socket :: INET在应用程序级别重置accept套接字?

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

在TCP端口上有一个bindlisten程序,并且accept是一个客户端连接,之后它是readwrite的一些数据. 如果仅使用closeshutdown套接字,则TCP层会优雅地终止(使用FIN数据包),而不是生成RST数据包.

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.

推荐答案

您没有指定要使用的确切操作系统.我发现Linux确实有一个API调用,它将重置TCP连接,但我不知道它的可移植性.做到这一点的方法是在已连接的套接字上使用connect系统调用,但是这次使用家族AF_UNSPEC.

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.

以这种方式重置套接字后,甚至可以通过另一个connect调用再次连接该套接字.

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);
  }
}

这篇关于从应用程序重置TCP套接字连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆