- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #define N 100
- int main()
- {
- int sockfd;
- struct sockaddr_in servaddr;
- struct sockaddr_in cliaddr;
- socklen_t clilen;
- char msg[N];
- int ret;
- int i;
- int n;
- int opt = 1;
- sockfd = socket(AF_INET,SOCK_DGRAM,0);
- if(sockfd == -1)
- {
- printf("socket errpor!\n");
- exit(-1);
- }
- ret = setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));
- if(ret == -1)
- {
- printf("setsockopt error!\n");
- exit(-1);
- }
- bzero(&servaddr,sizeof(servaddr));
- servaddr.sin_family = AF_INET;
- servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
- servaddr.sin_port = htons(8000);
- ret = bind(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr));
- if(ret == -1)
- {
- printf("bind error!\n");
- exit(-1);
- }
- clilen = sizeof(cliaddr);
- while(1)
- {
- n = recvfrom(sockfd,msg,N,0,(struct sockaddr*)&cliaddr,&clilen);
- if(n == 0)
- {
- printf("client is closed!\n");
- break;
- }
- msg[n] = '\0';
- printf("recv:%s",msg);
- for(i = 0; i < n; i++)
- {
- if(msg[i] >= 'a' && msg[i] <= 'z')
- {
- msg[i] -= 32;
- }
- }
- printf("send:%s",msg);
- sendto(sockfd,msg,n,0,(struct sockaddr*)&cliaddr,sizeof(cliaddr));
- }
- close(sockfd);
- return 0;
- }
用套接字实现UDP通信
最新推荐文章于 2022-09-26 22:04:15 发布