亲宝软件园·资讯

展开

C语言回声服务器

reg183 人气:0

新建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 
等待客户端的连接..

telnet访问

[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

加载全部内容

相关教程
猜你喜欢
用户评论