UDP的实现代码C语言
时间: 2023-10-26 15:11:35 浏览: 79
以下是一个简单的UDP服务器和客户端的实现代码,使用C语言编写:
UDP服务器端代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#define PORT 8080
#define MAXLINE 1024
int main() {
int sockfd;
char buffer[MAXLINE];
struct sockaddr_in servaddr, cliaddr;
// 创建套接字
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
// 清空servaddr
memset(&servaddr, 0, sizeof(servaddr));
// 设置套接字地址信息
servaddr.sin_family = AF_INET; // IPv4
servaddr.sin_addr.s_addr = INADDR_ANY;
servaddr.sin_port = htons(PORT);
// 绑定套接字到本地地址
bind(sockfd, (const struct sockaddr *)&servaddr, sizeof(servaddr));
while (1) {
unsigned int len = sizeof(cliaddr);
int n = recvfrom(sockfd, (char *)buffer, MAXLINE,
MSG_WAITALL, (struct sockaddr *)&cliaddr,
&len);
buffer[n] = '\0';
printf("Client : %s\n", buffer);
sendto(sockfd, (const char *)buffer, strlen(buffer),
MSG_CONFIRM, (const struct sockaddr *)&cliaddr,
len);
printf("Message sent.\n");
}
close(sockfd);
return 0;
}
```
UDP客户端代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define PORT 8080
#define MAXLINE 1024
int main() {
int sockfd;
char buffer[MAXLINE];
char *hello = "Hello from client";
struct sockaddr_in servaddr;
// 创建套接字
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
// 清空servaddr
memset(&servaddr, 0, sizeof(servaddr));
// 设置套接字地址信息
servaddr.sin_family = AF_INET; // IPv4
servaddr.sin_port = htons(PORT);
servaddr.sin_addr.s_addr = INADDR_ANY;
int n, len;
while (1) {
printf("Enter message to send : ");
fgets(buffer, MAXLINE, stdin);
sendto(sockfd, (const char *)buffer, strlen(buffer),
MSG_CONFIRM, (const struct sockaddr *)&servaddr,
sizeof(servaddr));
printf("Message sent.\n");
n = recvfrom(sockfd, (char *)buffer, MAXLINE,
MSG_WAITALL, (struct sockaddr *)&servaddr,
&len);
buffer[n] = '\0';
printf("Server : %s\n", buffer);
}
close(sockfd);
return 0;
}
```
注意,这是一个简单的UDP实现,没有错误处理和其他的功能。在实际应用中,需要对错误和异常情况进行处理。
阅读全文