- 服務器端
服務器不用綁定地址,他只須要進行綁定相應的監聽端口便可。服務器
#include <sys/types.h> #include <sys/socket.h> #include<pthread.h> #include <netinet/in.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <stdlib.h> #include<arpa/inet.h> //#include<cstdlib.h> char* PORT="8899"; //server's port char* SOCKET_SERVER_IP="192.168.1.105"; // int main() { printf("Welcome! This is a UDP server, I can only received message from client and reply with same message\n"); struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(atoi(PORT)); addr.sin_addr.s_addr = htonl(INADDR_ANY); int sock; if ( (sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { perror("socket"); exit(1); } //port bind to server if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) { perror("bind"); exit(1); } char buff[512]; struct sockaddr_in clientAddr; memset(&clientAddr,0,sizeof(clientAddr)); size_t n; socklen_t len = sizeof(clientAddr); while (1) { n = recvfrom(sock, buff, 511, 0, (struct sockaddr*)&clientAddr, &len); if (n>0) { buff[n] = 0; printf("%s %u says: %s\n", inet_ntoa(clientAddr.sin_addr), ntohs(clientAddr.sin_port), buff); n = sendto(sock, buff, n, 0, (struct sockaddr *)&clientAddr, sizeof(clientAddr)); if (n < 0) { perror("sendto"); break; } } else { perror("recv"); break; } } return 0; }
- 客戶端
客戶端進行(服務器)地址和端口與本身建立的套接字綁定。網絡
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <netdb.h> #include <sys/types.h> #include <netinet/in.h> #include <sys/socket.h> #include <arpa/inet.h> #include <unistd.h> int CLIENT_PORT=8899; char* CLIENT_IP="192.168.1.105"; int main() { /*1 建立socket*/ int socket_fd = socket(AF_INET, SOCK_DGRAM, 0); if(socket_fd == -1) { perror("udp_socket建立失敗!退出客戶端系統"); exit(-1); } /*2 準備地址:須要設計一個地址結構體用於存儲sock地址結構 addr 的數據*/ struct sockaddr_in addr; //設置family地址格式類型 addr.sin_family = AF_INET; /*綁定地址和端口; * htons是一個轉換函數,由於操做系統中的字節排序和網絡中字節排序中的字節流順序是不統一的,因此在進行由系統轉化爲網絡傳送。 * htons->host to net short 由主機轉換爲網絡順序。 */ addr.sin_port = htons(CLIENT_PORT); addr.sin_addr.s_addr = inet_addr(CLIENT_IP); if (addr.sin_addr.s_addr == INADDR_NONE) { printf("Incorrect ip address!"); close(socket_fd); exit(1); } /*3 進行通訊*/ char buff[512]; socklen_t len = sizeof(addr); while (1) { scanf("%s",buff); int n; //addr是sockaddr_in類型須要進行強制類型轉換 n = sendto(socket_fd, buff, strlen(buff), 0, (struct sockaddr *)&addr, sizeof(addr)); if (n < 0)//發送了n個字節 { perror("sendto"); close(socket_fd); break; } memset(buff,0,sizeof (buff)); n = recvfrom(socket_fd, buff, 512, 0, (struct sockaddr *)&addr, &len); if (n>0) { buff[n] = 0; printf("received:"); puts(buff); } else if (n==0) { printf("server closed\n"); close(socket_fd); break; } else if (n == -1) { perror("recvfrom"); close(socket_fd); break; } } return 0; }