Server reading a command line argument passed to the client - c

I want to pass an argument to the client, send it to the server, then print it there, currently I am getting no output.
Current codes:
Client:
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include<errno.h>
#define PORT 8080
int main(int argc, char const *argv[])
{
int sock = 0, valread;
struct sockaddr_in serv_addr;
char buffer[1024] = {0};
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\n Socket creation error \n");
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr)<=0)
{
printf("Invalid address \n");
return -1;
}
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("Connection Failed \n");
return -1;
}
int i;
if(argc>=2){
for(i=0; i<argc; i++) {
if(write( sock, argv[i], 1 + strlen( argv[i] ))<0)
{
printf("Error in write() ! %s\n", strerror(errno));
return -1;
}
}
}
return 0;
}
Server:
#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#include<errno.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";
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0)
{
perror("socket failed");
exit(EXIT_FAILURE);
}
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR , &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 );
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);
puts("The client sent the value: ");
int* valuerec=(int *)buffer;
int val2=*valuerec;
return 0;
}
Currently I am getting no number as an output, how can I do fix this? Ultimately my goal would be to send and receive multiple arguments but for now I am only sending one.

the following proposed code:
cleanly compiles
performs the desired server functionality
properly checks for errors
properly handles errors
uses an appropriate signature for function: main()
does not include header files those contents are not used
uses meaningful names rather than 'magic' numbers
uses appropriate horizontal spacing for readability
properly NUL terminates the input buffer
note the function: atoi() does not indicate when an error occurs, so suggest using strtol() instead
properly cleared the struct address before setting some of the fields
and now the proposed code:
#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#define PORT 8080
#define MAX_BUFFER_LEN 1025
int main( void )
{
int server_fd, new_socket;
struct sockaddr_in address;
if ( ( server_fd = socket( AF_INET, SOCK_STREAM, 0 ) ) < 0 )
{
perror( "socket failed" );
exit( EXIT_FAILURE );
}
int opt = 1;
if ( setsockopt( server_fd, SOL_SOCKET, SO_REUSEADDR , &opt, sizeof(opt) ) )
{
perror("setsockopt failed" );
exit( EXIT_FAILURE );
}
memset( &address, 0, sizeof( address ) );
address.sin_family = AF_INET;
address.sin_addr.s_addr = htonl( INADDR_ANY );
address.sin_port = htons( PORT );
socklen_t addrlen = sizeof( address );
if ( bind( server_fd, (struct sockaddr *)&address, addrlen ) < 0 )
{
perror( "bind failed" );
exit( EXIT_FAILURE );
}
if ( listen( server_fd, 3 ) < 0 )
{
perror( "listen failed" );
exit( EXIT_FAILURE );
}
if (( new_socket = accept(server_fd, (struct sockaddr *)&address,
(socklen_t*)&addrlen ) ) < 0 )
{
perror( "accept failed" );
exit( EXIT_FAILURE );
}
ssize_t valread;
char buffer[ MAX_BUFFER_LEN ] = { 0 };
if( ( valread = read( new_socket, buffer, MAX_BUFFER_LEN -1 ) ) > 0 )
{ // then read successful
buffer[ valread ] = '\0';
int value = atoi( buffer );
printf( "The client sent the string: %s, which began with integer value: %d\n", buffer, value );
}
else if( ! valread )
{
puts( "client hungup" );
}
else
{
perror( "read failed" );
}
return 0;
}

Related

Sending command line arguments from client to server

