如何在C中完全破坏套接字连接 [英] How to completely destroy a socket connection in C

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

问题描述

我在 linux 中使用套接字创建了一个聊天客户端,我希望完全破坏连接.以下是代码的相关部分:

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("
TCPServer Waiting for client on port 3128");
fflush(stdout);
connected = accept(sock, (struct sockaddr *)&client_addr,&sin_size);
//necessary code
close(sock);
goto label;

但是 close(sock) 似乎并没有完全关闭破坏连接,因为在转到标签"之后,代码正在退出并显示错误消息

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?

推荐答案

close 调用只标记 TCP 套接字关闭.它不再被进程使用.但是内核可能仍会在一段时间内保留一些资源(TIME_WAIT、2MLS 等).

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.

所以请确保调用 setsockopttrue 的值真的不为零(溢出错误可能会覆盖它):

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 变量是你的代码.如果你使用fork(用于启动连接处理进程),那么你也应该在不需要它的进程中关闭sock.

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天全站免登陆