您好,登錄后才能下訂單哦!
- 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);
- //創(chuàng)建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);
- //進(jìn)行綁定
- ret = bind(sockfd, (struct sockaddr*)&addr, len);
- if(ret == -1)
- {
- perror("bind\n");
- exit(1);
- }
- //接收數(shù)據(jù)
- struct sockaddr_in addr_client;
- while(1)
- {
- char buf[100];
- memset(buf,100,0);
- socklen_t length = sizeof(struct sockaddr);
- fputs("等待數(shù)據(jù)。。。。\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);
- //創(chuàng)建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("請(qǐng)輸入內(nèi)容:\n",stdout);
- //存在scanf字符串空格問(wèn)題
- scanf("%s",buf);
- fputs("確認(rèn)發(fā)送內(nèi)容為:\n",stdout);
- fputs(buf,stdout);
- printf("\n");
- sendto(sockfd, buf, 100, 0, (struct sockaddr*)&addr, len);
- fputs("確認(rèn)發(fā)送完成\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 *~
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。