0% found this document useful (0 votes)
6 views

ass2

Uploaded by

itztozx
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

ass2

Uploaded by

itztozx
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <stdio.

h>

#include <stdlib.h>

#include <string.h>

#include <unistd.h>

#include <arpa/inet.h>

#define PORT 8080

#define BUFFER_SIZE 1024

#define FILE_NAME "downloaded_file.txt"

int main() {

int sock = 0;

struct sockaddr_in server_addr;

char buffer[BUFFER_SIZE] = {0};

FILE *file;

if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {

perror("Socket creation error");

exit(EXIT_FAILURE);

server_addr.sin_family = AF_INET;

server_addr.sin_port = htons(PORT);

if (inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr) <= 0) {

perror("Invalid address");

exit(EXIT_FAILURE);

if (connect(sock, (struct sockaddr *)&server_addr, sizeof(server_addr))


< 0) {
perror("Connection failed");

exit(EXIT_FAILURE);

printf("Connected to server.\n");

file = fopen(FILE_NAME, "wb");

if (file == NULL) {

perror("File open error");

close(sock);

exit(EXIT_FAILURE);

int bytes_received;

while ((bytes_received = recv(sock, buffer, BUFFER_SIZE, 0)) > 0) {

fwrite(buffer, sizeof(char), bytes_received, file);

printf("File downloaded successfully.\n");

fclose(file);

close(sock);

return 0;

You might also like