您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
- server.c
- #include <sys/types.h> /* See NOTES */
- #include <sys/socket.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <stdio.h>
- #include <arpa/inet.h>
- #include <unistd.h>
- 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 <sys/types.h> /* See NOTES */
- #include <sys/socket.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <stdio.h>
- #include <arpa/inet.h>
- #include <unistd.h>
- 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 *~
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。