0% found this document useful (0 votes)
5 views2 pages

Ass 1

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)
5 views2 pages

Ass 1

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 "file_to_send.txt"

int main() {

int server_fd, new_socket;

struct sockaddr_in address;

int addrlen = sizeof(address);

char buffer[BUFFER_SIZE] = {0};

FILE *file;

if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {

perror("Socket failed");

exit(EXIT_FAILURE);

address.sin_family = AF_INET;

address.sin_addr.s_addr = INADDR_ANY;

address.sin_port = htons(PORT);

if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {

perror("Bind failed");

close(server_fd);

exit(EXIT_FAILURE);

if (listen(server_fd, 3) < 0) {

perror("Listen failed");

close(server_fd);

exit(EXIT_FAILURE);

printf("Server listening on port %d...\n", PORT);

if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {

perror("Accept failed");

close(server_fd);
exit(EXIT_FAILURE);

printf("Connection accepted.\n");

file = fopen(FILE_NAME, "rb");

if (file == NULL) {

perror("File not found");

close(new_socket);

close(server_fd);

exit(EXIT_FAILURE);

int bytes_read;

while ((bytes_read = fread(buffer, sizeof(char), BUFFER_SIZE, file)) > 0) {

if (send(new_socket, buffer, bytes_read, 0) < 0) {

perror("Failed to send file data");

fclose(file);

close(new_socket);

close(server_fd);

exit(EXIT_FAILURE);

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

fclose(file);

close(new_socket);

close(server_fd);

return 0;

You might also like