Unix/Linux socket编程的一个问题?

发布于 2022-09-04 14:59:53 字数 2055 浏览 23 评论 0

服务端提供一个返回时间的服务,客户端使用telnet去访问

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <time.h>
#include <strings.h>

#define PORTNUM 13000
#define HOSTLEN 256
#define oops(msg) {perror(msg); exit(1);}

int main()
{
    struct sockaddr_in saddr;
    struct hostent *hp;
    char hostname[HOSTLEN];
    int sock_id, sock_fd;
    FILE *sock_fp;
    char *ctime();
    time_t thetime;

    sock_id = socket(PF_INET, SOCK_STREAM, 0);
    if( sock_id == -1 )
        oops("scoket");
    
    bzero((void*)&saddr, sizeof(saddr));

    gethostname(hostname, HOSTLEN);
    hp = gethostbyname(hostname);

    bcopy((void*)hp->h_addr, (void*)&saddr.sin_addr, hp->h_length);
    saddr.sin_port = htons(PORTNUM);
    saddr.sin_family = AF_INET;
    
    if( bind(sock_id, (struct sockaddr*)&saddr, sizeof(saddr)) != 0  )
        oops("bind");

    if( listen(sock_id, 1) != 0 )
        oops("listen");

    while(1) {
        sock_fd = accept(sock_id, NULL, NULL);
        printf("Wow! got a call\n");
        if( sock_fd == -1 )
            oops("accept");
        
        sock_fp = fdopen(sock_id, "w");
        if (sock_fp == NULL)
            oops("fdopen");
        thetime = time(NULL);

        fprintf(sock_fp, "The time here is...");
        fprintf(sock_fp, "%s", ctime(&thetime));
        fclose(sock_fp);
    }
}

运行结果:

deweixudeMBP:socket deweixu$ ./timeserv.out &
[1] 32999
deweixudeMBP:socket deweixu$ hostname
deweixudeMBP.lan
deweixudeMBP:socket deweixu$ telnet deweixudeMBP.lan 13000
Trying 192.168.199.205...
Wow! got a call
Connected to deweixudembp.lan.
Escape character is '^]'.
Wow! got a call
accept: Bad file descriptor
Connection closed by foreign host.
[1]+  Exit 1                  ./timeserv.out
deweixudeMBP:socket deweixu$ 

为什么会 accept: Bad file descriptor ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

感性不性感 2022-09-11 14:59:53
    sock_fd = accept(sock_id, NULL, NULL);
    printf("Wow! got a call\n");
    if( sock_fd == -1 )
        oops("accept");
    
    sock_fp = fdopen(sock_id, "w");

sock_fp = fdopen(sock_id, "w");
换成
sock_fp = fdopen(sock_fd, "w");

狼性发作 2022-09-11 14:59:53

你给出的程序这句话纯属多余:
sock_fp = fdopen(sock_id, "w");

accept 之后的socket就可以直接读写,不需要用管道命令打开,删了应该就好。

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文