I want to input arguments from the command line to the client and make the server receive them and print them.
current codes:
Client:
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#define PORT 8080
int main(int argc, char const *argv[])
{
int sock = 0, valread;
struct sockaddr_in serv_addr;
char buffer[1024] = {0};
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\n Socket creation error \n");
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr)<=0)
{
printf(Invalid address\n");
return -1;
}
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("Connection Failed \n");
return -1;
}
if(argc>=2){
int i, numb;
for(i=0; i<argc; i++) {
send(sock , &argv[i] , 10000 , 0 );
}
}
return 0;
}
Server:
#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};
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0)
{
perror("socket failed");
exit(EXIT_FAILURE);
}
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR , &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 );
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);
puts("The client sent the values: ");
if(argc>=2){
int i;
for(i=0; i<argc; i++) {
int* valuerec=(int *)buffer;
int val2=*valuerec;
printf("%d\n", val2);
puts(" ");
}
}
return 0;
}
I tried doing it multiple ways such as using atoi before sending but all resulted in no output of numbers, any help on how I can establish this?
I am aware I didn't include the server libraries in this post but that is just to make it shorter.

Socket Program in C++ to send a message back and forth between server and client

I am Trying to make a C/C++ Project using Socket Programming.
For this I need Client and Server to sent a index of array back and forth to each other.
So Client will next a index of array and server will sent another index of array until the game is over. (Yeah we are trying to make a game.)
I have written (copied from gfg) code for it but it's not working properly.
The Server for some reason didn't receive the second message. So, We kind of stuck in a deadlock.
Any idea what I did wrong??
Server.cpp
#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#define PORT 8080
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int server_fd, new_socket, valread;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[1024] = {0};
char *msg = "0";
// 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);
}
int i=0;
while(i<10)
{
valread = read( new_socket , buffer, 1024);
printf("%s\n",buffer );
send(new_socket , msg , strlen(msg) , 0 );
printf("Message sent\n");
i++;
}
return 0;
}
Client.cpp
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#define PORT 8080
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int sock = 0, valread;
struct sockaddr_in serv_addr;
char *msg="0";
char buffer[1024] = {0};
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\n Socket creation error \n");
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
// Convert IPv4 and IPv6 addresses from text to binary form
if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr)<=0)
{
printf("\nInvalid address/ Address not supported \n");
return -1;
}
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("\nConnection Failed \n");
return -1;
}
int i=0;
while(i<10)
{
send(sock , msg , strlen(msg) , 0 );
printf("Message sent\n");
valread = read( sock , buffer, 1024);
printf("%s\n",buffer );
i++;
}
return 0;
}
Edit: It will be really nice if somebody can tell me how to sent an integer instead of a string.

Socket programming in c connection failed

Trying to practice socket programming in c. Been hitting an error of Connection Failedbut not sure why. I included both the server and client code. I believe the problem is with connect.
Also, i run the client first then run the server. Is that the right way to compile it?
//CLIENT
#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[])
{
struct sockaddr_in address;
int sock = 0, valread;
struct sockaddr_in serv_addr;
char *hello = "Hello from client";
char buffer[1024] = {0};
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\n Socket creation error \n");
return -1;
}
memset(&serv_addr, '0', sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
// Convert IPv4 and IPv6 addresses from text to binary form
if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr)<=0)
{
printf("\nInvalid address/ Address not supported \n");
return -1;
}
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("\nConnection Failed \n");
return -1;
}
send(sock , hello , strlen(hello) , 0 );
printf("Hello message sent\n");
valread = read( sock , buffer, 1024);
printf("%s\n",buffer );
return 0;
}
//SERVER
#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;
}

How to prevent Socket server to disconnect

