首页 > 其他分享 >一个简单的时间获取服务器

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

时间:2022-09-06 15:13:09浏览次数:67  
标签:include int listenfd char 获取 简单 服务器 maxline

#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;
    size_t length;
    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端口,需要高权用户。

标签:include,int,listenfd,char,获取,简单,服务器,maxline
From: https://www.cnblogs.com/donggongdechen/p/16661861.html

相关文章