本文实例为大家分享了C语言实现简单的回声服务器,供大家参考,具体内容如下
新建echo_server.c
#include#include #include #include #include #include #include #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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。