- 客户端代码
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<sys/socket.h> #include<sys/types.h> #include<unistd.h> #include<netinet/in.h> #include <errno.h> int main(int argc, char** argv) { int socketfd = 0; struct sockaddr_in server_addr; char recvbuf[1024]; int port = 8001; int nbyte; if((socketfd = socket(AF_INET, SOCK_DGRAM, 0)) == 0){ fprintf(stderr, "socket Error:%s\n\a", strerror(errno)); exit(1); } bzero(&server_addr, sizeof(struct sockaddr_in)); server_addr.sin_family = AF_INET; server_addr.sin_port = htons(port); server_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); int len = sizeof(struct sockaddr_in); while(1){ if(sendto(socketfd, "Hello Fredric", strlen("Hello Fredric"), 0, (struct sockaddr *)&server_addr, len) == -1){ fprintf(stderr, "sendto Error:%s\n\a", strerror(errno)); close(socketfd); exit(1); } if((nbyte = recvfrom(socketfd, recvbuf, 1024, 0, (struct sockaddr *)&server_addr, &len)) == -1){ fprintf(stderr, "recvfrom Error:%s\n\a", strerror(errno)); close(socketfd); exit(1); } recvbuf[nbyte] = '\0'; printf("recv data is:%s\n",recvbuf); } close(socketfd); exit(0); }
- 服务器端代码
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<sys/socket.h> #include<sys/types.h> #include<unistd.h> #include<netinet/in.h> #include <errno.h> int main(int argc, char** argv){ int socketfd = 0; struct sockaddr_in server_addr; char recvbuf[1024]; char sendbuf[1024]; int port = 8001; int nbyte; if((socketfd = socket(AF_INET, SOCK_DGRAM, 0)) == 0){ fprintf(stderr, "socket Error:%s\n\a", strerror(errno)); exit(1); } bzero(&server_addr, sizeof(struct sockaddr_in)); server_addr.sin_family = AF_INET; server_addr.sin_port = htons(port); server_addr.sin_addr.s_addr = htonl(INADDR_ANY); if((bind(socketfd, &server_addr, sizeof(server_addr))) == -1){ fprintf(stderr, "bind Error:%s\n\a", strerror(errno)); exit(1); } int len = sizeof(struct sockaddr_in); while(1){ if((nbyte = recvfrom(socketfd, recvbuf, 1024, 0, (struct sockaddr*)&server_addr, &len)) == -1){ fprintf(stderr, "recvfrom Error:%s\n\a", strerror(errno)); close(socketfd); exit(1); } recvbuf[nbyte] = '\0'; printf("recv data is:%s\n",recvbuf); printf("Input:"); scanf("%s", sendbuf); if((nbyte = sendto(socketfd, sendbuf, sizeof(sendbuf), 0, (struct sockaddr*)&server_addr, len)) == -1){ fprintf(stderr, "sendto Error:%s\n\a", strerror(errno)); close(socketfd); exit(1); } } close(socketfd); exit(0); }
来源:https://www.cnblogs.com/Fredric-2013/p/4549315.html