`

UNIX网络编程 基本TCP套接字编程

 
阅读更多

 

 

 

一段打印客户端的ip和端口,并返回一段当前时间的代码,客户端通过telnet就可以连接了

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

int main(int argc, char **argv) {

    int listenfd, connfd;
    socklen_t len;
    struct sockaddr_in server,cli;
    char buffer[1024];
    time_t ticks;

    listenfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    bzero(&server, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = htonl(INADDR_ANY);
    server.sin_port = htons(9527);

    bind(listenfd, (struct sockaddr *)&server,sizeof(server));
    listen(listenfd, 10);


    while(1) {
        len = sizeof(cli);
        connfd = accept(listenfd, (struct sockaddr *)&cli, &len);

        inet_ntop(AF_INET, &cli.sin_addr, buffer, sizeof(buffer));
        uint16_t u = ntohs(cli.sin_port);
        printf("connection from %s, port  %d\n", buffer,u);

   
        ticks = time(NULL);
        char *t = ctime(&ticks);
        snprintf(buffer,sizeof(buffer), "%35s\r\n", t);
        write(connfd, buffer,strlen(buffer));
   
        close(connfd);
    }

    printf("ok~\n");
    return 0;
}

 

 

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics