天天看點

C語言實作簡單的回聲伺服器

建立echo_server.c

#include<stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <ctype.h>
#include <arpa/inet.h>

#define SERVER_PORT 666

int main(void){
    int sock;
    struct sockaddr_in server_addr;

    sock=socket(AF_INET,SOCK_STREAM,0);

    bzero(&server_addr,sizeof(server_addr));

    server_addr.sin_family=AF_INET;
    server_addr.sin_addr.s_addr=htonl(INADDR_ANY);

    server_addr.sin_port=htons(SERVER_PORT);

    bind(sock,(struct sockaddr *)&server_addr,sizeof(server_addr));

    listen(sock,128);

    printf("等待用戶端的連接配接..\n");

    int done=1;
    while(done){
        struct sockaddr_in client;
        int client_sock;
        char client_ip[64];
        socklen_t client_addr_len;
        client_addr_len=sizeof(client);
        accept(sock,(struct sockaddr *)&client,&client_addr_len);
        printf("client ip:%s\n port :%d\n",
                inet_ntop(AF_INET,&client.sin_addr.s_addr,client_ip,sizeof(client_ip)),
                ntohs(client.sin_port));
    }
}      

打包生成可執行檔案

[root@localhost c++]# gcc echo_server.c  -o echo_server.exe      

啟動伺服器

[root@localhost c++]# ./echo_server.exe 
等待用戶端的連接配接..      
[root@localhost ~]# telnet 127.0.0.1 666
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.      
[root@localhost c++]# ./echo_server.exe 
等待用戶端的連接配接..
client ip:127.0.0.1
 port :36156