当前位置:网站首页>作业8.9 构建TCP协议的服务器
作业8.9 构建TCP协议的服务器
2022-08-10 12:40:00 【不知名大学生M】
构建TCP协议的服务器
实现代码
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
//打印错误新的宏函数
#define ERR_MSG(msg) do{
\ fprintf(stderr, " __%d__ ", __LINE__);\ perror(msg);\ }while(0)
#define PORT 8888 //1024~49151
#define IP "192.168.31.96" //本机IP,用ifconfig查看
int main(int argc, const char *argv[])
{
//创建流式套接字
int sfd = socket(AF_INET, SOCK_STREAM, 0);
if(sfd < 0)
{
ERR_MSG("socket");
return -1;
}
printf("create socket success\n");
//填充地址信息结构体,真实的地址信息结构体与协议族相关
//AF_INET,所以详情请看man 7 ip
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(PORT); //网络字节序的端口号
sin.sin_addr.s_addr = inet_addr(IP); //网络字节序的IP地址
//将地址信息结构体绑定到套接字上
if(bind(sfd, (struct sockaddr*)&sin, sizeof(sin)) < 0)
{
ERR_MSG("bind");
return -1;
}
printf("bind success\n");
//将套接字设置为被动监听状态,让内核去监听是否有客户端连接;
if(listen(sfd, 10) < 0)
{
ERR_MSG("listen");
return -1;
}
printf("listen success\n");
struct sockaddr_in cin;
socklen_t addrlen = sizeof(cin);
//从已完成连接的队列头中,取出一个客户端的信息,创建生成一个新的套接字文件描述符,
//该文件描述符才是与客户端通信的文件描述符!!!
int newfd = accept(sfd, (struct sockaddr*)&cin, &addrlen);
if(newfd < 0)
{
perror("accept");
return -1;
}
//网络字节序的IP-->点分十进制 网络字节序的port--->本机字节序
printf("[%s : %d] newfd = %d\n", inet_ntoa(cin.sin_addr), ntohs(cin.sin_port),newfd);
char buf[128] = "";
ssize_t res = 0;
while(1)
{
bzero(buf, sizeof(buf));
//循环接收
res = recv(newfd, buf, sizeof(buf), 0);
if(res < 0)
{
ERR_MSG("recv");
return -1;
}
else if(0 == res)
{
printf("[%s : %d] newfd = %d客户端退出\n", inet_ntoa(cin.sin_addr), ntohs(cin.sin_port),newfd);
break;
}
printf("[%s : %d] newfd = %d : %s\n", inet_ntoa(cin.sin_addr), ntohs(cin.sin_port),newfd, buf);
}
close(sfd);
close(newfd);
return 0;
}
运行结果
边栏推荐
猜你喜欢
【黑马早报】雷军称低谷期曾想转行开酒吧;拜登正式签署芯片法案;软银二季度巨亏230亿美元;北京市消协约谈每日优鲜...
跨域的五种解决方案
shell:常用小工具(sort、uniq、tr、cut)
Digicert EV证书签名后出现“证书对于请求用法无效”的解决方案
Code Casual Recording Notes_Dynamic Programming_70 Climbing Stairs
没有接班人,格力只剩“明珠精选”
【百度统计】用户行为分析
神了!阿里数据库专家纯手写了这份604页的Oracle+MySQL攻坚指南
LeetCode简单题之合并相似的物品
一个 CRM One Order Application log 的单元测试报表
随机推荐
Wirshark common operations and tcp three-way handshake process example analysis
YTU 2295: KMP pattern match one (string)
【iOS】Organization of interviews
娄底植物细胞实验室建设基本组成要点
Jiugongge lottery animation
娄底疾控中心实验室设计理念说明
22!Beijing Changping District notified catering service enterprises with food safety problems
3DS MAX 批量导出文件脚本 MAXScript 带界面
C#中导入其它自定义的命名空间
关于flask中static_folder 和 static_url_path参数理解
kubernetes介绍
教育Codeforces轮41(额定Div。2)大肠Tufurama
3DS MAX batch export file script MAXScript with interface
es6-promise对象详解
九宫格抽奖动效
The recursive recursive Fighting_ silver study ah but level 4
【ECCV 2022|百万奖金】PSG大赛:追求“最全面”的场景理解
iTextSharp 使用详解
NodeJs原理 - Stream(二)
C# error The 'xmins' attribute is not supported in this context