I wrote a code about sockets and I cannot prevent the server to close when the client sends a message or when the client do a CTRL + C
The server goes off.
Server.c:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/time.h>
#define PORT 8888
#define BACKLOG 10
#define LOOP(i, n) for((i) = 0; (i) < (n); (i)++)
#define BUFFSIZE 6500
int create_fd( struct sockaddr_in *server );
int bind_fd ( struct sockaddr_in *server, int servSocket );
int list_fd( int servSocket );
int accept_fd( struct sockaddr_in *server, int servSocket );
int select_fd ( fd_set *readfds, int max_sd );
ssize_t send_fd( int new_fd, const char *const msg );
int main( void ){
const char msg[BUFFSIZE] = "Server is On\n";
char recive[BUFFSIZE];
int servSocket ,clientSocket ,i ,sd;
int client_socket_max[30] = { 0 } , max_clients = 30;
int max_sd;
ssize_t valread;
struct sockaddr_in server;
for (i = 0; i < max_clients; i++)
{
client_socket_max[i] = 0;
}
//set of socket descriptors
fd_set readfds;
size_t addr_size = sizeof(server);
//create
servSocket = create_fd( &server );
//bind the socket to localhost port 8888
bind_fd(&server, servSocket );
//listen the socket to localhost port 8888
printf("\tServer is On\nListener on port %d \n", PORT);
list_fd( servSocket );
//accept the incoming connection
printf( "\n\tWaiting for connections ...\n" );
while(1){
//clear the socket set
FD_ZERO(&readfds);
//add master socket to set
FD_SET(servSocket, &readfds);
max_sd = servSocket;
//add child sockets to set
LOOP( i, max_clients ){
//socket descriptor
sd = client_socket_max[i];
//if valid socket descriptor then add to read list
if(sd > 0){
FD_SET( sd , &readfds);
}
//highest file descriptor number, need it for the select function
if(sd > max_sd){
max_sd = sd;
}
}
//wait for an activity on one of the sockets , timeout is NULL , so wait indefinitely
select_fd( &readfds, max_sd );
//select( max_sd + 1 , &readfds , NULL , NULL , NULL);
//If something happened on the master socket , then its an incoming connection
if ( FD_ISSET( servSocket, &readfds ) ){
clientSocket = accept_fd( &server, servSocket );
//inform user of socket number - used in send and receive commands
printf("New connection , socket fd is %d , ip is : %s , port : %d \n" , clientSocket , inet_ntoa(server.sin_addr) , ntohs(server.sin_port));
//send new connection greeting msg
send_fd( clientSocket, msg );
/*if( send(clientSocket, msg, strlen(msg), 0) != (long int)strlen(msg) ){
perror("send");
}*/
puts("Welcome msg sent successfully");
//add new socket to array of sockets
LOOP( i, max_clients ){
//if position is empty
if( client_socket_max[i] == 0 ){
client_socket_max[i] = clientSocket;
printf("Adding to list of sockets as %d\n" , i);
break;
}
}
}
//else its some IO operation on some other socket :)
LOOP( i, max_clients ){
sd = client_socket_max[i];
if (FD_ISSET( sd , &readfds)){
//Check if it was for closing , and also read the incoming msg
if (( valread = read( sd , recive, 1024)) == 0){
//Somebody disconnected , get his details and print
getpeername(sd , (struct sockaddr*)&server , (socklen_t*)&addr_size);
printf("Host disconnected , ip %s , port %d \n" , inet_ntoa(server.sin_addr) , ntohs(server.sin_port));
//Close the socket and mark as 0 in list for reuse
close( sd );
client_socket_max[i] = 0;
}else{//Echo back the msg that came in
//set the string terminating NULL byte on the end of the data read
recive[valread] = '\0';
send(sd , recive , strlen(recive) , 0 );
}
}
}
}
close( servSocket );
}
int create_fd( struct sockaddr_in *server ){
int opt = 1;
int servSocket = socket(AF_INET , SOCK_STREAM , 0);
if (servSocket == -1 ){
printf("Error, socket()\n");
fprintf(stderr, "socket: %s (%d)\n", strerror(errno), errno);
exit ( EXIT_FAILURE );
}
//set master socket to allow multiple connections , this is just a good habit, it will work without this
if( setsockopt(servSocket, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(opt)) < 0 ){
perror("setsockopt");
exit(EXIT_FAILURE);
}
//type of socket created
server->sin_family = AF_INET;
server->sin_addr.s_addr = INADDR_ANY;
server->sin_port = htons( PORT );
//printf("socket() \tOK\n");
return servSocket;
}
int bind_fd ( struct sockaddr_in *server, int servSocket ){
int bindfd = bind( servSocket, (struct sockaddr *)server, sizeof(*server) );
if (bindfd == -1 ){
printf("Error, bind(), check line 34\n");
fprintf(stderr, "bind: %s (%d)\n", strerror(errno), errno);
exit ( EXIT_FAILURE );
}else{
//printf("bind() \t\tOK\n");
return bindfd;
}
}
int list_fd( int servSocket ){
int listfd = listen(servSocket, BACKLOG);
if (listfd == -1 ){
printf("Error, listen()\n");
fprintf(stderr, "listen: %s (%d)\n", strerror(errno), errno);
exit ( EXIT_FAILURE );
}else{
//printf("listen() \tOK\n");
return listfd;
}
}
int accept_fd( struct sockaddr_in *server, int servSocket ){
int new_fd;
socklen_t addr_size = sizeof( server );
new_fd = accept(servSocket, (struct sockaddr *)server, (socklen_t*)&addr_size);
if (new_fd == -1 ){
printf("Error, accept()\n");
fprintf(stderr, "accept: %s (%d)\n", strerror(errno), errno);
exit ( EXIT_FAILURE );
}else{
//printf("accept() \tOK\n");
return new_fd;
}
}
int select_fd ( fd_set *readfds, int max_sd ){
int activity = select( max_sd + 1 , readfds , NULL , NULL , NULL);
if ((activity < 0) && (errno!=EINTR)){
printf("select error");
exit ( EXIT_FAILURE );
}else{
return activity;
}
}
ssize_t send_fd( int new_fd, const char *const msg ){
size_t len = strlen(msg);
ssize_t sendfd;
sendfd = send( new_fd, msg, len, 0 );
if (sendfd == -1 ){
printf("Error, write()\n");
fprintf(stderr, "recv: %s (%d)\n", strerror(errno), errno);
exit ( EXIT_FAILURE );
}else{
printf("write() \tOK\n");
printf("Client sent:\t%s", msg );
return sendfd;
}
}
Client.c:
#include <stdio.h>
#include <string.h> //strlen
#include <stdlib.h>
#include <errno.h>
#include <unistd.h> //close
#include <arpa/inet.h> //close
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/time.h> //FD_SET, FD_ISSET, FD_ZERO macros
#define PORT 8888
#define BUFFSIZE 6500
int create_fd( struct sockaddr_in server );
int connect_fd( const int servSocket, struct sockaddr_in *server );
int opt = 1;
int main ( void ){
struct sockaddr_in server;
char recivemsg[BUFFSIZE];
char sendmsg[BUFFSIZE];
memset( recivemsg, 0, sizeof(*recivemsg) );
memset( sendmsg, 0, sizeof(*sendmsg) );
int servSocket = socket(AF_INET , SOCK_STREAM , 0);
if (servSocket == -1 ){
printf("Error, socket()\n");
fprintf(stderr, "socket: %s (%d)\n", strerror(errno), errno);
exit ( EXIT_FAILURE );
}
//set master socket to allow multiple connections , this is just a good habit, it will work without this
if( setsockopt(servSocket, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(opt)) < 0 ){
perror("setsockopt");
exit(EXIT_FAILURE);
}
//type of socket created
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons( PORT );
if ( ( connect( servSocket, ( struct sockaddr* )&server, sizeof( server ) ) ) < 0 ){
printf("Error, connect()\n");
fprintf(stderr, "connect: %s (%d)\n", strerror(errno), errno);
exit( EXIT_FAILURE );
}
if ( recv( servSocket, recivemsg, sizeof ( recivemsg ), 0 ) < 0 ){
printf("Error, recv()\n");
fprintf(stderr, "recv: %s (%d)\n", strerror(errno), errno);
exit( EXIT_FAILURE );
}
printf("Send a msg to the Server:> ");
fgets(sendmsg, BUFFSIZE, stdin );
if ( send( servSocket, sendmsg, sizeof ( sendmsg ), 0 ) < 0 ){
printf("Error, send()\n");
fprintf(stderr, "send: %s (%d)\n", strerror(errno), errno);
exit( EXIT_FAILURE );
}
close( servSocket );
}
There are a few problems with the code that together could lead to premature exits from your server program.
The most important is that you don't check for errors from either your read or send calls.
If the read call fails it will return -1 which you don't check for (and which will lead to you using -1 as index into your array receive, which is out of bounds and lead to undefined behavior). That will in turn lead to you calling send with a broken connection, which will cause the operating system to send a SIGPIPE signal to your process.
The default behavior of SIGPIPE is to terminate the process.
The usual way to handle this is to ignore the SIGPIPE signal, as then send would return with an error (it returns -1 with errno set to EPIPE) that you should handle.
The common way to handle errors (from either read or send) is to simply close your end of the connection. That's because most errors are simply not recoverable.

