在Linux中,数据的发送和接收通常使用套接字(socket)来实现。以下是一个简单的示例代码,演示了如何创建一个UDP套接字并发送和接收数据:
发送数据:
#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 8888int main(){ int sockfd; struct sockaddr_in servaddr;
char sendline[] = "Hello, Server!"; char recvline[1024]; // 创建套接字
sockfd = socket(AF_INET, SOCK_DGRAM, 0); // 设置服务器地址结构体
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(PORT);
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); // 发送数据
sendto(sockfd, (const char *)sendline, strlen(sendline),
MSG_CONFIRM, (const struct sockaddr *)&servaddr, sizeof(servaddr));
close(sockfd); return 0;
}
接收数据:
#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 8888int main(){ int sockfd; struct sockaddr_in servaddr, cliaddr;
char buffer[1024]; // 创建套接字
sockfd = socket(AF_INET, SOCK_DGRAM, 0); // 设置服务器地址结构体
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(PORT);
servaddr.sin_addr.s_addr = INADDR_ANY; // 绑定套接字到端口
bind(sockfd, (const struct sockaddr *)&servaddr, sizeof(servaddr)); socklen_t len; int n; // 接收数据
n = recvfrom(sockfd, (char *)buffer, 1024,
MSG_WAITALL, (struct sockaddr *)&cliaddr,
&len);
buffer[n] = '