对于UDP套接字,当close()返回时,ip地址是否无限制?

The*_*eer 6 c sockets port binding bind

在阅读这个很棒的答案时,我了解到TCP套接字可以具有一个名为的状态TIME_WAIT.由于该状态,即使close(int fd)函数返回 ,TCP套接字也可能没有释放它已绑定到的地址0.

鉴于UDP是无连接的,并且它没有像TCP那样提供数据的可靠性要求,可以安全地假设一旦close(int fd)返回0,地址是未绑定的吗?

use*_*028 6

是的,根据源代码https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/tree/net/ipv4/udp.c?id=refs/tags/v3.19 -rc6,udp_destroy_sock()(〜第2028行)刷新任何挂起的帧,并释放释放该地址的套接字.

您可以通过一个简单的示例来演示这一点 你需要netcat一个客户端和一个服务器.一个服务器,运行此代码:

#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <string.h>
int main() {
    struct sockaddr_in me;
    int sock;

    if ((sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
        perror("socket error:");
        return -1;
        }
    memset(&me, 0, sizeof(me));
    me.sin_family = AF_INET;
    me.sin_port = htons(60000);
    me.sin_addr.s_addr = htonl(INADDR_ANY);
    if (bind(sock, (struct sockaddr*)&me, sizeof(me)) == -1) {
        perror("bind error: ");
        return -1;
        }

    printf("On client execute:\n");
    printf("      nc -u {servers ip address} 60000\n\n");
    printf("type: hello world<enter>\n");
    printf("Hit enter when you've done this...");
    getchar();

    printf("\nNow check the input queue on this server\n");
    printf("    netstat -an|grep 60000\n");
    printf("Notice that we have buffered data we have not read\n");
    printf("(probably about 360 bytes)\n");
    printf("Hit enter to continue...");
    getchar();

    printf("\nI'm going to end. After I do, run netstat -an again\n");
    printf("and you'll notice port 60000 is gone.\n\n");
    printf("Re-run this program on server again and see you\n");
    printf("have no problem re-acquiring the UDP port.\n");
    return 0;
    }
Run Code Online (Sandbox Code Playgroud)