0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

C言語 close()でRST送信する

Last updated at Posted at 2022-05-17

0.概要

C言語実装において、ネットワークソケットに対してclose()をコールすると通常FINが発行されるが、TCPコネクションがTIME_WAITになって処理が遅いなどRSTで強制切断したい場合がある。

1.方法

ソケットに対して、ソケットオプションSOL_SOCKET, SO_LINGERを設定する。
linger on, タイムアウト値0にするとRSTが送信される。

int force_close(int sock)
{
	int ret = 0;
	struct linger ling;

	memset(&ling, 0, sizeof(ling));
	ling.l_onoff = 1;  /* 0以外でon, 0でoff */
	ling.l_linger = 0; /* 0で即時切断。0以外は指定時間(秒)でタイムアウト */

	ret = setsockopt(sock, SOL_SOCKET, SO_LINGER, &ling, sizeof(ling));
	if(ret != 0) {
		printf("setsockopt:%s\n", strerror(errno));
	}
	ret = close(sock);

	return ret;
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?