• 《UNIX网络编程》 1


    1、安装 daytime 服务:

    apt-get install xinetd

    chmod 777 /etc/xinetd.d/daytime

    vim /etc/xinetd.d/daytime

    把两个 disable = yes ,改成 disable = no

    /etc/init.d/xinetd restart

    2、timeserver.cpp:

    #include <time.h>
    #include <netinet/in.h>
    #include <string.h>
    #include <stdio.h>
    #include <unistd.h>
    
    #define LISTENQ 1024
    int main(int argc, char** argv)
    {
        int listenfd,connfd;
        sockaddr_in servaddr;
        char buff[1024];
        time_t ticks;
    
        listenfd = socket(AF_INET,SOCK_STREAM,0);
        bzero(&servaddr,sizeof(servaddr));
        servaddr.sin_family = AF_INET;
        servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
        servaddr.sin_port = htons(2013);
    
        bind(listenfd,(sockaddr*)&servaddr,sizeof(servaddr));
        listen(listenfd,LISTENQ);
        for(;;)
        {   
            connfd = accept(listenfd,(sockaddr*)NULL,NULL);
            ticks = time(NULL);
            snprintf(buff,sizeof(buff),"%.24s\r\n",ctime(&ticks));
            write(connfd,buff,strlen(buff));    //#include <unistd.h>
            close(connfd);
        }   
    }

    3、timeclient.cpp:

    #include <iostream>
    #include <netinet/in.h>
    #include <string.h>
    #include <arpa/inet.h>
    #include <stdio.h>
    
    int main(int argc, char **argv)
    {
        int     sockfd,n;
        char    recvline[1024];
        sockaddr_in servaddr;       //#include <netinet/in.h>
    
        if(argc != 2)
        {   
            std::cout<<"usage: a.out <IP>"<<std::endl;
            return -1; 
        }   
        if((sockfd = socket(AF_INET,SOCK_STREAM,0)) < 0)    //#include <sys/socket.h>
        {   
            std::cout<<"socket error."<<std::endl;
            return -1; 
        }   
        bzero(&servaddr, sizeof(servaddr)); //#include <cstring>
        servaddr.sin_family = AF_INET;
        servaddr.sin_port = htons(2013);
        if(inet_pton(AF_INET,argv[1],&servaddr.sin_addr) <= 0)  // #include <arpa/inet.h>
        {   
            std::cout<<"inet_pton error"<<std::endl;
            return -1; 
        }   
        if(connect(sockfd, (sockaddr*)&servaddr,sizeof(servaddr)) < 0)  
        {   
            std::cout<<"connect error"<<std::endl;
            return -1; 
        }   
        while( (n = read(sockfd, recvline, 1023)) > 0)
        {   
            recvline[n] = 0;
            if(fputs(recvline, stdout) == EOF)  //#include <stdio.h>
            {   
                std::cout<<"fputs error"<<std::endl;
            }   
        }   
        if(n < 0)
        {   
            std::cout<<"read error"<<std::endl;
        }  
    }
  • 相关阅读:
    Java高并发(1)
    Java基础知识之常见关键字(1)
    jQuery中attr()与prop()区别介绍
    win7下delphi中的help文档问题
    Delphi TMemo 可以显示、编辑多行文本
    TcxGrid
    Delphi学习手记——单引号和双引号的区别
    sql 系统表协助集合
    VCL安装有哪几种方法?
    sqlserver2008 服务器实例连接
  • 原文地址:https://www.cnblogs.com/tianyajuanke/p/3096991.html
Copyright © 2020-2023  润新知