UDP文件传输c语言代码
时间: 2023-05-15 20:06:09 浏览: 235
以下是一个简单的UDP文件传输的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
int main(int argc, char *argv[]) {
if (argc != 4) {
printf("Usage: %s <server_ip> <server_port> <file_path>\n", argv[0]);
return 1;
}
const char *server_ip = argv[1];
int server_port = atoi(argv[2]);
const char *file_path = argv[3];
FILE *fp = fopen(file_path, "rb");
if (fp == NULL) {
printf("Failed to open file %s\n", file_path);
return 1;
}
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
printf("Failed to create socket\n");
return 1;
}
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr(server_ip);
server_addr.sin_port = htons(server_port);
char buf[BUF_SIZE];
int len;
while ((len = fread(buf, 1, BUF_SIZE, fp)) > 0) {
sendto(sockfd, buf, len, 0, (struct sockaddr *)&server_addr, sizeof(server_addr));
}
fclose(fp);
close(sockfd);
printf("File transfer completed\n");
return 0;
}
```
注意:这只是一个简单的示例代码,实际应用中还需要考虑很多问题,比如文件分片、丢包重传、流量控制等。
阅读全文