如何彻底摧毁在C套接字连接 [英] How to completely destroy a socket connection in C

查看:232
本文介绍了如何彻底摧毁在C套接字连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经用插座在Linux聊天客户端,我希望彻底摧毁连接。以下是code的相关部分:

I have made a chat client in linux using socket, and i wish to destroy the connection completely. Following is the relevant portions of the code:

int sock, connected, bytes_recieved , true = 1, pid;  
char send_data [1024] , recv_data[1024];     
struct sockaddr_in server_addr,client_addr;    
int sin_size;
label:
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
    perror("Socket");
    exit(1);
}
if (setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&true,sizeof(int)) == -1)
{
    perror("Setsockopt");
    exit(1);
}
server_addr.sin_family = AF_INET;         
server_addr.sin_port = htons(3128);     
server_addr.sin_addr.s_addr = INADDR_ANY; 
bzero(&(server_addr.sin_zero),8); 
if (bind(sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr))== -1)
{
    perror("Unable to bind");
    exit(1);
}
if (listen(sock, 5) == -1)
{
    perror("Listen");
    exit(1);
}
printf("\nTCPServer Waiting for client on port 3128");
fflush(stdout);
connected = accept(sock, (struct sockaddr *)&client_addr,&sin_size);
//necessary code
close(sock);
goto label;

但接近(袜子)不列入似乎关闭彻底摧毁的连接,因为要去'标签'的code正在退出显示错误消息后

but the close(sock) doesnot seem to close the destroy the connection completely, because after going to 'label' the code is exiting showing the error message

Unable to bind: Address already in use

这是连接不会再次发生。能有什么问题呢?先谢谢了。

That is the connection is not happening again. What can the problem be? Thanks in advance.

编辑:其实我要的是,当我破坏了连接后,运行从一开始的剧本,它应该是一个新的程序运行什么。我该怎么办呢?

What I actually want is, when I run the script from the beginning after destroying the connection, it should run as a fresh program. How can I do it?

推荐答案

关闭呼叫才标志着TCP套接字关闭。它不是由过程可用了。
但是,内核可能仍持有一些资源,期限(TIME_WAIT,2毫升等东西)。

The close call only marks the TCP socket closed. It is not usable by process anymore. But kernel may still hold some resources for a period (TIME_WAIT, 2MLS etc stuff).

SO_REUSEADDR的设置应取消绑定的问题。

Setting of SO_REUSEADDR should remove binding problems.

所以一定的那个值真正真是非零致电时的setsockopt (溢出错误可能覆盖它):

So be sure that value of true is really non-zero when calling setsockopt (overflow bug may overwrite it):

true = 1;
setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&true,sizeof(int))

PID 变量是您code。如果你使用(用于启动连接处理PROCESSS),那么你应该关闭袜子在不过程中也需要它。

There is pid variable is your code. If you use fork (for starting connection handling processs), then you should close sock also in the process which does not need it.

这篇关于如何彻底摧毁在C套接字连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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