C语言socket传图片
时间: 2023-10-06 22:08:23 浏览: 80
下面是一个简单的C语言socket传输图片的示例代码:
发送端:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#define PORT 9999
#define MAXLINE 4096
int main(int argc, char *argv[]) {
int sockfd, n;
char recvline[MAXLINE], sendline[MAXLINE];
struct sockaddr_in servaddr;
if (argc != 2) {
printf("usage: ./client <IP address>\n");
exit(1);
}
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
printf("create socket error: %s(errno: %d)\n", strerror(errno), errno);
exit(1);
}
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(PORT);
if (inet_pton(AF_INET, argv[1], &servaddr.sin_addr) <= 0) {
printf("inet_pton error for %s\n", argv[1]);
exit(1);
}
if (connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0) {
printf("connect error: %s(errno: %d)\n", strerror(errno), errno);
exit(1);
}
// 读取图片文件
FILE *fp;
if ((fp = fopen("test.jpg", "rb")) == NULL) {
printf("open file error: %s(errno: %d)\n", strerror(errno), errno);
exit(1);
}
// 发送文件内容
int count;
while ((count = fread(sendline, 1, MAXLINE, fp)) > 0) {
if (send(sockfd, sendline, count, 0) < 0) {
printf("send file error: %s(errno: %d)\n", strerror(errno), errno);
exit(1);
}
}
fclose(fp);
close(sockfd);
return 0;
}
```
接收端:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#define PORT 9999
#define MAXLINE 4096
int main(int argc, char *argv[]) {
int listenfd, connfd;
struct sockaddr_in servaddr;
char buff[MAXLINE];
int n;
if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
printf("create socket error: %s(errno: %d)\n", strerror(errno), errno);
exit(1);
}
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(PORT);
if (bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) == -1) {
printf("bind socket error: %s(errno: %d)\n", strerror(errno), errno);
exit(1);
}
if (listen(listenfd, 10) == -1) {
printf("listen socket error: %s(errno: %d)\n", strerror(errno), errno);
exit(1);
}
printf("waiting for client's request...\n");
if ((connfd = accept(listenfd, (struct sockaddr*)NULL, NULL)) == -1) {
printf("accept socket error: %s(errno: %d)\n", strerror(errno), errno);
exit(1);
}
// 读取文件内容
FILE *fp;
if ((fp = fopen("test.jpg", "wb")) == NULL) {
printf("open file error: %s(errno: %d)\n", strerror(errno), errno);
exit(1);
}
int count;
while ((count = recv(connfd, buff, MAXLINE, 0)) > 0) {
fwrite(buff, 1, count, fp);
}
fclose(fp);
close(connfd);
close(listenfd);
return 0;
}
```
这个例子中,发送端读取名为“test.jpg”的图片文件并将其内容发送到接收端。接收端将收到的内容写入名为“test.jpg”的文件。注意这个例子并没有考虑文件大小超过MAXLINE的情况,实际使用时需要根据情况进行修改。