而重新套接字绑定错误 [英] Bind error while recreating socket

查看:153
本文介绍了而重新套接字绑定错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个有以下监听套接字:

A have the following listener socket:

int sd = socket(PF_INET, SOCK_STREAM, 0);

struct sockaddr_in addr;
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(http_port);
addr.sin_addr.s_addr = INADDR_ANY;

if(bind(sd,(sockaddr*)&addr,sizeof(addr))!=0)
{
    ...
}

if (listen(sd, 16)!=0)
{
    ...
}

int sent = 0;
for(;;) {
    int client = accept(sd, (sockaddr*)&addr, (socklen_t*)&size);
    if (client > 0)
    {
        ...
        close(client);
    }
}

如果一个用

close(sd);

,然后试图重新插座相同code,A绑定错误发生,30〜60秒一个新的socket创建成功后才能。

and then trying to recreate socket with the same code, a bind error happens, and only after 30-60 second a new socket is created successfully.

这有什么办法可以创建或接近一些很酷的方式,以避免绑定错误?

It there a way to create or close in some cool way to avoid bind error?

推荐答案

某处在内核中,还是有你的previous插座周围挂着一些信息。告诉你愿意内核反正重新使用的端口:

Somewhere in the kernel, there's still some information about your previous socket hanging around. Tell the kernel that you are willing to re-use the port anyway:

int yes=1;
//char yes='1'; // use this under Solaris

if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == -1) {
    perror("setsockopt");
    exit(1);
}

请参阅 beej说明书中的bind()的部分网络编程更详细的解释。

这篇关于而重新套接字绑定错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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