是否可以使用相同的端口和IP地址?

时间:2014-01-23 14:12:44

标签: sockets tcp ip port tcpserver

我创建了一个TCP服务器程序,它绑定,监听和接受来自特定IP地址和端口号的连接。 在第一次连接期间:服务器正在接受来自客户端的SYN数据包并将ACK发送回客户端。稍后从客户端获得ACK。最后,客户端是服务器的RST。

在第二次连接期间,客户端正在向从设备发送SYN数据包,但服务器没有ACK。

我认为在使用相同的IP地址和端口号的第二次连接期间没有绑定。

是否可以在第二个连接中绑定SAME 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);
    }

}

1 个答案:

答案 0 :(得分:1)

TCP连接由四个参数标识:

  • 本地IP
  • 本地端口
  • 远程IP
  • 远程端口

服务器通常对其所有连接使用相同的本地IP和端口(例如,HTTP服务器在端口80上侦听所有连接)。来自客户端的每个连接都将具有不同的远程IP和/或远程端口,这些解决了歧义。

当服务器关闭所有连接的套接字时,TCB会在TIME_WAIT状态下保持几分钟。这通常会阻止进程绑定到端口,因为您无法绑定到具有任何关联TCB的本地IP /端口。如果要重新启动服务器并绑定到刚刚用于连接的相同端口和地址,则需要使用SO_REUSEADDR套接字选项来解决此问题。参见:

Socket options SO_REUSEADDR and SO_REUSEPORT, how do they differ? Do they mean the same across all major operating systems?

了解详情。

相关问题