您好,登錄后才能下訂單哦!
- 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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。