使用c++编写一个udp server和udp client
时间: 2024-05-05 19:15:43 浏览: 97
udp.rar_Server_UDP_UDP socket_c++ udp_udp client
UDP Server:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define BUF_SIZE 1024
#define PORT 8888
int main()
{
int sockfd;
struct sockaddr_in server_addr, client_addr;
socklen_t client_len;
char buf[BUF_SIZE];
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(PORT);
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
perror("socket");
exit(EXIT_FAILURE);
}
if (bind(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
perror("bind");
exit(EXIT_FAILURE);
}
while (1) {
memset(buf, 0, BUF_SIZE);
client_len = sizeof(client_addr);
if (recvfrom(sockfd, buf, BUF_SIZE, 0, (struct sockaddr *)&client_addr, &client_len) < 0) {
perror("recvfrom");
continue;
}
printf("Received message from %s:%d: %s\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port), buf);
}
close(sockfd);
return 0;
}
```
UDP Client:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define BUF_SIZE 1024
#define SERVER_IP "127.0.0.1"
#define PORT 8888
int main()
{
int sockfd;
struct sockaddr_in server_addr;
char buf[BUF_SIZE];
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr(SERVER_IP);
server_addr.sin_port = htons(PORT);
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
perror("socket");
exit(EXIT_FAILURE);
}
while (1) {
printf("Enter message: ");
fgets(buf, BUF_SIZE, stdin);
if (sendto(sockfd, buf, strlen(buf), 0, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
perror("sendto");
continue;
}
printf("Sent message to server: %s\n", buf);
}
close(sockfd);
return 0;
}
```
阅读全文