在Linux系统下进行UDP编程主要涉及到socket编程接口。以下是一个简单的UDP客户端和服务器的编程实例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#define BUFLEN 512 // 缓冲区大小
#define PORT 8888 // 监听端口
int main() {
struct sockaddr_in si_me, si_other;
int s, slen = sizeof(si_other);
char buf[BUFLEN];
// 创建UDP socket
if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
perror("socket");
exit(EXIT_FAILURE);
}
// 绑定socket到端口
memset((char *)&si_me, 0, sizeof(si_me));
si_me.sin_family = AF_INET;
si_me.sin_port = htons(PORT);
si_me.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(s, (struct sockaddr*)&si_me, sizeof(si_me)) == -1) {
perror("bind");
close(s);
exit(EXIT_FAILURE);
}
// 接收数据
while (1) {
memset(buf, 0, BUFLEN);
if (recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *)&si_other, &slen) == -1) {
perror("recvfrom()");
exit(EXIT_FAILURE);
}
printf("Received packet from %s:%d\nData: %s\n", inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port), buf);
// 发送回复
sendto(s, buf, strlen(buf), 0, (struct sockaddr*)&si_other, slen);
}
close(s);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#define SERVER "127.0.0.1" // 服务器IP地址
#define BUFLEN 512 // 缓冲区大小
#define PORT 8888 // 服务器端口
int main(int argc, char *argv[]) {
struct sockaddr_in si_other;
int s, slen = sizeof(si_other);
char buf[BUFLEN];
char message[BUFLEN];
if (argc != 2) {
fprintf(stderr, "Usage: %s <message>\n", argv[0]);
exit(1);
}
// 创建UDP socket
if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
perror("socket");
exit(EXIT_FAILURE);
}
// 设置服务器地址
memset((char *)&si_other, 0, sizeof(si_other));
si_other.sin_family = AF_INET;
si_other.sin_port = htons(PORT);
if (inet_aton(SERVER, &si_other.sin_addr) == 0) {
fprintf(stderr, "inet_aton() failed\n");
exit(1);
}
// 发送消息
strcpy(message, argv[1]);
if (sendto(s, message, strlen(message), 0, (struct sockaddr*)&si_other, slen) == -1) {
perror("sendto()");
exit(EXIT_FAILURE);
}
// 接收回复
if (recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *)&si_other, &slen) == -1) {
perror("recvfrom()");
exit(EXIT_FAILURE);
}
printf("Received reply: %s\n", buf);
close(s);
return 0;
}
UDP(User Datagram Protocol)是一种无连接的传输层协议,它提供了一种不可靠的服务,不保证数据包的顺序和可靠性,但具有较低的延迟和较小的开销。
以上是Linux系统下UDP编程的基础概念、优势、类型、应用场景以及可能遇到的问题和解决方法。希望这些信息对你有所帮助。
腾讯云数据库TDSQL训练营
2022OpenCloudOS社区开放日
云+社区技术沙龙[第14期]
腾讯云数据库TDSQL训练营
腾讯云数据库TDSQL(PostgreSQL版)训练营
腾讯云数据库TDSQL训练营
腾讯技术创作特训营第二季
企业创新在线学堂
云原生正发声
T-Day
领取专属 10元无门槛券
手把手带您无忧上云