0% found this document useful (0 votes)
7 views4 pages

C/C++ Server Socket Example Code

This C/C++ program code implements a basic server that creates a socket, binds it to port 8080, listens for incoming connections, accepts a connection, reads from the socket into a buffer, prints the buffer, sends a hello message to the client, and closes the connection.

Uploaded by

Anonymous
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)
7 views4 pages

C/C++ Server Socket Example Code

This C/C++ program code implements a basic server that creates a socket, binds it to port 8080, listens for incoming connections, accepts a connection, reads from the socket into a buffer, prints the buffer, sends a hello message to the client, and closes the connection.

Uploaded by

Anonymous
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

// Server side C/C++ program t

#include <unistd.h>

#include <stdio.h>

#include <sys/socket.h>

#include <stdlib.h>

#include <netinet/in.h>

#include <string.h>

#define PORT 8080

Int main(int argc, char const *argv[])

Int server_fd, new_socket, valread;

Struct sockaddr_in address;

Int opt = 1;

Int addrlen = sizeof(address);

Char buffer[1024] = {0};

Char *hello = “Hello from server”;

// Creating socket file descriptor

If ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0)


{

Perror(“socket failed”);

Exit(EXIT_FAILURE);

// Forcefully attaching socket to the port 8080

If (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT,

&opt, sizeof(opt)))

Perror(“setsockopt”);

Exit(EXIT_FAILURE);

Address.sin_family = AF_INET;

Address.sin_addr.s_addr = INADDR_ANY;
Address.sin_port = htons( PORT );

// Forcefully attaching socket to the port 8080

If (bind(server_fd, (struct sockaddr *)&address,

Sizeof(address))<0)

Perror(“bind failed”);

Exit(EXIT_FAILURE);

If (listen(server_fd, 3) < 0)

Perror(“listen”);

Exit(EXIT_FAILURE);

If ((new_socket = accept(server_fd, (struct sockaddr *)&address,


(socklen_t*)&addrlen))<0)

Perror(“accept”);

Exit(EXIT_FAILURE);

Valread = read( new_socket , buffer, 1024);

Printf(“%s\n”,buffer );

Send(new_socket , hello , strlen(hello) , 0 );

Printf(“Hello message sent\n”);

Return 0;

You might also like