The ultimate SO_LINGER page, or: why is my tcp not reliable

本文深入探讨了TCP协议在传输未知大小数据时可能遇到的问题,并详细解释了为何有时数据无法完全到达接收方。通过分析SO_LINGER选项及shutdown系统调用的作用,文章提供了确保数据可靠传输的有效解决方案。
部署运行你感兴趣的模型镜像

This post is about an obscure corner of TCP network programming, a corner where almost everybody doesn’t quite get what is going on. I used to think I understood it, but found out last week that I didn’t.

So I decided to trawl the web and consult the experts, promising them to write up their wisdom once and for all, in hopes that this subject can be put to rest.

The experts (H. Willstrand, Evgeniy Polyakov, Bill Fink, Ilpo Jarvinen, and Herbert Xu) responded, and here is my write-up.

Even though I refer a lot to the Linux TCP implementation, the issue described is not Linux-specific, and can occur on any operating system.

What is the issue?

Sometimes, we have to send an unknown amount of data from one location to another. TCP, the reliable Transmission Control Protocol, sounds like it is exactly what we need. From the Linux tcp(7) manpage:

“TCP provides a reliable, stream-oriented, full-duplex connection between two sockets on top of ip(7), for both v4 and v6 versions. TCP guarantees that the data arrives in order and retransmits lost packets. It generates and checks a per-packet checksum to catch transmission errors.”

However, when we naively use TCP to just send the data we need to transmit, it often fails to do what we want - with the final kilobytes or sometimes megabytes of data transmitted never arriving.

Let’s say we run the following two programs on two POSIX compliant operating systems, with the intention of sending 1 million bytes from program A to program B (programs can be found here):

A:

   
      sock = socket(AF_INET, SOCK_STREAM, 0);  
      connect(sock, &remote, sizeof(remote));
      write(sock, buffer, 1000000);             // returns 1000000
      close(sock);

B:

    int sock = socket(AF_INET, SOCK_STREAM, 0);
    bind(sock, &local, sizeof(local));
    listen(sock, 128);
    int client=accept(sock, &local, locallen);
    write(client, "220 Welcome\r\n", 13);

    int bytesRead=0, res;
    for(;;) {
        res = read(client, buffer, 4096);
        if(res < 0)  {
            perror("read");
            exit(1);
        }
        if(!res)
            break;
        bytesRead += res;
    }
    printf("%d\n", bytesRead);

Quiz question - what will program B print on completion?

A) 1000000
B) something less than 1000000
C) it will exit reporting an error
D) could be any of the above

The right answer, sadly, is ‘D’. But how could this happen? Program A reported that all data had been sent correctly!

What is going on

Sending data over a TCP socket really does not offer the same ‘it hit the disk’ semantics as writing to a normal file does (if you remember to call fsync()).

In fact, all a successful write() in the TCP world means is that the kernel has accepted your data, and will now try to transmit it in its own sweet time. Even when the kernel feels that the packets carrying your data have been sent, in reality, they’ve only been handed off to the network adapter, which might actually even send the packets when it feels like it.

From that point on, the data will traverse many such adapters and queues over the network, until it arrives at the remote host. The kernel there will acknowledge the data on receipt, and if the process that owns the socket is actually paying attention and trying to read from it, the data will finally have arrived at the application, and in filesystem speak, ‘hit the disk’.

Note that the acknowledgment sent out only means the kernel saw the data - it does not mean the application did!

OK, I get all that, but why didn’t all data arrive in the example above?

When we issue a close() on a TCP/IP socket, depending on the circumstances, the kernel may do exactly that: close down the socket, and with it the TCP/IP connection that goes with it.

And this does in fact happen - even though some of your data was still waiting to be sent, or had been sent but not acknowledged: the kernel can close the whole connection.

This issue has led to a large number of postings on mailing lists, Usenet and fora, and these all quickly zero in on the SO_LINGER socket option, which appears to have been written with just this issue in mind:

When enabled, a close(2) or shutdown(2) will not return until all queued messages for the socket have been successfully sent or the linger timeout has been reached. Otherwise, the call returns immediately and the closing is done in the background. When the socket is closed as part of exit(2), it always lingers in the background.

