下面提供了代码。我创建了一个 TCP 套接字并尝试连接。连接失败。但是,缓冲区中留下了一些东西,并且套接字仍然可读。在这种情况下有没有办法清理套接字?非常感谢你的帮助。
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/inotify.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <time.h>
#include <sys/time.h>
#include <sys/select.h>
#include <fcntl.h>
#include <semaphore.h>
#include <sys/epoll.h>
#include <signal.h>
#include <math.h>
#include <netdb.h>
#include <errno.h>
int main()
{
int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
struct sockaddr_in sai;
sai.sin_family = AF_INET;
int rv = inet_pton(AF_INET, "10.10.131.1", &(sai.sin_addr));
sai.sin_port = htons(1234);
int r = connect(sock, (struct sockaddr*)(&sai), sizeof(struct sockaddr_in));
if (r < 0)
{
printf("connection failed: %s\n", strerror(errno));
}
fd_set r_set;
FD_ZERO(&r_set);
FD_SET(sock, &r_set);
int n = select(sock + 1, &r_set, NULL, NULL, NULL);
if (n > 0)
{
if (FD_ISSET(sock, &r_set))
{
printf("socket %d is readable\n", sock);
}
}
return 0;
}
执行结果:
connection failed: Connection refused
socket 3 is readable