【发布时间】:2014-02-14 03:28:13
【问题描述】:
我创建了一个 TCP 服务器程序,它绑定、侦听和接受来自特定 IP 地址和端口号的连接。 在第一次连接期间:服务器正在接受来自客户端的 SYN 数据包并将 ACK 发送回客户端。稍后从客户端获得 ACK。最后客户端是与服务器的 RST。
在第二次连接期间,客户端正在向从属发送一个 SYN 数据包,但没有来自服务器的 ACK。
我认为在第二次连接时不可能绑定相同的ip地址和端口号。
是否可以在第二次连接中绑定相同的ip地址和端口号?
服务器:
SOCKET sock;
SOCKET fd;
uint16 port = 52428;
// I am also using non blocking mode
void CreateSocket()
{
struct sockaddr_in server, client; // creating a socket address structure: structure contains ip address and port number
WORD wVersionRequested;
WSADATA wsaData;
int len;
int iResult;
u_long iMode = 1;
printf("Initializing Winsock\n");
wVersionRequested = MAKEWORD (1, 1);
iResult = WSAStartup (wVersionRequested, &wsaData);
if (iResult != NO_ERROR)
printf("Error at WSAStartup()\n");
// create socket
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock < 0) {
printf("Could not Create Socket\n");
//return 0;
}
printf("Socket Created\n");
iResult = ioctlsocket(sock, FIONBIO, &iMode);
if (iResult < 0)
printf("\n ioctl failed \n");
// create socket address of the server
memset( &server, 0, sizeof(server));
// IPv4 - connection
server.sin_family = AF_INET;
// accept connections from any ip adress
server.sin_addr.s_addr = htonl(INADDR_ANY);
// set port
server.sin_port = htons(52428);
//Binding between the socket and ip address
if(bind (sock, (struct sockaddr *)&server, sizeof(server)) < 0)
{
printf("Bind failed with error code: %d", WSAGetLastError());
}
//Listen to incoming connections
if(listen(sock, 10) == -1){
printf("Listen failed with error code: %d", WSAGetLastError());
}
printf("Server has been successfully set up - Waiting for incoming connections");
for(;;){
len = sizeof(client);
fd = accept(sock, (struct sockaddr*) &client, &len);
if (fd < 0){
printf("Accept failed");
closesocket(sock);
}
//echo(fd);
printf("\n Process incoming connection from (%s , %d)", inet_ntoa(client.sin_addr),ntohs(client.sin_port));
//closesocket(fd);
}
}
【问题讨论】:
-
服务器是否关闭了它调用
listen()的套接字? -
我会在上面添加我的代码。
-
绑定什么?客户端套接字?您根本不需要绑定客户端套接字。
标签: sockets tcp ip port tcpserver