網站首頁 編程語言 正文
本文實例為大家分享了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
原文鏈接:https://blog.csdn.net/chendongpu/article/details/122682665
相關推薦
- 2022-04-11 matlab模擬退火算法單約束車間流水線調度解決實現及示例_C 語言
- 2022-05-13 Github pages 同步到Gitee pages 并自動更新Gitee pages
- 2022-09-26 Python文件相關操作和方法匯總大全_python
- 2022-09-26 快速搭建 ElasticSearch學習環境
- 2023-07-02 Python3中zip()函數知識點小結_python
- 2023-01-26 Android?源碼淺析RecyclerView?ItemAnimator_Android
- 2022-12-06 Docker基礎和常用命令詳解_docker
- 2022-09-03 解決Python3錯誤:SyntaxError:?unexpected?EOF?while?pars
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支