KEMBAR78
Server2 C | PDF
0% found this document useful (0 votes)
2 views2 pages

Server2 C

The document is a C program for a TCP server that listens on port 9090. It accepts client connections, receives a file request, and attempts to send the requested file's content back to the client. If the file is not found, it sends a 'File not found' message to the client.

Uploaded by

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

Server2 C

The document is a C program for a TCP server that listens on port 9090. It accepts client connections, receives a file request, and attempts to send the requested file's content back to the client. If the file is not found, it sends a 'File not found' message to the client.

Uploaded by

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

// server2.

c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define PORT2 9090


#define BUF_SIZE 1024

int main() {
int sockfd, new_sock;
struct sockaddr_in server_addr, client_addr;
char buffer[BUF_SIZE];
socklen_t addr_size;

// Create socket
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) { perror("Socket error"); exit(1); }

server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT2);
server_addr.sin_addr.s_addr = INADDR_ANY;

// Bind
if (bind(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
perror("Bind error");
exit(1);
}

// Listen
if (listen(sockfd, 5) < 0) {
perror("Listen error");
exit(1);
}

printf("Server2 listening on port %d...\n", PORT2);

while (1) {
addr_size = sizeof(client_addr);
new_sock = accept(sockfd, (struct sockaddr*)&client_addr, &addr_size);
if (new_sock < 0) { perror("Accept error"); continue; }

memset(buffer, 0, BUF_SIZE);
recv(new_sock, buffer, BUF_SIZE, 0);
printf("Server2: Request received for file: %s\n", buffer);

// Try to open file


FILE *fp = fopen(buffer, "r");
if (fp != NULL) {
char data[BUF_SIZE];
fread(data, 1, BUF_SIZE, fp);
send(new_sock, data, strlen(data), 0);
fclose(fp);
printf("Server2: Sent file to Server1.\n");
} else {
char *msg = "File not found\n";
send(new_sock, msg, strlen(msg), 0);
printf("Server2: File not found.\n");
}

close(new_sock);
}

close(sockfd);
return 0;
}

You might also like