C套接字:accept()总是返回相同的套接字ID吗?

时间:2017-08-11 18:48:05

标签: c sockets

accept总是返回相同的套接字ID /文件描述符(connfd:4)

无论我是在使用两个不同进程的同一本地计算机上,还是在两台不同的计算机上。为什么返回值不同?

不确定它是否与输出有关。我以前只使用printf()但是stdout上没有输出,所以我把它改成了fprintf(stderr,...)。我也试过使用fflush(),同样的东西,来自accept()

的相同套接字ID /描述符
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <time.h>
#include <pthread.h> /* -pthread */

#define SERVER_PORT 5000

void *cli_func(void *arg);

int main(int argc, char* argv[]){
        fflush(stdout);
        int listenfd = 0, connfd = 0;
        struct sockaddr_in serv_addr;

        char sendBuff[1025];
        time_t ticks;
        listenfd = socket(AF_INET, SOCK_STREAM, 0);

        fprintf(stderr, "Starting server...\n");

        memset(&serv_addr, '0', sizeof(serv_addr));
        memset(sendBuff, '0', sizeof(sendBuff));

        serv_addr.sin_family = AF_INET;
        serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
        serv_addr.sin_port = htons(SERVER_PORT);

        bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));

        listen(listenfd, 10);

        fprintf(stderr, "Listening...\n");

        while(1){

                connfd = accept(listenfd, (struct sockaddr*)NULL, NULL);
                pthread_t cli_thread;
                fprintf(stderr, "Got new client\n");

                if(pthread_create(&cli_thread, NULL, cli_func, &connfd)){
                        fprintf(stderr, "Error creating thread\n");
                        return 1;
                }
                /*
                if(pthread_join(cli_thread, NULL)){
                        fprintf(stderr, "Error joining thread\n");
                        return 2;
                }
                */
                ticks = time(NULL);
                snprintf(sendBuff, sizeof(sendBuff), "%.24s\r\n", ctime(&ticks));
                write(connfd, sendBuff, strlen(sendBuff));

                close(connfd);

                sleep(1);

        }

}

void *cli_func(void *arg){
        int* clifd_ptr = (int *)arg;
        fprintf(stderr, "client ID: %d", *clifd_ptr);

        return NULL;
}

0 个答案:

没有答案