Good afternoon. I have written a basic C program to exchange text between sockets. However, I have a issue where the program hangs at the point where I send a message from the client socket. I ran the program in GDB and saw no errors, the program just hung.
My code is included below.
Code:
#include <stdio.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdbool.h>
#define MAX 80
#define PORT 3636
#define SA struct sockaddr
void server_func(int connfd)
{
char buff[MAX];
int n;
memset(buff, 0, MAX);
read(connfd, buff, sizeof(buff));
printf("From client: %s\t To client : ", buff);
const char *response = "Response from server";
write(connfd, response, strlen(response) + 1);
}
void client_func(int sockfd)
{
char buff[MAX];
int n;
memset(buff, 0, MAX);
printf("Enter the string : ");
fgets(buff, MAX, stdin);
write(sockfd, buff, strlen(buff) + 1);
memset(buff, 0, MAX);
read(sockfd, buff, sizeof(buff));
printf("From Server : %s \n", buff);
}
int client()
{
int sock_holder;
int confd;
// printf("Client called\n");
printf("Hello Client");
struct sockaddr_in svraddcli, cliadd;
sock_holder = socket(AF_INET, SOCK_STREAM, 0);
if (sock_holder == -1)
{
perror("Client Socket creation failed\n");
}
else
printf("Client Socket creation worked\n");
memset(&svraddcli, 0, sizeof(svraddcli));
svraddcli.sin_family = AF_INET;
svraddcli.sin_addr.s_addr = inet_addr("127.0.0.1");
svraddcli.sin_port = htons(PORT);
if (connect(sock_holder, (SA *)&svraddcli, sizeof(svraddcli)) != 0)
{
printf("Connection with server failed \n");
}
else
printf("Connected to server\n");
client_func(confd);
// close(sock_holder);
return 0;
}
int main()
{
int sock_holder;
int confd;
int len;
struct sockaddr_in svradd, cliadd;
sock_holder = socket(AF_INET, SOCK_STREAM, 0);
printf("Hello Server");
if (sock_holder == -1)
{
printf("Socket creation failed\n");
}
else
printf("Socket creation worked\n");
memset(&svradd, 0, sizeof(svradd));
svradd.sin_family = AF_INET;
svradd.sin_addr.s_addr = htonl(INADDR_ANY);
svradd.sin_port = htons(PORT);
if ((bind(sock_holder, (SA *)&svradd, sizeof(svradd))) != 0)
{
printf("Socket bind failed \n");
exit(0);
}
else
printf("Socket binding worked \n");
if ((listen(sock_holder, 5)) != 0)
{
printf("Listen failed\n");
}
else
printf("Server listening \n");
client();
len = sizeof(cliadd);
confd = accept(sock_holder, (SA *)&cliadd, &len);
if (confd < 0)
{
printf("server accept failed\n");
exit(0);
}
else
printf("server has accepted client\n");
client_func(confd);
server_func(confd);
// close(sock_holder);
}