Linux环境C C++起Socket Server监听8080端口的代码实现

Linux环境C C++起Socket Server监听8080端口的代码实现


DATE: 2017-09-06 21:56:31

代码抄录自《UNUX网络编程 卷一》,在实现开发环境中调试通过,经测试发现可以正常监听。

开发环境:CentOS,g++,VIM
功能:C++实现Socket通信的Server端,实现监听8080端口接收到的消息。

#include <arpa/inet.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <stdio.h>
#include <strings.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

const int MAXLINE = 4096;
const int LISTENQ = 1024;

int main(int argc, char **argv)
{
    int     listenfd, connfd;
    socklen_t len;
    struct     sockaddr_in servaddr, cliaddr;
    char     buff[MAXLINE];
    time_t     ticks;
    bzero(&servaddr, sizeof(servaddr));

    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(8080);

    listenfd = socket(AF_INET, SOCK_STREAM, 0);
    bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
    listen(listenfd, LISTENQ);

    for ( ; ; ) {
        len = sizeof(cliaddr);
        connfd = accept(listenfd, (struct sockaddr *) &cliaddr, &len);
        printf("connect from %s, port %d\n",
            inet_ntop(AF_INET, &cliaddr.sin_addr, buff, sizeof(buff)),
            ntohs(cliaddr.sin_port));
        
        read(connfd, buff, strlen(buff));
        printf("Recive msg: %s\n", buff);
        
        bzero(buff, sizeof(buff));
        ticks = time(NULL);
        snprintf(buff, sizeof(buff), "%.24s\r\n", ctime(&ticks));
        write(connfd, buff, strlen(buff));
        printf("Send msg: %s\n", buff);
        
        close(connfd);
    }
    return 0;
}
版权声明

弈心博客


本文首发site_name,转载请附上博文链接!