So, we set this option, rerun our program. And it still does not work, not all our million bytes arrive.

How come?

It turns out that in this case, section 4.2.2.13 of RFC 1122 tells us that a close() with any pending readable data could lead to an immediate reset being sent.

A host MAY implement a ‘half-duplex’ TCP close sequence, so that an application that has called CLOSE cannot continue to read data from the connection. If such a host issues a CLOSE call while received data is still pending in TCP, or if new data is received after CLOSE is called, its TCP SHOULD send a RST to show that data was lost.

And in our case, we have such data pending: the “220 Welcome\r\n” we transmitted in program B, but never read in program A!

If that line has not been sent by program B, it is most likely that all our data would have arrived correctly.

So, if we read that data first, and LINGER, are we good to go?

Not really. The close() call really does not convey what we are trying to tell the kernel: please close the connection after sending all the data I submitted through write().

Luckily, the system call shutdown() is available, which tells the kernel exactly this. However, it alone is not enough. When shutdown() returns, we still have no indication that everything was received by program B.

What we can do however is issue a shutdown(), which will lead to a FIN packet being sent to program B. Program B in turn will close down its socket, and we can detect this from program A: a subsequent read() will return 0.

Program A now becomes:

    sock = socket(AF_INET, SOCK_STREAM, 0);  
    connect(sock, &remote, sizeof(remote));
    write(sock, buffer, 1000000);             // returns 1000000
    shutdown(sock, SHUT_WR);
    for(;;) {
        res=read(sock, buffer, 4000);
        if(res < 0) {
            perror("reading");
            exit(1);
        }
        if(!res)
            break;
    }
    close(sock);

So is this perfection?

Well.. If we look at the HTTP protocol, there data is usually sent with length information included, either at the beginning of an HTTP response, or in the course of transmitting information (so called ‘chunked’ mode).

And they do this for a reason. Only in this way can the receiving end be sure it received all information that it was sent.

Using the shutdown() technique above really only tells us that the remote closed the connection. It does not actually guarantee that all data was received correctly by program B.

The best advice is to send length information, and to have the remote program actively acknowledge that all data was received.

This only works if you have the ability to choose your own protocol, of course.

What else can be done?

If you need to deliver streaming data to a ‘stupid TCP/IP hole in the wall’, as I’ve had to do a number of times, it may be impossible to follow the sage advice above about sending length information, and getting acknowledgments.

In such cases, it may not be good enough to accept the closing of the receiving side of the socket as an indication that everything arrived.

Luckily, it turns out that Linux keeps track of the amount of unacknowledged data, which can be queried using the SIOCOUTQ ioctl(). Once we see this number hit 0, we can be reasonably sure our data reached at least the remote operating system.

Unlike the shutdown() technique described above, SIOCOUTQ appears to be Linux-specific. Updates for other operating systems are welcome.

The sample code contains an example of how to use SIOCOUTQ.

But how come it ‘just worked’ lots of times!

As long as you have no unread pending data, the star and moon are aligned correctly, your operating system is of a certain version, you may remain blissfully unimpacted by the story above, and things will quite often ‘just work’. But don’t count on it.

Some notes on non-blocking sockets

Volumes of communications have been devoted the the intricacies of SO_LINGER versus non-blocking (O_NONBLOCK) sockets. From what I can tell, the final word is: don’t do it. Rely on the shutdown()-followed-by-read()-eof technique instead. Using the appropriate calls to poll/epoll/select(), of course.

A few words on the Linux sendfile() and splice() system calls

It should also be noted that the Linux system calls sendfile() and splice() hit a spot in between - these usually manage to deliver the contents of the file to be sent, even if you immediately call close() after they return.

This has to do with the fact that splice() (on which sendfile() is based) can only safely return after all packets have hit the TCP stack since it is zero copy, and can’t very well change its behaviour if you modify a file after the call returns!

Please note that the functions do not wait until all the data has been acknowledged, it only waits until it has been sent.

From:

http://blog.netherlabs.nl/articles/2009/01/18/the-ultimate-so_linger-page-or-why-is-my-tcp-not-reliable

您可能感兴趣的与本文相关的镜像

