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

basic c program

This document contains a C program that implements a simple TCP server. The server listens on port 8080, accepts a connection from a client, reads a message from the client, and sends a response back. It includes necessary headers and error handling for socket creation and binding.

Uploaded by

vedhamurthi39
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

basic c program

This document contains a C program that implements a simple TCP server. The server listens on port 8080, accepts a connection from a client, reads a message from the client, and sends a response back. It includes necessary headers and error handling for socket creation and binding.

Uploaded by

vedhamurthi39
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <stdio.

h>

#include <stdlib.h>

#include <string.h>

#include <netinet/in.h>

#include <unistd.h>

#define PORT 8080

int main() {

int server_fd, new_socket;

struct sockaddr_in address;

int addrlen = sizeof(address);

char buffer[1024] = {0};

char *message = "Hello from server";

server_fd = socket(AF_INET, SOCK_STREAM, 0);

if (server_fd == 0) {

perror("Socket failed");

exit(EXIT_FAILURE);

address.sin_family = AF_INET;

address.sin_addr.s_addr = INADDR_ANY;

address.sin_port = htons(PORT);

bind(server_fd, (struct sockaddr *)&address, sizeof(address));

listen(server_fd, 3);

printf("Server is waiting for a connection...\n");


new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen);

read(new_socket, buffer, 1024);

printf("Client: %s\n", buffer);

send(new_socket, message, strlen(message), 0);

printf("Message sent to client\n");

close(server_fd);

return 0;

You might also like