windows环境下#include <stdio.h> #include <stdlib.h> #include <string.h> #include<windows.h> #include <WinSock2.h> #define PORT 8888 int main(int argc, char const *argv[]) { int sock = 0, valread; struct sockaddr_in serv_addr; char buffer[1024] = {0}; char filename[100] = {0}; FILE *fp; // 创建 socket 文件描述符 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) { printf("\n Socket creation error \n"); return -1; } // 初始化地址结构体 memset(&serv_addr, '0', sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(PORT); // 将 IP 地址从字符串转换为二进制格式 if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) { printf("\n Invalid address/ Address not supported \n"); return -1; } // 连接服务器 if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { printf("\n Connection Failed \n"); return -1; } // 发送文件名 printf("Enter filename: "); scanf("%s", filename); send(sock, filename, strlen(filename), 0); // 打开文件 fp = fopen(filename, "rb"); if (fp == NULL) { perror("fopen failed"); exit(EXIT_FAILURE); } // 发送文件内容 while (!feof(fp)) { valread = fread(buffer, sizeof(char), sizeof(buffer), fp); send(sock, buffer, valread, 0); memset(buffer, 0, sizeof(buffer)); } // 关闭文件和 socket fclose(fp); close(sock); return 0;}该怎么写
时间: 2023-06-24 21:07:46 浏览: 208
这是一个基于 Socket 实现文件传输的客户端程序,需要连接到一个运行在本地的服务器。以下是完整代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winsock2.h>
#define PORT 8888
int main(int argc, char const *argv[])
{
WSADATA wsa;
SOCKET sock = INVALID_SOCKET;
struct sockaddr_in serv_addr;
char buffer[1024] = {0};
char filename[100] = {0};
FILE *fp;
int valread;
// 初始化 Winsock 库
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
{
printf("WSAStartup failed. Error Code : %d\n", WSAGetLastError());
return -1;
}
// 创建 socket 文件描述符
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
{
printf("Socket creation error. Error Code : %d\n", WSAGetLastError());
return -1;
}
// 初始化地址结构体
memset(&serv_addr, '0', sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
// 将 IP 地址从字符串转换为二进制格式
if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0)
{
printf("Invalid address/ Address not supported.\n");
return -1;
}
// 连接服务器
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("Connection failed.\n");
return -1;
}
// 发送文件名
printf("Enter filename: ");
scanf("%s", filename);
send(sock, filename, strlen(filename), 0);
// 打开文件
fp = fopen(filename, "rb");
if (fp == NULL)
{
perror("fopen failed");
exit(EXIT_FAILURE);
}
// 发送文件内容
while (!feof(fp))
{
valread = fread(buffer, sizeof(char), sizeof(buffer), fp);
send(sock, buffer, valread, 0);
memset(buffer, 0, sizeof(buffer));
}
// 关闭文件和 socket
fclose(fp);
closesocket(sock);
// 清理 Winsock 库
WSACleanup();
return 0;
}
```
需要注意的是,在 Windows 环境下使用 Socket 编程需要先调用 `WSAStartup()` 函数来初始化 Winsock 库,并在程序结束时调用 `WSACleanup()` 函数来清理 Winsock 库。此外,Windows 下使用的是 `closesocket()` 函数来关闭 socket,而不是 `close()` 函数。
阅读全文