'Echo server continuously echo

I am reproducing the echo server sample based on process in CSAPP. But when I use ctrl+c terminate the client, the server continuously echo without stopping while host and port are the same as the client before it terminated.

It continuously print "close error" and "localhost xxxx"(xxxx is the port same as the client).

Well,sometimes the server also continuously echo "server received 18446744073709551615 bytes " while the client is absolutely be closed and I find out that in this case, the connfd is -1.

The server is listening 127.0.0.1 and port 8888. Well, I'am running my code by the vscode code_server in my linux server, I don't know if this matters.

The server code:

int open_lisetnfd(char *port){
    int listenfd,optval=1;
    struct addrinfo hints,*p,*listp;
    memset(&hints,0,sizeof(hints));
    hints.ai_family=AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE |AI_ADDRCONFIG|AI_NUMERICSERV;
    getaddrinfo(NULL,port,&hints,&listp);
    
    for(p=listp;p;p=p->ai_next){
        if((listenfd = socket(p->ai_family,p->ai_socktype,p->ai_protocol))<0){
            continue;
        }
        setsockopt(listenfd,SOL_SOCKET,SO_REUSEADDR,(const void*)&optval,sizeof(int));  
        if(bind(listenfd,p->ai_addr,p->ai_addrlen)==0){
            break;
        }
        close(listenfd);
    }
    freeaddrinfo(listp);
    if(!p)
        return -1;
    if(listen(listenfd,SOMAXCONN)<0){
        close(listenfd);
        return -1;
    }
    return listenfd;
}

int main(){
    int listenfd,connfd;
    socklen_t clientlen;
    struct sockaddr_storage clientaddr;
    char client_hostnmae[MAXLEN],client_port[MAXLEN];
    char Listen_port[20]="8888";
    listenfd = open_lisetnfd(Listen_port);
    while(1){
        clientlen = sizeof(struct sockaddr_storage);
        connfd = accept(listenfd, (SA*)&clientaddr,&clientlen);
        getnameinfo((SA*) &clientaddr, clientlen, client_hostnmae,MAXLEN,client_port,MAXLEN,0);
        cout<<client_hostnmae<<" "<<client_port<<"\n";
        echo(connfd);
        close(connfd);
    }
}
void echo(int connfd){
    size_t n;
    char buf[MAXLEN];
    rio_t rio;
    rio_readinitb(&rio,connfd);
    while((n=rio_readlineb(&rio,buf,MAXLEN))!=0){
        cout<<"server received "<<n<<" bytes\n";
        rio_writen(connfd,buf,n);
    }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source