- server.c
- #include
/* See NOTES */ - #include
- #include
- #include
- #include
- #include
- #include
- #include
- int main(int argc, char** argv)
- {
- int ret;
- int len = sizeof(struct sockaddr);
- //创建socket
- int sockfd = socket(AF_INET, SOCK_DGRAM,0);
- if(sockfd == -1)
- {
- perror("socket\n");
- exit(1);
- }
- //将addr地址与socket绑定在一起
- //初始化地址
- struct sockaddr_in addr;
- addr.sin_family = AF_INET;
- addr.sin_port = htons(4444);
- addr.sin_addr.s_addr = INADDR_ANY;
- memset(addr.sin_zero,8,0);
- //进行绑定
- ret = bind(sockfd, (struct sockaddr*)&addr, len);
- if(ret == -1)
- {
- perror("bind\n");
- exit(1);
- }
- //接收数据
- struct sockaddr_in addr_client;
- while(1)
- {
- char buf[100];
- memset(buf,100,0);
- socklen_t length = sizeof(struct sockaddr);
- fputs("等待数据。。。。\n",stdout);
- ssize_t recnum = recvfrom(sockfd, buf, 100,MSG_WAITALL, (struct sockaddr*)&addr_client,&length);
- if(recnum<0)
- {
- perror("recvfrom\n");
- exit(1);
- }
- printf("received(%d): %s\n",recnum,buf);
- if(strcmp(buf,"stop") == 0)
- {
- break;
- }
- }
- close(sockfd);
- fputs("退出成功!!\n",stdout);
- return 0;
- }
- ----------------------------
- client.c
- #include
/* See NOTES */ - #include
- #include
- #include
- #include
- #include
- #include
- #include
- int main(int argc, char** argv)
- {
- int len = sizeof(struct sockaddr);
- //创建socket
- int sockfd = socket(AF_INET, SOCK_DGRAM,0);
- if(sockfd == -1)
- {
- perror("socket\n");
- exit(1);
- }
- //将addr地址与socket绑定在一起
- //初始化地址
- struct sockaddr_in addr;
- addr.sin_family = AF_INET;
- addr.sin_port = htons(4444);
- addr.sin_addr.s_addr = inet_addr("127.0.0.1");
- memset(addr.sin_zero,8,0);
- while(1)
- {
- char buf[100];
- memset(buf,100,0);
- fputs("请输入内容:\n",stdout);
- //存在scanf字符串空格问题
- scanf("%s",buf);
- fputs("确认发送内容为:\n",stdout);
- fputs(buf,stdout);
- printf("\n");
- sendto(sockfd, buf, 100, 0, (struct sockaddr*)&addr, len);
- fputs("确认发送完成\n",stdout);
- }
- return 0;
- }
- ----------------------------
- makefile
- .PHONY: all clean
- all:server client
- server:server.c
- gcc -o server server.c -Wall
- client:client.c
- gcc -o client client.c -Wall
- clean:
- rm -f *.o client server *~
创新互联专注为客户提供全方位的互联网综合服务,包含不限于成都做网站、网站建设、青川网络推广、成都微信小程序、青川网络营销、青川企业策划、青川品牌公关、搜索引擎seo、人物专访、企业宣传片、企业代运营等,从售前售中售后,我们都将竭诚为您服务,您的肯定,是我们最大的嘉奖;创新互联为所有大学生创业者提供青川建站搭建服务,24小时服务热线:028-86922220,官方网址:www.cdcxhl.com
售后响应及时
7×24小时客服热线数据备份
更安全、更高效、更稳定价格公道精准
项目经理精准报价不弄虚作假合作无风险
重合同讲信誉,无效全额退款