Capture a video in raspberry pi camera model using C language

I wrote a server code as the main server for all the clients. This program is multi-threaded and waits for the clients to connect. Once all the threads are created, they wait on thread accept. Once the connection is accepted, they wait on reception of file from clients. At the end of these threads reception, all the threads join so that system is at common point. This behavior repeats after every 40 seconds.
I need to capture video frames and transferring then integrated in the code?
Server.c
// Server side C/C++ program to demonstrate Socket programming
#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#include<pthread.h> //for threading , link with lpthread
#define LISTENING_PORT 8080
#define CLIENT_COUNT 4
void * handle_new_conn(void *server_fd)
{
int valread;
char buffer[1024] = {0};
char *hello = "Hello from server";
int new_socket;
struct sockaddr_in address;
int addrlen = sizeof(address);
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons( LISTENING_PORT );
/* Accept connection from client */
if ((new_socket = accept(*((int *)server_fd),
(struct sockaddr *)&address,
(socklen_t*)&addrlen)) < 0)
{
perror("accept");
exit(EXIT_FAILURE);
}
/* Code to handle new connection */
valread = read(new_socket, buffer, 1024);
printf("%s\n", buffer);
sleep(10);
send(new_socket, hello , strlen(hello), 0);
printf("Hello message sent\n");
sleep(2);
close(new_socket);
}
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";
pthread_t thread_id[4];
int client_no = 0;
int i;
// 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( LISTENING_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, CLIENT_COUNT - 1) < 0)
{
perror("listen");
exit(EXIT_FAILURE);
}
while (1)
{
for (i=0; i < CLIENT_COUNT; i++)
{
/* Handle the accepted connection from client */
if (pthread_create(&thread_id[client_no] , NULL,
handle_new_conn, (void*) &server_fd) < 0)
{
perror("Couldn't create thread");
exit(EXIT_FAILURE);
}
client_no++;
}
client_no = 0;
for (i=0; i < CLIENT_COUNT; i++)
{
pthread_join(thread_id[client_no], NULL);
printf("Thread [%d] destroyed\n",
thread_id[client_no]);
client_no++;
}
/* Wait for the next interval to fetch the feed */
sleep(40);
}
return 0;
}
client.c
// Client side C/C++ program to demonstrate Socket programming
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#define SERVER_PORT 8080
void record_video()
{
/* Record video that has to be transmitted */
}
void handle_request(int sock)
{
char *hello = "Hello from client";
char * buffer[1024] = {0};
int valread;
printf("Client sock id: %d\n", sock);
sleep(2);
/* Connection to the server will be handled here */
send(sock , hello , strlen(hello) , 0 );
printf("Hello message sent\n");
valread = read( sock , buffer, 1024);
printf("%s\n",buffer );
close(sock);
}
int main(int argc, char const *argv[])
{
struct sockaddr_in address;
int sock = 0, valread;
struct sockaddr_in serv_addr;
char *hello = "Hello from client";
char buffer[1024] = {0};
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\n Socket creation error \n");
return -1;
}
memset(&serv_addr, '0', sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(SERVER_PORT);
// Convert IPv4 and IPv6 addresses from text to binary form
if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr)<=0)
{
printf("\nInvalid address/ Address not supported \n");
return -1;
}
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("\nConnection Failed \n");
return -1;
}
record_video();
handle_request(sock);
return 0;
}

Resources