C語言實現(xiàn)簡單回聲服務器
更新時間:2022年03月02日 09:10:28 作者:reg183
這篇文章主要為大家詳細介紹了C語言實現(xiàn)簡單回聲服務器,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了C語言實現(xiàn)簡單的回聲服務器,供大家參考,具體內容如下
新建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
啟動服務器
[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
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
深入解讀C++ 內聯(lián)函數(shù)inline|nullptr
內聯(lián)函數(shù):用** inline 修飾的函數(shù)叫做內聯(lián)函數(shù),編譯時C++編譯器會在調用的地方展開內聯(lián)函數(shù)**,這樣調用內聯(lián)函數(shù)就需要創(chuàng)建棧楨,就提高效率了,這篇文章給大家介紹C++ 內聯(lián)函數(shù)inline|nullptr的相關知識,感興趣的朋友跟隨小編一起看看吧2024-07-07
C語言 數(shù)據(jù)結構之鏈表實現(xiàn)代碼
這篇文章主要介紹了C語言 數(shù)據(jù)結構之鏈表實現(xiàn)代碼的相關資料,需要的朋友可以參考下2016-10-10

