1.connect(fd, serveraddr, size) a. fd -> tcb syn /// 2.listen a. listenfd -> tcb b. tcb -> listen // 3.accept a. while(acceptqueue == NULL) { pthread_cond_wait(); } b. *tcb = get_tcb_from(acceptqueue); c. clientfd = get_fd_fdtable(); d. tcb -> clientfd; return clientfd;
如何通过网络数据包,查找半链接队列的节点
五元组(sip, dip, sport, dport, proto)
端口65535个,如何做百万级别的连接
连接 tcb 五元组
连接断开
FIN包一般是携带包,比如携带在最后一次发送数据包的标志位上,如果一直没有发送数据,则会单独发送FIN包。
大量close_wait状态?没有及时调用close();
两端同时调用close() ? 进入CLOSING状态(下图的同时关闭状态)
思考:
使用tcpdump抓取三次握手
SYN_SENT如何转为SYN_RECV ? (同时打开)
listenfd能不能够connect ?
这里使用一个拿来即用的TCP测试程序:
#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <string.h> int main(void) { //初始化套接字 int listenfd = socket(AF_INET, SOCK_STREAM, 0); if (listenfd < 0) { perror("socket"); return -1; } struct sockaddr_in address; bzero(&address, sizeof(address)); address.sin_family = AF_INET; address.sin_addr.s_addr = htonl(INADDR_ANY); address.sin_port = htons(8888); int ret = bind(listenfd, (struct sockaddr *)&address, sizeof(address)); if (ret < 0) { perror("bind"); return -1; } ret = listen(listenfd, 5); if (ret < 0) { perror("listen"); return -1; } struct sockaddr_in client_address; socklen_t client_addrlength = sizeof(client_address); int connfd = accept(listenfd, (struct sockaddr *)&client_address, &client_addrlength); if (connfd < 0) { perror("accept"); } printf("The connection is successful : %d\n", connfd); char buf[1024] = {0}; ret = recv(connfd, buf, 1024, 0); if (ret <= 0) { perror("recv"); } printf("recv: %s\n", buf); close(connfd); close(listenfd); return 0; }
程序监听在8888端口上,我们使用网络调试助手连接一下,并使用tcpdump查看8888端口的状态:
上面的是建立连接抓取的包,下面的是服务端主动断开连接发送的网络包。
仍然使用上面那个服务端程序,使用下面这个客户端程序连接,看看listenfd能不能connect:
int main(void) { //初始化套接字 int listenfd = socket(AF_INET, SOCK_STREAM, 0); if (listenfd < 0) { perror("socket"); return -1; } struct sockaddr_in address; bzero(&address, sizeof(address)); address.sin_family = AF_INET; address.sin_addr.s_addr = htonl(INADDR_ANY); address.sin_port = htons(8889);//这里绑定在8889端口 int ret = bind(listenfd, (struct sockaddr *)&address, sizeof(address)); if (ret < 0) { perror("bind"); return -1; } ret = listen(listenfd, 5); if (ret < 0) { perror("listen"); return -1; } struct sockaddr_in srv_addr; srv_addr.sin_family = AF_INET; srv_addr.sin_addr.s_addr = htonl(INADDR_ANY); srv_addr.sin_port = htons(8888);//连接8888 //使用listenfd if(-1 == connect(listenfd, (struct sockaddr*)&srv_addr, sizeof(srv_addr))) { perror("connect"); return 1; } else { printf("connect success!"); } return 0; }
运行发现连接失败:
gaoyuelong@ubuntu:~/23040voice/06/test$ ./client connect: Transport endpoint is already connected
文章参考与<零声教育>的C/C++linux服务期高级架构系统教程学习:https://ke.qq.com/course/417774?flowToken=1020253