一个简单的时间获取服务器

#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <time.h>
#include <errno.h>
#include <string.h>

const int maxline = 4096;

int main(int argc, char **argv) {
    int listenfd, connfd;
    struct sockaddr_in servaddr;
    char buff[maxline], errbuff[maxline];
    time_t ticks;

    if((listenfd=socket(AF_INET, SOCK_STREAM, 0))<0) {
        strerror_r(errno, errbuff, maxline);
        fprintf(stderr, "socket error: %s\n", errbuff);
        exit(-1);
    }
    
    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(13);

    if(bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr))<0) {
        strerror_r(errno, errbuff, maxline);
        fprintf(stderr, "bind error: %s\n", errbuff);
        exit(-1);
    }

    if(listen(listenfd, 1024)<0) {
        strerror_r(errno, errbuff, maxline);
        fprintf(stderr, "listen error: %s\n", errbuff);
        exit(-1);
    }
    
    for(;;)    {
        if((connfd=accept(listenfd, (struct sockaddr *)NULL, NULL))<0) {
            strerror_r(errno, errbuff, maxline);
            fprintf(stderr, "accept error: %s\n", errbuff);
            exit(-1);
        }
        ticks = time(NULL);
        snprintf(buff, sizeof(buff), "%.24s\r\n", ctime(&ticks));
        if(write(connfd, buff, strlen(buff)) != strlen(buff)) {
            strerror_r(errno, errbuff, maxline);
            fprintf(stderr, "write error: %s\n", errbuff);
            exit(-1);
        }        
        if(close(connfd)<0) {
            strerror_r(errno, errbuff, maxline);
            fprintf(stderr, "close error: %s\n", errbuff);
            exit(-1);
        }
    }

    return 0;
}  

$ ./a.out
bind error: Permission denied

用普通用户执行,会报错,因为绑定的是13端口,需要高权用户。

或者使用1024之外的端口。

posted @ 2022-09-06 15:02  东宫得臣  阅读(41)  评论(0编辑  收藏  举报