Stable-Diffusion-3.5

Stable-Diffusion-3.5

图片生成
Stable-Diffusion

Stable Diffusion 3.5 (SD 3.5) 是由 Stability AI 推出的新一代文本到图像生成模型,相比 3.0 版本,它提升了图像质量、运行速度和硬件效率

【无人机】基于改进粒子群算法的无人机路径规划研究[和遗传算法、粒子群算法进行比较](Matlab代码实现)内容概要:本文围绕基于改进粒子群算法的无人机路径规划展开研究,重点探讨了在复杂环境中利用改进粒子群算法(PSO)实现无人机三维路径规划的方法,并将其与遗传算法(GA)、标准粒子群算法等传统优化算法进行对比分析。研究内容涵盖路径规划的多目标优化、避障策略、航路点约束以及算法收敛性和寻优能力的评估,所有实验均通过Matlab代码实现,提供了完整的仿真验证流程。文章还提到了多种智能优化算法在无人机路径规划中的应用比较,突出了改进PSO在收敛速度和全局寻优方面的优势。; 适合人群:具备一定Matlab编程基础和优化算法知识的研究生、科研人员及从事无人机路径规划、智能优化算法研究的相关技术人员。; 使用场景及目标:①用于无人机在复杂地形或动态环境下的三维路径规划仿真研究;②比较不同智能优化算法(如PSO、GA、蚁群算法、RRT等)在路径规划中的性能差异;③为多目标优化问题提供算法选型和改进思路。; 阅读建议:建议读者结合文中提供的Matlab代码进行实践操作,重点关注算法的参数设置、适应度函数设计及路径约束处理方式,同时可参考文中提到的多种算法对比思路,拓展到其他智能优化算法的研究与改进中。
<think>我们正在讨论C#中的Socket选项SO_LINGER。根据提供的引用,SO_LINGER选项用于控制当调用close(或closesocket)时系统的行为,特别是在有数据待发送时是否延迟关闭以完成传输。 在C#中,我们可以通过Socket.SetSocketOption方法来设置SO_LINGER。该选项需要一个LingerOption结构体(在命名空间System.Net.Sockets中)。 引用[1]和[2]介绍了SO_LINGER的基本概念:它通过一个结构体指定,包括一个开关(l_onoff)和一个延迟时间(l_linger,单位为秒)。 - 当l_onoff为0(或false)时,关闭SO_LINGER选项,采用默认行为:close立即返回,但系统会尝试发送剩余数据(在后台)。 - 当l_onoff非零(或true)时,开启SO_LINGER,并设置l_linger的值。这意味着: 如果l_linger为0:则close将立即终止连接,丢弃未发送的数据,并发送RST(复位)给对端,这称为“硬中止”。 如果l_linger大于0:则close将阻塞(或延迟)直到数据发送完成或超时(延迟时间为l_linger秒)。如果超时则放弃发送,close返回。 引用[3]和[4]提供了代码示例,展示了如何设置SO_LINGER来中止连接(即设置l_onoff=true, l_linger=0)。 在C#中,我们有专门的LingerOption类来表示这个选项。 具体步骤: 1. 创建一个LingerOption对象,构造函数的第一个参数是是否启用(enable),第二个参数是延迟时间(秒)。 2. 使用Socket.SetSocketOption设置选项,参数为: - optionLevel: SocketOptionLevel.Socket (因为SO_LINGERSocket级别的选项) - optionName: SocketOptionName.Linger - optionValue: 上面创建的LingerOption对象 注意事项: - 在设置SO_LINGER时,尤其是在设置l_linger=0来立即中止连接时,要小心,因为这会丢弃未发送的数据,可能导致接收方无法收到完整数据。 - 在非阻塞套接字上,即使设置了SO_LINGER,close也可能立即返回,然后系统在后台处理发送和关闭。但是,如果设置了SO_LINGER且超时时间为0,则close会立即中止连接并返回。 - 在C#中,设置SO_LINGER会影响Socket.Close()方法的行为。 示例代码(C#): 使用SO_LINGER并设置延迟时间为0(即立即中止): Socket socket = ...; // 已经建立连接的socket // 设置SO_LINGER,enable为true,等待时间为0秒 socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, 0)); socket.Close(); // 此时将立即中止连接 如果要启用SO_LINGER并等待最多10秒: socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, 10)); socket.Close(); // 会阻塞直到数据发送完成或10秒超时 如果要关闭SO_LINGER(使用默认行为): // 注意:LingerOption的构造函数第一个参数为false,第二个参数忽略(通常设为0) socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(false, 0)); // 或者,也可以直接设置LingerOption(false,任意值),因为当启用为false时,时间值被忽略 引用[5]提到了一篇博客,但我们可以参考《UNIX Network Programming》中的经典描述来理解其行为。 重要:在C#中,当你调用Close()方法时,如果设置了SO_LINGER并且等待时间大于0,那么Close()方法可能会阻塞当前线程直到等待时间结束。因此,在图形界面应用程序中,如果在主线程中这样操作,可能会导致界面冻结。在这种情况下,建议在单独的线程中关闭socket或使用异步方法,或者考虑使用非阻塞模式。 另外,需要注意的是,在设置SO_LINGER选项后,对Close()的调用行为会改变。所以,根据应用程序的需求,合理设置SO_LINGER。 总结:SO_LINGER选项用于控制关闭连接时如何处理未发送的数据。在C#中,通过Socket.SetSocketOption方法设置LingerOption结构来配置此选项。 参考文献: [^1], [^2], [^3], [^4], [^5] 提供了关于SO_LINGER的基本概念和用法。 </think>### C# 中 Socket 使用 `SO_LINGER` 的详解 #### 一、`SO_LINGER` 的作用 `SO_LINGER` 是 Socket 选项,用于控制调用 `Close()` 方法时的关闭行为: 1. **默认行为** 调用 `Close()` 后立即返回,操作系统在后台尝试发送剩余数据(可能丢失数据)。 2. **启用 `SO_LINGER`** - 确保数据发送完成或超时后才关闭连接。 - 避免数据丢失,但可能阻塞线程。 #### 二、关键参数(`LingerOption` 结构体) ```csharp public class LingerOption { public bool Enabled { get; set; } // 对应 l_onoff(true=启用) public int LingerTime { get; set; } // 对应 l_linger(延迟时间,秒) } ``` | 参数组合 | 行为 | |----------|------| | `Enabled=false` | 立即关闭(默认行为),不保证数据发送完成[^1] | | `Enabled=true, LingerTime=0` | **强制中止连接**:丢弃未发送数据,发送 RST 复位包[^3][^4] | | `Enabled=true, LingerTime>0` | 阻塞等待数据发送,超时后强制关闭[^2] | #### 三、C# 中的使用方法 ```csharp using System.Net.Sockets; Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // ...(连接操作) // 设置 SO_LINGER(示例:等待 5 秒) LingerOption linger = new LingerOption(enable: true, seconds: 5); socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, linger); // 关闭连接 socket.Close(); // 此处可能阻塞最多 5 秒 ``` #### 四、典型应用场景 1. **强制中止连接** ```csharp socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, 0)); // 立即中止[^4] ``` 2. **确保数据完整性** ```csharp socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, 10)); // 等待 10 秒 ``` #### 五、注意事项 1. **线程阻塞风险** 当 `LingerTime > 0` 时,`Close()` 会阻塞当前线程,UI 线程中需谨慎使用[^2]。 2. **资源释放** 即使启用 `SO_LINGER`,仍需手动关闭 Socket: ```csharp using (Socket socket = new Socket(...)) { // ...设置 SO_LINGER... } // 自动调用 Close() ``` 3. **与非阻塞模式冲突** 在非阻塞模式下设置 `SO_LINGER` 可能导致未定义行为[^2]。 4. **与 `Shutdown()` 的配合** 最佳实践:先调用 `Shutdown(SocketShutdown.Both)` 停止收发,再关闭连接[^5]。 #### 六、底层机制 - **TCP 协议层**:启用后,关闭流程遵循 `FIN → ACK` 四次挥手过程。 - **超时控制**:若数据在 `LingerTime` 内未发送完毕,连接将被强制终止[^1][^2]。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值