服务器端:
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <string.h>
- #include <pthread.h>
- int main()//service code
- {
- int fd;
- int sockfd;
- struct sockaddr_in myaddr, clientaddr;
- char buf[100]="";
- int len = sizeof(clientaddr);
- bzero(&clientaddr, sizeof(clientaddr));
- bzero(&myaddr, sizeof(myaddr));
- myaddr.sin_family = AF_INET;
- myaddr.sin_port = htons(2222);
- myaddr.sin_addr.s_addr = inet_addr("127.0.0.1");//设定本机的回环地址
- if((sockfd = socket(AF_INET, SOCK_DGRAM, 0))<0)
- {
- perror("socket");
- exit(1);
- }
- if(bind(sockfd, (struct sockaddr*)&myaddr, sizeof(struct sockaddr))!=0)
- {
- perror("bind");
- exit(1);
- }
- recvfrom(sockfd, buf, 100, 0, (struct sockaddr*)&clientaddr, &len);
- printf("recv:%s\n",buf);
- sendto(sockfd, "OK!", 3, 0, (struct sockaddr*)&clientaddr, len);
- return fd;
- }
-
客户端:
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <string.h>
- #include <pthread.h>
- int main()//client code
- {
- int fd;
- int sockfd;
- struct sockaddr_in myaddr, clientaddr;
- char buf[100]="";
- int len = sizeof(clientaddr);
- bzero(&clientaddr, sizeof(clientaddr));
- bzero(&myaddr, sizeof(myaddr));
- myaddr.sin_family = AF_INET;
- myaddr.sin_port = htons(2222);
- myaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
- if((sockfd = socket(AF_INET, SOCK_DGRAM, 0))<0)
- {
- perror("socket");
- exit(1);
- }
- sendto(sockfd, "hello!", 10, 0, (struct sockaddr*)&myaddr, len);
- recvfrom(sockfd, buf, 100, 0, (struct sockaddr*)&myaddr, &len);
- printf("recv:%s\n",buf);
- return fd;
- }
转载于:https://blog.51cto.com/dong4716138/1125834