Linux C 时间服务器

来源:互联网 发布:大华监控主机网络设置 编辑:程序博客网 时间:2024/06/07 06:55
<strong><span style="font-size:18px;">#include <stdio.h>#include <unistd.h>#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <stdlib.h>#include <time.h>#include <netdb.h>#include <string.h>#define PORTNUM 13000#define HOSTLEN 256#define oops(msg)   {perror(msg);exit(1);}int main(int argc,char **argv){    struct sockaddr_in saddr;    struct hostent *hp;    char hostname[HOSTLEN];    int sock_id, sock_fd;    FILE *sock_fp;    time_t thetime;    // 创建 socket 套接字    sock_id = socket(PF_INET,SOCK_STREAM,0);    if(sock_id == -1)        oops("socket")    bzero((void *)&saddr,sizeof(saddr));    // 填充套接字    gethostname(hostname,HOSTLEN);  //获取主机名    hp = gethostbyname(hostname);   // 获取给定主机名的主机信息    printf("%s\n",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_fd,"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);    }}</span></strong>



可以使用 telnet 命令测试。 

telnet  “HOSTNAME” 13000
HOSTNAME 可以通过 linux 命令 hostname 获得


0 0