C語言實現(xiàn)簡單回聲服務(wù)器
更新時間:2022年03月02日 09:10:28 作者:reg183
這篇文章主要為大家詳細介紹了C語言實現(xiàn)簡單回聲服務(wù)器,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了C語言實現(xiàn)簡單的回聲服務(wù)器,供大家參考,具體內(nèi)容如下
新建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));
? ? }
}打包生成可執(zhí)行文件
[root@localhost c++]# gcc echo_server.c ?-o echo_server.exe
啟動服務(wù)器
[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 '^]'.
服務(wù)器端打印
[root@localhost c++]# ./echo_server.exe? 等待客戶端的連接.. client ip:127.0.0.1 ?port :36156
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

