How do I run my server as a daemon process? - c

For a few days I have been trying to run my server as a daemon process that runs continuously. Right now, my server closes the connection with the client and then closes itself. So I am able to send my packet once to the server, but when I try to send it again I get a segmentation fault error.
Also, even though I wrote the daemon process, I am not sure about its behavior and whether it is working or not.
Server Code:
#include <sys/socket.h>
#include <netinet/in.h>
#include "unistd.h"
#include <syslog.h>
#include <math.h>
#define MAXPROFILES 2
float Pearson(int mySum, int recSum, int multSum);
int main(int argc, char *argv[])
{
int sockfd, newsockfd, portno, clilen;
struct sockaddr_in serv_addr, cli_addr;
unsigned char buf[1024];
int myDataBinary[500] = {0};
int myDataBinary2[500] = {0};
int recData[500] = {0};*/
int index1=0;
struct profile_t
{
unsigned char length;
unsigned char type;
unsigned char *data;
};
typedef struct profile_datagram_t
{
unsigned char *src;
unsigned char *dst;
unsigned char ver;
unsigned char n;
struct profile_t profiles[MAXPROFILES];
} header;
header outObj;
int j =0;
int i =0;
extern int daemon_proc; /* defined in error.c */
void daemon_init (const char *pname, int facility)
{
/* Our process ID and Session ID */
pid_t pid, sid;
/* Fork off the parent process */
pid = fork();
if (pid < 0) {
exit(EXIT_FAILURE);
}
/* If we got a good PID, then
we can exit the parent process. */
if (pid > 0) {
exit(EXIT_SUCCESS);
}
/* Change the file mode mask */
umask(0);
/* Open any logs here */
/* Create a new SID for the child process */
sid = setsid();
if (sid < 0) {
/* Log the failure */
exit(EXIT_FAILURE);
}
/* Change the current working directory */
if ((chdir("/")) < 0) {
/* Log the failure */
exit(EXIT_FAILURE);
}
/* Close out the standard file descriptors */
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
/* Daemon-specific initialization goes here */
}
if (argc < 2) {
fprintf(stderr,"usage: %s port_number1",argv[0]);
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR DETECTED !!! Problem in opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
error("ERROR DETECTED !!! There was a problem in binding");
listen(sockfd, 10);
clilen = sizeof(cli_addr);
while (1){
printf("Server listening on port number %d...\n", serv_addr.sin_port);
newsockfd = accept(sockfd,(struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0)
error("ERROR DETECTED !!! the connection request was not accepted");
int rc = read(newsockfd,buf,100);
if(rc < 0){
printf("error");
}
else {
printf("success %d",rc);
}
outObj.src = malloc(4);
outObj.dst = malloc(4);
// printf(pointer);
memcpy(outObj.src,buf+0,4);
memcpy(outObj.dst,buf+4,4);
memcpy(&outObj.ver,buf+8,1);
memcpy(&outObj.n,buf+9,1);
printf("\nSource IP = ");
for(int i=0;i<4;i++){
printf("%d ",outObj.src[i]);
}
printf("\nDestination IP = ");
for(int i=0;i<4;i++){
printf("%d ",outObj.dst[i]);
}
printf("\nVersion = %d",outObj.ver);
printf("\nNumber of messages = %d",outObj.n);
int k = 10;
for(i=0;i<outObj.n;i++){
memcpy(&outObj.profiles[i].length,buf+k,1);
memcpy(&outObj.profiles[i].type,buf+k+1,1);
outObj.profiles[i].data = malloc(outObj.profiles[i].length);
memcpy(outObj.profiles[i].data,buf+k+2,5);
k +=7;
}
for(int i=0;i<outObj.n;i++){
printf("\n------- Message %d --------",i+1);
printf("\nLength : %d",outObj.profiles[i].length);
printf("\nType : %d\n",outObj.profiles[i].type);
for(int j=0;j<5;j++){
printf(" Data[%d] : %d",j,outObj.profiles[i].data[j]);
}
}
float rho;
for(int i=0;i<outObj.n;i++){
printf("\n\n---------- Values for Data Profile %d ------------",i+1);
index1=0;
int sumRecievedData = 0;
int sumMyData = 0;
int sumMultpliedData = 0;
int my_data[10] = {0};// = {1,2,3,4,5};
int myDataBinary[500] = {0};
int recData[500] = {0};
if(i==0){
my_data[0] = 1;
my_data[1] = 3;
my_data[2] = 9;
my_data[3] = 10;
} else if(i==1){
my_data[0] = 1;
my_data[1] = 2;
my_data[2] = 3;
my_data[3] = 4;
my_data[4] = 5;
}
for(int i=0; i<sizeof(my_data)/sizeof(int);i++)
{
if(my_data[i] > 0){
index1 = my_data[i];
myDataBinary[index1] = 1;
//printf("my data %d = %d\n",index1,myDataBinary[index1]);
}
}
for (int j=0; j<outObj.profiles[i].length;j++) {
if(outObj.profiles[i].data[j] > 0){
index1 = outObj.profiles[i].data[j];
recData[index1] = 1;
//printf("rec data %d = %d\n",index1,recData[index1]);
}
}
for(int i=0;i<500;i++){
sumRecievedData += recData[i];
sumMyData += myDataBinary[i];
sumMultpliedData += recData[i] * myDataBinary[i];
}
printf("\nrecSum = %d, \nmySum = %d, \nmultSum = %d\n",sumRecievedData,sumMyData,sumMultpliedData);
rho = Pearson(sumMyData,sumRecievedData,sumMultpliedData);
printf("\nPearson Coefficient for Data Profile %d= %f\n",i+1,rho);
}
return 0;
}
//exit(EXIT_SUCCESS);
}
float Pearson(int mySum, int recSum, int multSum)
{
float Cov =0;
float sdMyData = 0;
float sdRecievedData =0;
float rho;
int n = 500;
Cov = (1.0/(n-1))*(multSum - (1.0/n)*mySum*recSum);
sdMyData = sqrt((1.0/(n-1))*(mySum - (1.0/n)*mySum*mySum));
sdRecievedData = sqrt((1.0/(n-1))*(recSum - (1.0/n)*recSum*recSum));
printf("\nCovariance = %f, \nVarianceMyData = %f, \nVarianceRecData = %f",Cov,sdMyData,sdRecievedData);
if (sdMyData == 0.0 || sdRecievedData == 0.0){
rho = 0.0;
}else{
rho = Cov/(sdMyData*sdRecievedData);
}
return(rho);
}

The server does return(0); at the bottom of the supposedly infinite loop, thus exiting from main() and terminating.
As noted in a comment, your code includes a nested function daemon_init() which is never called. Nested functions are a GCC-only feature; you should avoid using them. If you do call it, the server is going to have problems because it closes stdout and stderr but your code then tries to write to the now closed files.
Without the client code, it is very far from clear what information is being sent over the wire. There is one read() call:
int rc = read(newsockfd,buf,100);
That should be using sizeof(buf) in place of 100; and it is wasteful to use char buf[1024]; when you only use 100 bytes. You check that you got some data; you do not check that you got all the data you expect. You might, therefore, be reading uninitialized data.
There are numerous other similar problems in the code, especially with constants used somewhat inappropriately. As also noted in a comment, the code is not properly modularized.
The code does not seem to respond to the client; its outputs only go to its standard output (or error).
This code compiles reasonably cleanly, but still doesn't call daemon_init() for the reasons mentioned earlier.
#include <errno.h>
#include <math.h>
#include <netinet/in.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h> /* exit() */
#include <string.h>
#include <sys/socket.h>
#include <sys/stat.h> /* umask() */
#include <syslog.h>
#include <unistd.h>
#define MAXPROFILES 2
static void error(const char *fmt, ...)
{
va_list args;
int errnum = errno;
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
fprintf(stderr, ": %d %s\n", errnum, strerror(errnum));
exit(1);
}
static float Pearson(int mySum, int recSum, int multSum);
static void daemon_init(void)
{
/* Our process ID and Session ID */
pid_t pid, sid;
/* Fork off the parent process */
pid = fork();
if (pid < 0)
error("failed to fork");
/* If we got a good PID, then
we can exit the parent process. */
if (pid > 0)
exit(EXIT_SUCCESS);
/* Change the file mode mask */
umask(0);
/* Open any logs here */
/* Create a new SID for the child process */
sid = setsid();
if (sid < 0)
error("failed to set session ID");
/* Change the current working directory */
if ((chdir("/")) < 0)
error("failed to chdir to root");
/* Close out the standard file descriptors */
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
/* Daemon-specific initialization goes here */
}
int main(int argc, char *argv[])
{
int sockfd, newsockfd, portno;
socklen_t clilen;
struct sockaddr_in serv_addr, cli_addr;
unsigned char buf[1024];
struct profile_t
{
unsigned char length;
unsigned char type;
unsigned char *data;
};
typedef struct profile_datagram_t
{
unsigned char *src;
unsigned char *dst;
unsigned char ver;
unsigned char n;
struct profile_t profiles[MAXPROFILES];
} header;
header outObj;
if (argc != 2)
error("usage: %s port", argv[0]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR DETECTED !!! Problem in opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
error("ERROR DETECTED !!! There was a problem in binding");
listen(sockfd, 10);
while (1)
{
clilen = sizeof(cli_addr);
printf("Server listening on port number %d...\n", serv_addr.sin_port);
newsockfd = accept(sockfd, (struct sockaddr *)&cli_addr, &clilen);
if (newsockfd < 0)
error("ERROR DETECTED !!! the connection request was not accepted");
int rc = read(newsockfd,buf,100);
if (rc < 0)
error("read error");
else
printf("read: success %d", rc);
outObj.src = malloc(4);
outObj.dst = malloc(4);
// printf(pointer);
memcpy(outObj.src,buf+0,4);
memcpy(outObj.dst,buf+4,4);
memcpy(&outObj.ver,buf+8,1);
memcpy(&outObj.n,buf+9,1);
printf("\nSource IP = ");
for (int i=0;i<4;i++)
printf("%d ",outObj.src[i]);
printf("\nDestination IP = ");
for (int i=0;i<4;i++)
printf("%d ",outObj.dst[i]);
printf("\nVersion = %d",outObj.ver);
printf("\nNumber of messages = %d",outObj.n);
int k = 10;
for (int i=0;i<outObj.n;i++)
{
memcpy(&outObj.profiles[i].length,buf+k,1);
memcpy(&outObj.profiles[i].type,buf+k+1,1);
outObj.profiles[i].data = malloc(outObj.profiles[i].length);
memcpy(outObj.profiles[i].data,buf+k+2,5);
k +=7;
}
for (int i=0;i<outObj.n;i++)
{
printf("\n------- Message %d --------",i+1);
printf("\nLength : %d",outObj.profiles[i].length);
printf("\nType : %d\n",outObj.profiles[i].type);
for (int j=0;j<5;j++)
{
printf(" Data[%d] : %d",j,outObj.profiles[i].data[j]);
}
}
for (int i=0;i<outObj.n;i++)
{
printf("\n\n---------- Values for Data Profile %d ------------",i+1);
int index1=0;
int sumReceivedData = 0;
int sumMyData = 0;
int sumMultpliedData = 0;
int my_data[10] = {0};
int myDataBinary[500] = {0};
int recData[500] = {0};
if (i==0)
{
my_data[0] = 1;
my_data[1] = 3;
my_data[2] = 9;
my_data[3] = 10;
}
else if (i==1)
{
my_data[0] = 1;
my_data[1] = 2;
my_data[2] = 3;
my_data[3] = 4;
my_data[4] = 5;
}
for (int i=0; i<sizeof(my_data)/sizeof(int);i++)
{
if (my_data[i] > 0)
{
index1 = my_data[i];
myDataBinary[index1] = 1;
//printf("my data %d = %d\n",index1,myDataBinary[index1]);
}
}
for (int j=0; j<outObj.profiles[i].length;j++)
{
if (outObj.profiles[i].data[j] > 0)
{
index1 = outObj.profiles[i].data[j];
recData[index1] = 1;
//printf("rec data %d = %d\n",index1,recData[index1]);
}
}
for (int i=0;i<500;i++)
{
sumReceivedData += recData[i];
sumMyData += myDataBinary[i];
sumMultpliedData += recData[i] * myDataBinary[i];
}
printf("\nrecSum = %d, \nmySum = %d, \nmultSum = %d\n",sumReceivedData,sumMyData,sumMultpliedData);
float rho = Pearson(sumMyData,sumReceivedData,sumMultpliedData);
printf("\nPearson Coefficient for Data Profile %d= %f\n",i+1,rho);
}
return 0;
}
//exit(EXIT_SUCCESS);
}
static float Pearson(int mySum, int recSum, int multSum)
{
float Cov =0;
float sdMyData = 0;
float sdReceivedData =0;
float rho;
int n = 500;
Cov = (1.0/(n-1))*(multSum - (1.0/n)*mySum*recSum);
sdMyData = sqrt((1.0/(n-1))*(mySum - (1.0/n)*mySum*mySum));
sdReceivedData = sqrt((1.0/(n-1))*(recSum - (1.0/n)*recSum*recSum));
printf("Covariance = %f\n",Cov);
printf("VarianceMyData = %f\n",sdMyData);
printf("VarianceRecData = %f\n",sdReceivedData);
if (sdMyData == 0.0 || sdReceivedData == 0.0)
rho = 0.0;
else
rho = Cov/(sdMyData*sdReceivedData);
return(rho);
}
It still needs a lot of work.

Related

Sending files from a client to a server and then reading the file in another client using sockets in C

There are two clients and a server in the application. The two clients communicate with each other via the server. When one client sends a message to the server, the server stores the message as a text file in the server, where file name is clientid_timestamp.txt. The server then sends the file to the other client that reads the file and displays its content on its terminal.
I have written the code for the client and the server given below.The issue that I am facing is that the client is not able to get the file from the server print it's contents.It doesn't show an output in the terminal.
Server side image in terminal
client side image in terminal
Server code:
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <pthread.h>
#include <sys/types.h>
#include <signal.h>
#define MAX_CLIENTS 3
#define BUFFER_SZ 2048
#define SIZE 1024
static _Atomic unsigned int cli_count = 0;
static int uid = 10;
/* Client structure */
typedef struct{
struct sockaddr_in address;
int sockfd;
int uid;
char name[32];
} client_t;
client_t *clients[MAX_CLIENTS];
pthread_mutex_t clients_mutex = PTHREAD_MUTEX_INITIALIZER;
void str_overwrite_stdout() {
printf("\r%s", "> ");
fflush(stdout);
}
void print_client_addr(struct sockaddr_in addr){
printf("%d.%d.%d.%d",
addr.sin_addr.s_addr & 0xff,
(addr.sin_addr.s_addr & 0xff00) >> 8,
(addr.sin_addr.s_addr & 0xff0000) >> 16,
(addr.sin_addr.s_addr & 0xff000000) >> 24);
}
/* Add clients to queue */
void queue_add(client_t *cl){
pthread_mutex_lock(&clients_mutex);
for(int i=0; i < MAX_CLIENTS; ++i){
if(!clients[i]){
clients[i] = cl;
break;
}
}
pthread_mutex_unlock(&clients_mutex);
}
/* Remove clients to queue */
void queue_remove(int uid){
pthread_mutex_lock(&clients_mutex);
for(int i=0; i < MAX_CLIENTS; ++i){
if(clients[i]){
if(clients[i]->uid == uid){
clients[i] = NULL;
break;
}
}
}
pthread_mutex_unlock(&clients_mutex);
}
void send_file(int sockfd){
int n;
char data[SIZE] = {0};
FILE *fp = fopen("clientid_timestamp.txt", "r");
if (fp == NULL){
printf("Error opening file!\n");
exit(1);
}
while(fgets(data, SIZE, fp) != NULL) {
if (send(sockfd, data, sizeof(data), 0) == -1) {
perror("[-]Error in sending file.");
exit(1);
}
printf("hello");
bzero(data, SIZE);
}
}
/* Send message to all clients except sender */
void send_message(char *s, int uid){
pthread_mutex_lock(&clients_mutex);
for(int i=0; i<MAX_CLIENTS; ++i){
if(clients[i]){
if(clients[i]->uid != uid){
printf("MESSAGE SENT TO %s:%d \n",inet_ntoa(clients[i]->address.sin_addr),ntohs(clients[i]->address.sin_port));
send_file(clients[i]->uid);
}
}
}
pthread_mutex_unlock(&clients_mutex);
}
/* Handle all communication with the client */
void *handle_client(void *arg){
char buff_out[BUFFER_SZ];
char name[32];
int leave_flag = 0;
cli_count++;
client_t *cli = (client_t *)arg;
// Name
bzero(buff_out, BUFFER_SZ);
while(1){
if (leave_flag) {
break;
}
int receive = recv(cli->sockfd, buff_out, BUFFER_SZ, 0);
if (receive > 0){
if(strlen(buff_out) > 0){
FILE *f = fopen("clientid_timestamp.txt", "w");
if (f == NULL){
printf("Error opening file!\n");
exit(1);
}
/* print some text */
fprintf(f, "%s", buff_out);
send_message(buff_out, cli->uid);
fclose(f);
printf("\n");
}
}
else {
printf("ERROR: -1\n");
leave_flag = 1;
}
bzero(buff_out, BUFFER_SZ);
}
/* Delete client from queue and yield thread */
close(cli->sockfd);
queue_remove(cli->uid);
free(cli);
cli_count--;
pthread_detach(pthread_self());
return NULL;
}
int main(int argc, char **argv){
if(argc != 2){
printf("Usage: %s <port>\n", argv[0]);
return EXIT_FAILURE;
}
char *ip = "127.0.0.1";
int port = atoi(argv[1]);
int option = 1;
int listenfd = 0, connfd = 0;
struct sockaddr_in serv_addr;
struct sockaddr_in cli_addr;
pthread_t tid;
/* Socket settings */
listenfd = socket(AF_INET, SOCK_STREAM, 0);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = inet_addr(ip);
serv_addr.sin_port = htons(port);
/* Ignore pipe signals */
signal(SIGPIPE, SIG_IGN);
if(setsockopt(listenfd, SOL_SOCKET,(SO_REUSEPORT | SO_REUSEADDR),(char*)&option,sizeof(option)) < 0){
perror("ERROR: setsockopt failed");
return EXIT_FAILURE;
}
/* Bind */
if(bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {
perror("ERROR: Socket binding failed");
return EXIT_FAILURE;
}
/* Listen */
if (listen(listenfd, 10) < 0) {
perror("ERROR: Socket listening failed");
return EXIT_FAILURE;
}
printf("=== WELCOME TO THE CHATROOM ===\n");
char exit[] = "exit_client";
char accepted[] = "accept_client";
while(1){
socklen_t clilen = sizeof(cli_addr);
connfd = accept(listenfd, (struct sockaddr*)&cli_addr, &clilen);
/* Check if max clients is reached */
if((cli_count) == MAX_CLIENTS){
printf("Max clients reached. Rejected: ");
print_client_addr(cli_addr);
printf(":%d\n", cli_addr.sin_port);
send(connfd, exit, strlen(exit), 0);
close(connfd);
continue;
}
else{
send(connfd, accepted, strlen(accepted), 0);
client_t *cli = (client_t *)malloc(sizeof(client_t));
cli->address = cli_addr;
cli->sockfd = connfd;
cli->uid = uid++;
printf("Client Connected : ");
printf("%s:%d \n",inet_ntoa(cli->address.sin_addr),ntohs(cli->address.sin_port));
/* Add client to the queue and fork thread */
queue_add(cli);
pthread_create(&tid, NULL, &handle_client, (void*)cli);
/* Reduce CPU usage */
sleep(1);
}
/* Client settings */
}
return EXIT_SUCCESS;
}
Client Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#define LENGTH 2048
#define MAX 10000
// Global variables
volatile sig_atomic_t flag = 0;
int sockfd = 0;
char name[32];
void str_overwrite_stdout() {
printf("%s", "> ");
fflush(stdout);
}
void str_trim_lf (char* arr, int length) {
int i;
for (i = 0; i < length; i++) { // trim \n
if (arr[i] == '\n') {
arr[i] = '\0';
break;
}
}
}
void catch_ctrl_c_and_exit(int sig) {
flag = 1;
}
void send_msg_handler() {
char message[LENGTH] = {};
char buffer[LENGTH + 32] = {};
while(1) {
str_overwrite_stdout();
fgets(message, LENGTH, stdin);
//str_trim_lf(message, LENGTH);
if (strcmp(message, "exit") == 0) {
break;
} else {
sprintf(buffer, "%s\n", message);
send(sockfd, buffer, strlen(buffer), 0);
}
bzero(message, LENGTH);
bzero(buffer, LENGTH + 32);
}
catch_ctrl_c_and_exit(2);
}
void recv_msg_handler() {
while (1) {
int n;
FILE *fp;
char buff[1024]="",*ptr=buff;
int bytes=0,bytes_received;
while(bytes_received = recv(sockfd,ptr, 1, 0)){
printf("%s\n",ptr);
if(bytes_received==-1){
perror("recieve");
exit(3);
}
if(*ptr=='\n' ) break;
ptr++; //each times we increment it it points to the buffer element
}
*ptr=0;
ptr=buff;
printf("%s\n",ptr);
str_overwrite_stdout();
}
}
int main(int argc, char **argv){
if(argc != 2){
printf("Usage: %s <port>\n", argv[0]);
return EXIT_FAILURE;
}
char *ip = "127.0.0.1";
int port = atoi(argv[1]);
signal(SIGINT, catch_ctrl_c_and_exit);
struct sockaddr_in server_addr;
/* Socket settings */
sockfd = socket(AF_INET, SOCK_STREAM, 0);
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr(ip);
server_addr.sin_port = htons(port);
// Connect to Server
int err = connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr));
if (err == -1) {
printf("ERROR: connect\n");
return EXIT_FAILURE;
}
char exit_client[] = "exit_client";
char buff[MAX];
bzero(buff, sizeof(buff));
recv(sockfd, buff, 1024, 0);
if((strcmp(buff, exit_client) == 0)){
printf("limit exceeded , closing the client \n");
close(sockfd);
return EXIT_SUCCESS;
}
else{
printf("client accepted by the server and limit not exceeded \n");
}
printf("=== WELCOME TO THE CHATROOM ===\n");
pthread_t send_msg_thread;
if(pthread_create(&send_msg_thread, NULL, (void *) send_msg_handler, NULL) != 0){
printf("ERROR: pthread\n");
return EXIT_FAILURE;
}
pthread_t recv_msg_thread;
if(pthread_create(&recv_msg_thread, NULL, (void *) recv_msg_handler, NULL) != 0){
printf("ERROR: pthread\n");
return EXIT_FAILURE;
}
while (1){
if(flag){
printf("\nBye\n");
break;
}
}
close(sockfd);
return EXIT_SUCCESS;
}
EDIT-1
I have made the changes suggested by the user stackinside and the code now works , but I have being facing a new issue for the past few hours and I am not able to wrap my head around it as what could the reason for it.
The issue that arises now is that the client is only able to send the message once to other client and vice versa and then it is not able to send any more messages except a new line.The updated code based on the changes I made
client side image in terminal
server side image in terminal
Server code :
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <pthread.h>
#include <sys/types.h>
#include <signal.h>
#define MAX_CLIENTS 3
#define BUFFER_SZ 2048
#define SIZE 1024
static _Atomic unsigned int cli_count = 0;
static int uid = 10;
/* Client structure */
typedef struct{
struct sockaddr_in address;
int sockfd;
int uid;
char name[32];
} client_t;
client_t *clients[MAX_CLIENTS];
void str_trim_lf (char* arr, int length) {
int i;
for (i = 0; i < length; i++) { // trim \n
if (arr[i] == '\n') {
arr[i] = '\0';
break;
}
}
}
pthread_mutex_t clients_mutex = PTHREAD_MUTEX_INITIALIZER;
void str_overwrite_stdout() {
printf("\r%s", "> ");
fflush(stdout);
}
void print_client_addr(struct sockaddr_in addr){
printf("%d.%d.%d.%d",
addr.sin_addr.s_addr & 0xff,
(addr.sin_addr.s_addr & 0xff00) >> 8,
(addr.sin_addr.s_addr & 0xff0000) >> 16,
(addr.sin_addr.s_addr & 0xff000000) >> 24);
}
/* Add clients to queue */
void queue_add(client_t *cl){
pthread_mutex_lock(&clients_mutex);
for(int i=0; i < MAX_CLIENTS; ++i){
if(!clients[i]){
clients[i] = cl;
break;
}
}
pthread_mutex_unlock(&clients_mutex);
}
/* Remove clients to queue */
void queue_remove(int uid){
pthread_mutex_lock(&clients_mutex);
for(int i=0; i < MAX_CLIENTS; ++i){
if(clients[i]){
if(clients[i]->uid == uid){
clients[i] = NULL;
break;
}
}
}
pthread_mutex_unlock(&clients_mutex);
}
void send_file(int sockfd){
int n;
char data[SIZE] = {0};
FILE *fp = fopen("clientid_timestamp.txt", "r");
if (fp == NULL){
printf("Error opening file!\n");
exit(1);
}
while(fgets(data, SIZE, fp) != NULL) {
if (send(sockfd, data, sizeof(data), 0) == -1) {
perror("[-]Error in sending file.");
exit(1);
}
bzero(data, SIZE);
}
}
/* Send message to all clients except sender */
void send_message(char *s, int uid){
pthread_mutex_lock(&clients_mutex);
for(int i=0; i<MAX_CLIENTS; ++i){
if(clients[i]){
if(clients[i]->uid != uid){
printf("MESSAGE SENT TO %s:%d \n",inet_ntoa(clients[i]->address.sin_addr),ntohs(clients[i]->address.sin_port));
send_file(clients[i]->sockfd);
}
}
}
pthread_mutex_unlock(&clients_mutex);
}
/* Handle all communication with the client */
void *handle_client(void *arg){
char buff_out[BUFFER_SZ];
char name[32];
int leave_flag = 0;
cli_count++;
client_t *cli = (client_t *)arg;
// Name
bzero(buff_out, BUFFER_SZ);
while(1){
if (leave_flag) {
break;
}
int receive = recv(cli->sockfd, buff_out, BUFFER_SZ, 0);
if (receive > 0){
if(strlen(buff_out) > 0){
FILE *f = fopen("clientid_timestamp.txt", "w");
if (f == NULL){
printf("Error opening file!\n");
exit(1);
}
/* print some text */
fprintf(f, "%s", buff_out);
fclose(f);
send_message(buff_out, cli->uid);
printf("\n");
}
}
else {
printf("ERROR: -1\n");
leave_flag = 1;
}
bzero(buff_out, BUFFER_SZ);
}
/* Delete client from queue and yield thread */
close(cli->sockfd);
queue_remove(cli->uid);
free(cli);
cli_count--;
pthread_detach(pthread_self());
return NULL;
}
int main(int argc, char **argv){
if(argc != 2){
printf("Usage: %s <port>\n", argv[0]);
return EXIT_FAILURE;
}
char *ip = "127.0.0.1";
int port = atoi(argv[1]);
int option = 1;
int listenfd = 0, connfd = 0;
struct sockaddr_in serv_addr;
struct sockaddr_in cli_addr;
pthread_t tid;
/* Socket settings */
listenfd = socket(AF_INET, SOCK_STREAM, 0);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = inet_addr(ip);
serv_addr.sin_port = htons(port);
/* Ignore pipe signals */
signal(SIGPIPE, SIG_IGN);
if(setsockopt(listenfd, SOL_SOCKET,(SO_REUSEPORT | SO_REUSEADDR),(char*)&option,sizeof(option)) < 0){
perror("ERROR: setsockopt failed");
return EXIT_FAILURE;
}
/* Bind */
if(bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {
perror("ERROR: Socket binding failed");
return EXIT_FAILURE;
}
/* Listen */
if (listen(listenfd, 10) < 0) {
perror("ERROR: Socket listening failed");
return EXIT_FAILURE;
}
printf("=== WELCOME TO THE CHATROOM ===\n");
char exit[] = "exit_client";
char accepted[] = "accept_client";
while(1){
socklen_t clilen = sizeof(cli_addr);
connfd = accept(listenfd, (struct sockaddr*)&cli_addr, &clilen);
/* Check if max clients is reached */
if((cli_count) == MAX_CLIENTS){
printf("Max clients reached. Rejected: ");
print_client_addr(cli_addr);
printf(":%d\n", cli_addr.sin_port);
send(connfd, exit, strlen(exit), 0);
close(connfd);
continue;
}
else{
send(connfd, accepted, strlen(accepted), 0);
client_t *cli = (client_t *)malloc(sizeof(client_t));
cli->address = cli_addr;
cli->sockfd = connfd;
cli->uid = uid++;
printf("Client Connected : ");
printf("%s:%d \n",inet_ntoa(cli->address.sin_addr),ntohs(cli->address.sin_port));
/* Add client to the queue and fork thread */
queue_add(cli);
pthread_create(&tid, NULL, &handle_client, (void*)cli);
/* Reduce CPU usage */
sleep(1);
}
/* Client settings */
}
return EXIT_SUCCESS;
}
Client code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#define LENGTH 2048
#define MAX 10000
// Global variables
volatile sig_atomic_t flag = 0;
int sockfd = 0;
char name[32];
void str_overwrite_stdout() {
printf("%s", "> ");
fflush(stdout);
}
void str_trim_lf (char* arr, int length) {
int i;
for (i = 0; i < length; i++) { // trim \n
if (arr[i] == '\n') {
arr[i] = '\0';
break;
}
}
}
void catch_ctrl_c_and_exit(int sig) {
flag = 1;
}
void send_msg_handler() {
char message[LENGTH] = {};
char buffer[LENGTH + 32] = {};
while(1) {
str_overwrite_stdout();
fgets(message, LENGTH, stdin);
str_trim_lf(message, LENGTH);
if (strcmp(message, "exit") == 0) {
break;
} else {
sprintf(buffer, "%s\n", message);
send(sockfd, buffer, strlen(buffer), 0);
}
bzero(message, LENGTH);
bzero(buffer, LENGTH + 32);
}
catch_ctrl_c_and_exit(2);
}
void recv_msg_handler() {
int n;
FILE *fp;
char buff[1024]="",*ptr=buff;
int bytes=0,bytes_received;
while (1) {
while(bytes_received = recv(sockfd,ptr, 1, 0)){
if(bytes_received==-1){
perror("recieve");
exit(3);
}
if(*ptr=='\n' ) break;
ptr++; //each times we increment it it points to the buffer element
}
*ptr=0;
str_trim_lf(buff, strlen(buff));
ptr=buff;
printf("%s \n",ptr);
str_overwrite_stdout();
}
}
int main(int argc, char **argv){
if(argc != 2){
printf("Usage: %s <port>\n", argv[0]);
return EXIT_FAILURE;
}
char *ip = "127.0.0.1";
int port = atoi(argv[1]);
signal(SIGINT, catch_ctrl_c_and_exit);
struct sockaddr_in server_addr;
/* Socket settings */
sockfd = socket(AF_INET, SOCK_STREAM, 0);
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr(ip);
server_addr.sin_port = htons(port);
// Connect to Server
int err = connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr));
if (err == -1) {
printf("ERROR: connect\n");
return EXIT_FAILURE;
}
char exit_client[] = "exit_client";
char buff[MAX];
bzero(buff, sizeof(buff));
recv(sockfd, buff, 1024, 0);
if((strcmp(buff, exit_client) == 0)){
printf("limit exceeded , closing the client \n");
close(sockfd);
return EXIT_SUCCESS;
}
else{
printf("client accepted by the server and limit not exceeded \n");
}
printf("=== WELCOME TO THE CHATROOM ===\n");
pthread_t send_msg_thread;
if(pthread_create(&send_msg_thread, NULL, (void *) send_msg_handler, NULL) != 0){
printf("ERROR: pthread\n");
return EXIT_FAILURE;
}
pthread_t recv_msg_thread;
if(pthread_create(&recv_msg_thread, NULL, (void *) recv_msg_handler, NULL) != 0){
printf("ERROR: pthread\n");
return EXIT_FAILURE;
}
while (1){
if(flag){
printf("\nBye\n");
break;
}
}
close(sockfd);
return EXIT_SUCCESS;
}
EDIT-2
So now I changed the fgets to freads and removed all the unnecessary bzero and changed the strlen to sizeof as suggested by the comments of user207421 , Martin James and stackinside .It finally works , I agree there is still a lot of room for optimisation , but it works for now and thanks for the effort.
client side image in terminal
Server side image in terminal
Client side code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#define LENGTH 2048
#define MAX 10000
#define CHUNK_SIZE 512
// Global variables
volatile sig_atomic_t flag = 0;
int sockfd = 0;
char name[32];
void str_overwrite_stdout() {
printf("%s", "> ");
fflush(stdout);
}
void str_trim_lf (char* arr, int length) {
int i;
for (i = 0; i < length; i++) { // trim \n
if (arr[i] == '\n') {
arr[i] = '\0';
break;
}
}
}
void catch_ctrl_c_and_exit(int sig) {
flag = 1;
}
void send_msg_handler() {
char message[LENGTH] = {};
char buffer[LENGTH + 32] = {};
while(1) {
str_overwrite_stdout();
fgets(message, LENGTH, stdin);
str_trim_lf(message, LENGTH);
if (strcmp(message, "exit") == 0) {
break;
}
else {
sprintf(buffer, "%s\n", message);
send(sockfd, buffer, sizeof(buffer), 0);
}
bzero(message, LENGTH);
bzero(buffer, LENGTH + 32);
}
catch_ctrl_c_and_exit(2);
}
void recv_msg_handler() {
while (1) {
int n;
FILE *fp;
char buff[1024],*ptr=buff;
int bytes=0,bytes_received;
int file_size;
recv(sockfd, buff, CHUNK_SIZE, 0);
file_size = atoi(buff);
str_trim_lf(buff, sizeof(buff));
printf("%s \n",buff);
str_overwrite_stdout();
}
}
int main(int argc, char **argv){
if(argc != 2){
printf("Usage: %s <port>\n", argv[0]);
return EXIT_FAILURE;
}
char *ip = "127.0.0.1";
int port = atoi(argv[1]);
signal(SIGINT, catch_ctrl_c_and_exit);
struct sockaddr_in server_addr;
/* Socket settings */
sockfd = socket(AF_INET, SOCK_STREAM, 0);
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr(ip);
server_addr.sin_port = htons(port);
// Connect to Server
int err = connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr));
if (err == -1) {
printf("ERROR: connect\n");
return EXIT_FAILURE;
}
char exit_client[] = "exit_client";
char buff[MAX];
bzero(buff, sizeof(buff));
recv(sockfd, buff, 1024, 0);
if((strcmp(buff, exit_client) == 0)){
printf("limit exceeded , closing the client \n");
close(sockfd);
return EXIT_SUCCESS;
}
else{
printf("client accepted by the server and limit not exceeded \n");
}
printf("=== WELCOME TO THE CHATROOM ===\n");
pthread_t send_msg_thread;
if(pthread_create(&send_msg_thread, NULL, (void *) send_msg_handler, NULL) != 0){
printf("ERROR: pthread\n");
return EXIT_FAILURE;
}
pthread_t recv_msg_thread;
if(pthread_create(&recv_msg_thread, NULL, (void *) recv_msg_handler, NULL) != 0){
printf("ERROR: pthread\n");
return EXIT_FAILURE;
}
while (1){
if(flag){
printf("\nBye\n");
break;
}
}
close(sockfd);
return EXIT_SUCCESS;
}
Server side:
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <pthread.h>
#include <sys/types.h>
#include <signal.h>
#define MAX_CLIENTS 3
#define BUFFER_SZ 2048
#define SIZE 1024
#define CHUNK_SIZE 512
static _Atomic unsigned int cli_count = 0;
static int uid = 10;
/* Client structure */
typedef struct{
struct sockaddr_in address;
int sockfd;
int uid;
char name[32];
} client_t;
client_t *clients[MAX_CLIENTS];
void str_trim_lf (char* arr, int length) {
int i;
for (i = 0; i < length; i++) { // trim \n
if (arr[i] == '\n') {
arr[i] = '\0';
break;
}
}
}
pthread_mutex_t clients_mutex = PTHREAD_MUTEX_INITIALIZER;
void str_overwrite_stdout() {
printf("\r%s", "> ");
fflush(stdout);
}
void print_client_addr(struct sockaddr_in addr){
printf("%d.%d.%d.%d",
addr.sin_addr.s_addr & 0xff,
(addr.sin_addr.s_addr & 0xff00) >> 8,
(addr.sin_addr.s_addr & 0xff0000) >> 16,
(addr.sin_addr.s_addr & 0xff000000) >> 24);
}
/* Add clients to queue */
void queue_add(client_t *cl){
pthread_mutex_lock(&clients_mutex);
for(int i=0; i < MAX_CLIENTS; ++i){
if(!clients[i]){
clients[i] = cl;
break;
}
}
pthread_mutex_unlock(&clients_mutex);
}
/* Remove clients to queue */
void queue_remove(int uid){
pthread_mutex_lock(&clients_mutex);
for(int i=0; i < MAX_CLIENTS; ++i){
if(clients[i]){
if(clients[i]->uid == uid){
clients[i] = NULL;
break;
}
}
}
pthread_mutex_unlock(&clients_mutex);
}
void send_file(int sockfd){
int n;
char data[SIZE] = {0};
FILE *fp = fopen("clientid_timestamp.txt", "r");
if (fp == NULL){
printf("Error opening file!\n");
exit(1);
}
char file_data[CHUNK_SIZE];
size_t nbytes = 0;
while ( (nbytes = fread(data, sizeof(char), CHUNK_SIZE,fp)) > 0){
if (send(sockfd, data, nbytes, 0) == -1) {
perror("[-]Error in sending file.");
exit(1);
}
}
}
/* Send message to all clients except sender */
void send_message(char *s, int uid){
pthread_mutex_lock(&clients_mutex);
for(int i=0; i<MAX_CLIENTS; ++i){
if(clients[i]){
if(clients[i]->uid != uid){
printf("MESSAGE SENT TO %s:%d \n",inet_ntoa(clients[i]->address.sin_addr),ntohs(clients[i]->address.sin_port));
send_file(clients[i]->sockfd);
}
}
}
pthread_mutex_unlock(&clients_mutex);
}
/* Handle all communication with the client */
void *handle_client(void *arg){
char buff_out[BUFFER_SZ];
char name[32];
int leave_flag = 0;
cli_count++;
client_t *cli = (client_t *)arg;
// Name
bzero(buff_out, BUFFER_SZ);
while(1){
if (leave_flag) {
break;
}
int receive = recv(cli->sockfd, buff_out, BUFFER_SZ, 0);
if (receive > 0){
if(strlen(buff_out) > 0){
FILE *f = fopen("clientid_timestamp.txt", "w");
if (f == NULL){
printf("Error opening file!\n");
exit(1);
}
/* print some text */
fprintf(f, "%s", buff_out);
fclose(f);
send_message(buff_out, cli->uid);
printf("\n");
}
}
else {
printf("ERROR: -1\n");
leave_flag = 1;
}
}
/* Delete client from queue and yield thread */
close(cli->sockfd);
queue_remove(cli->uid);
free(cli);
cli_count--;
pthread_detach(pthread_self());
return NULL;
}
int main(int argc, char **argv){
if(argc != 2){
printf("Usage: %s <port>\n", argv[0]);
return EXIT_FAILURE;
}
char *ip = "127.0.0.1";
int port = atoi(argv[1]);
int option = 1;
int listenfd = 0, connfd = 0;
struct sockaddr_in serv_addr;
struct sockaddr_in cli_addr;
pthread_t tid;
/* Socket settings */
listenfd = socket(AF_INET, SOCK_STREAM, 0);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = inet_addr(ip);
serv_addr.sin_port = htons(port);
/* Ignore pipe signals */
signal(SIGPIPE, SIG_IGN);
if(setsockopt(listenfd, SOL_SOCKET,(SO_REUSEPORT | SO_REUSEADDR),(char*)&option,sizeof(option)) < 0){
perror("ERROR: setsockopt failed");
return EXIT_FAILURE;
}
/* Bind */
if(bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {
perror("ERROR: Socket binding failed");
return EXIT_FAILURE;
}
/* Listen */
if (listen(listenfd, 10) < 0) {
perror("ERROR: Socket listening failed");
return EXIT_FAILURE;
}
printf("=== WELCOME TO THE CHATROOM ===\n");
char exit[] = "exit_client";
char accepted[] = "accept_client";
while(1){
socklen_t clilen = sizeof(cli_addr);
connfd = accept(listenfd, (struct sockaddr*)&cli_addr, &clilen);
/* Check if max clients is reached */
if((cli_count) == MAX_CLIENTS){
printf("Max clients reached. Rejected: ");
print_client_addr(cli_addr);
printf(":%d\n", cli_addr.sin_port);
send(connfd, exit, sizeof(exit), 0);
close(connfd);
continue;
}
else{
send(connfd, accepted, sizeof(accepted), 0);
client_t *cli = (client_t *)malloc(sizeof(client_t));
cli->address = cli_addr;
cli->sockfd = connfd;
cli->uid = uid++;
printf("Client Connected : ");
printf("%s:%d \n",inet_ntoa(cli->address.sin_addr),ntohs(cli->address.sin_port));
/* Add client to the queue and fork thread */
queue_add(cli);
pthread_create(&tid, NULL, &handle_client, (void*)cli);
/* Reduce CPU usage */
sleep(1);
}
/* Client settings */
}
return EXIT_SUCCESS;
}
Server side:
send_file(clients[i]->uid); ought to be send_file(clients[i]->sockfd);
fclose(f); should probably go before send_message(buff_out, cli->uid);
Client side:
printf("%s\n",ptr); (before if(bytes_received==-1)) ought to be removed
There are other inconsistencies, unused variables, etc. This reivew is very limited.

Sockets behavior differently between BSD (Mac OS X and OpenBSD) and Linux (Ubuntu)

I wrote a man-in-the-middle/proxy server initially on my mac. Essentially the proxy creates a socket and waits for a connection, then connects to another application. This works flawlessly on in OS X and in OpenBSD; however, when porting the proxy to Ubuntu, it doesn't work as intended.
There is two instances of this proxy running, listening on two separate ports. When this is ran on Ubuntu, all the traffic goes through a single port. I also run into a problem when setting the socket to nonblocking (through fcntl) that sometimes it fails with "Invalid Argument"
I am using sys/socket.
Any pitfalls during this port that I am missing?
EDIT:
I believe there are two problems. One being the Invalid Argument, the other being that traffic is being pushed to different ports.
Service 1 binds to Proxy instance 1 which then binds back to the appropriate service on the black box, which kicks off service 2. However, for some reason on Ubuntu it connects to the Instance 1 which is listening on the incorrect port.
EDIT Solution to Invalid Argument for fcntl:
Found out why i was getting the invalid argument, sadly i'm still having the other issue.
fcntl(fd, cmd, arg)
cmd - F_SETFL(long)
I was passing in a pointer to an int instead of the long primitive.
EDIT:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <netdb.h>
#include <string.h>
#include <signal.h>
#include <assert.h>
#include <syslog.h>
#include <sys/types.h>
#include <sys/select.h>
#include <sys/file.h>
#include <sys/ioctl.h>
#include <sys/param.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <arpa/ftp.h>
#include <arpa/inet.h>
#include <arpa/telnet.h>
void cleanup(int sig)
{
syslog(LOG_INFO, "Cleaning up...");
exit(0);
}
void sigreap(int sig)
{
int status;
pid_t p;
while ((p = waitpid(-1, &status, WNOHANG)) > 0) {
syslog(LOG_INFO, "sigreap: pid=%d, status=%d\n", (int) p, status);
}
/* doh! */
signal(SIGCHLD, sigreap);
}
void set_nonblock(int fd)
{
long fl;
int x;
fl = fcntl(fd, F_GETFL);
if (fl < 0) {
syslog(LOG_ERR, "fcntl F_GETFL: FD %d: %s", fd, strerror(errno));
exit(1);
}
fl |= O_NONBLOCK;
x = fcntl(fd, F_SETFL, fl);
if (x < 0) {
syslog(LOG_ERR, "fcntl F_SETFL: FD %d: %s", fd, strerror(errno));
exit(1);
}
}
int create_server_sock(char *addr, int port)
{
int addrlen, s, on = 1, x;
static struct sockaddr_in client_addr;
s = socket(AF_INET, SOCK_STREAM, 0);
if (s < 0)
perror("socket"), exit(1);
addrlen = sizeof(client_addr);
memset(&client_addr, '\0', addrlen);
client_addr.sin_family = AF_INET;
client_addr.sin_addr.s_addr = INADDR_ANY; //inet_addr(addr);
client_addr.sin_port = htons(port);
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, 4);
x = bind(s, (struct sockaddr *) &client_addr, addrlen);
if (x < 0)
perror("bind"), exit(1);
x = listen(s, 5);
if (x < 0)
perror("listen"), exit(1);
return s;
}
int open_remote_host(char *host, int port)
{
struct sockaddr_in rem_addr;
int len, s, x;
struct hostent *H;
int on = 1;
H = gethostbyname(host);
if (!H)
return (-2);
len = sizeof(rem_addr);
s = socket(AF_INET, SOCK_STREAM, 0);
if (s < 0)
return s;
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, 4);
len = sizeof(rem_addr);
memset(&rem_addr, '\0', len);
rem_addr.sin_family = AF_INET;
memcpy(&rem_addr.sin_addr, H->h_addr, H->h_length);
rem_addr.sin_port = htons(port);
x = connect(s, (struct sockaddr *) &rem_addr, len);
if (x < 0) {
close(s);
return x;
}
set_nonblock(s);
return s;
}
int get_hinfo_from_sockaddr(struct sockaddr_in addr, int len, char *fqdn)
{
struct hostent *hostinfo;
hostinfo = gethostbyaddr((char *) &addr.sin_addr.s_addr, len, AF_INET);
if (!hostinfo) {
sprintf(fqdn, "%s", inet_ntoa(addr.sin_addr));
return 0;
}
if (hostinfo && fqdn)
sprintf(fqdn, "%s [%s]", hostinfo->h_name, inet_ntoa(addr.sin_addr));
return 0;
}
int wait_for_connection(int s)
{
int newsock;
socklen_t len;
static struct sockaddr_in peer;
len = sizeof(struct sockaddr);
newsock = accept(s, (struct sockaddr *) &peer, &len);
/* dump_sockaddr (peer, len); */
if (newsock < 0) {
if (errno != EINTR)
perror("accept");
}
get_hinfo_from_sockaddr(peer, len, client_hostname);
set_nonblock(newsock);
return (newsock);
}
static int print_bytes(char * buf, ssize_t length)
{
int i = 0, ascii_off = 0, hex_off = 0;
char * hex_bytes = (char *) calloc(32*2,1);
char * ascii_bytes = (char *) calloc(32*2,1);
for( i = 0; i < length; i++)
{
hex_off += sprintf(hex_bytes+hex_off,"%02X ",(unsigned char)buf[i]);
if(buf[i] >= '!' && buf[i] <= '~')
ascii_off += sprintf(ascii_bytes+ascii_off,"%c ",buf[i]);
else
ascii_off += sprintf(ascii_bytes+ascii_off,". ");
if( ((i+1) % 16 == 0) || i == length-1 )
{
fprintf(stderr,"%-48s\t%s\n",hex_bytes,ascii_bytes);
free(hex_bytes);
free(ascii_bytes);
hex_bytes = (char *) calloc(32*2,1);
ascii_bytes = (char *) calloc(32*2,1);
ascii_off = 0;
hex_off = 0;
if(i != length-1)
fprintf(stderr,"\t");
}
}
free(hex_bytes);
free(ascii_bytes);
return 0;
}
int mywrite(int fd, char *buf, int *len)
{
int x = write(fd, buf, *len);
print_bytes(buf,*len);
if (x < 0)
return x;
if (x == 0)
return x;
if (x != *len)
memmove(buf, buf+x, (*len)-x);
*len -= x;
return x;
}
void service_client(int fd1, int fd2, int injfd)
{
int maxfd;
cfd = fd1;
sfd = fd2;
char *sbuf;
char *cbuf;
int x, n;
int cbo = 0;
int sbo = 0;
int ibo = 0;
fd_set R;
int max_clients = 30;
int i = 0,s = 0, addrlen;
struct sockaddr_in address;
sbuf = malloc(BUF_SIZE);
cbuf = malloc(BUF_SIZE);
cntrlbuf = calloc(1,BUF_SIZE);
char * injbuf = malloc(BUF_SIZE);
maxfd = cfd > sfd ? cfd : sfd;
maxfd = injfd > maxfd ? injfd : maxfd;
maxfd++;
maxfd++;
struct inj_con * ptr;
while (1) {
struct timeval to;
if (cbo) {
process_packet(cbuf,&cbo,sfd);
}
if (sbo) {
process_packet(sbuf,&sbo,cfd);
}
if (ibo) {
process_packet(injbuf,&ibo,cfd);
}
if (cntrlo) {
fprintf(stderr,"\033[33;1mControl->(%d), len = 0x%x (%d):\033[0m\n\t",cfd,cntrlo,cntrlo);
if (mywrite(cfd, cntrlbuf, &cntrlo) < 0 && errno != EWOULDBLOCK) {
syslog(LOG_ERR, "write %d: %s", cfd, strerror(errno));
exit(1);
}
}
FD_ZERO(&R);
if (cbo < BUF_SIZE)
FD_SET(cfd, &R);
if (sbo < BUF_SIZE)
FD_SET(sfd, &R);
if (ibo < BUF_SIZE)
FD_SET(injfd, &R);
to.tv_sec = 0;
to.tv_usec = 1000;
x = select(max_clients+3, &R, 0, 0, &to);
if (x > 0 || cntrl_q->item_count > 0) {
if (FD_ISSET(injfd, &R)) {
int new_socket;
if((new_socket = accept(injfd, (struct sockaddr *) &address, (socklen_t *) &addrlen)) < 0)
{
perror("accept");
exit(1);
}
// Truncated
//
}
char * temp_pkt;
if (FD_ISSET(cfd, &R)) {
temp_pkt = (char *) calloc(BUF_SIZE,1);
n = read(cfd, temp_pkt, BUF_SIZE);
syslog(LOG_INFO, "read %d bytes from CLIENT (%d)", n, cfd);
if (n > 0) {
push_msg(s_q,temp_pkt,n);
} else {
free(temp_pkt);
close(cfd);
close(sfd);
close_injection_sockets();
close(injfd);
_exit(0);
}
}
if (FD_ISSET(sfd, &R)) {
temp_pkt = (char *) calloc(BUF_SIZE,1);
n = read(sfd, temp_pkt, BUF_SIZE);
syslog(LOG_INFO, "read %d bytes from SERVER (%d)\n", n, sfd);
if (n > 0) {
push_msg(c_q,temp_pkt,n);
} else {
free(temp_pkt);
close(sfd);
close(cfd);
close_injection_sockets();
close(injfd);
_exit(0);
}
}
if(cntrlo == 0 && cntrl_q->front != NULL)
{
struct msg * tmp = next_msg(cntrl_q);
if(tmp != NULL)
{
memcpy(cntrlbuf,tmp->msg,tmp->len);
cntrlo += tmp->len;
free(tmp->msg);
free(tmp);
}
}
if(sbo == 0 && c_q->front != NULL)
{
struct msg * tmp = next_msg(c_q);
if(tmp != NULL)
{
memcpy(sbuf,tmp->msg,tmp->len);
sbo += tmp->len;
free(tmp->msg);
free(tmp);
}
}
if(cbo == 0 && s_q->front != NULL)
{
struct msg * tmp = next_msg(s_q);
if(tmp != NULL)
{
memcpy(cbuf,tmp->msg,tmp->len);
cbo += tmp->len;
free(tmp->msg);
free(tmp);
}
}
if(ibo == 0 && inj_q->front != NULL)
{
struct msg * tmp = next_msg(inj_q);
if(tmp != NULL)
{
memcpy(injbuf,tmp->msg,tmp->len);
ibo += tmp->len;
free(tmp->msg);
free(tmp);
}
}
} else if (x < 0 && errno != EINTR) {
close(sfd);
close(cfd);
_exit(0);
}
}
}
static int create_injection_sock(int injectionport)
{
struct sockaddr_in serv_addr;
int portno = injectionport;
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd <0)
{
perror("ERROR: opening socket");
exit(1);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
{
perror("ERROR: on bind");
exit(1);
}
if (listen(sockfd,5) < 0 )
{
perror("listen injection");
exit(1);
}
return sockfd;
}
int main(int argc, char *argv[])
{
if (!(5 == argc || 6 == argc)) {
fprintf(stderr, "usage: %s laddr lport rhost rport [injectionport]\n", argv[0]);
exit(1);
}
char *localaddr = strdup(argv[1]);
int localport = atoi(argv[2]);
char *remoteaddr = strdup(argv[3]);
int remoteport = atoi(argv[4]);
int injectionport;
if(argc == 6)
injectionport = atoi(argv[5]);
int client, server;
int master_sock;
int injection_sock = -1;
cntrl_q = (struct item_queue *) calloc(1,sizeof(struct item_queue));
inj_q = (struct item_queue *) calloc(1,sizeof(struct item_queue));
s_q = (struct item_queue *) calloc(1,sizeof(struct item_queue));
c_q = (struct item_queue *) calloc(1,sizeof(struct item_queue));
identities = (struct item_queue *) calloc(1,sizeof(struct item_queue));
assert(localaddr);
assert(localport > 0);
assert(remoteaddr);
assert(remoteport > 0);
if(argc == 6)
assert(injectionport > 0);
openlog(argv[0], LOG_PID, LOG_LOCAL4);
signal(SIGINT, cleanup);
signal(SIGCHLD, sigreap);
if(argc == 6)
injection_sock = create_injection_sock(injectionport);
master_sock = create_server_sock(localaddr, localport);
for (;;) {
if ((client = wait_for_connection(master_sock)) < 0)
continue;
if ((server = open_remote_host(remoteaddr, remoteport)) < 0)
continue;
if (!fork()) {
service_client(client, server, injection_sock);
}
close(client);
close(server);
}
}
Just a guess, but I think your problem is the way you're handling the injection socket. I don't know what you deleted in the // TRUNCATED code block, but basically what you're doing is this:
// Parent process -- bind & listen on the injection socket
injfd = socket(...);
bind(injfd, ...);
listen(injfd, ...);
...
while (1)
{
client = wait_for_connection();
...
if (!fork())
{
// Each child process
...
if (stuff && FD_ISSET(injfd, &R)) {
new_socket = accept(injfd);
...
}
...
}
...
}
In other words, all of your child processes are listening on the same injection socket and trying to accept connections. I'm not sure if this even well-defined behavior, but even in the best case, when a new connection arrives on the injection port, the process that is going to accept the connection could be random and uncontrollable. It could be any of the child processes or even the parent process.
In order to control that behavior, you need to decide who should be listening for connections on the injection socket. If only the parent should be listening, then only the parent should call accept() on it or pass it as an argument to select(). Likewise, if only a particular child should be listening, then only that child should call accept() or pass it to select(). All other processes that are ignoring that socket should close() it at their earliest convenience (e.g. immediately after fork() returns) to avoid leaking file descriptors.
Turns out that SO_REUSEADDR socket option was the issue. I removed me setting that socket option and everything worked out.
This Lead me to the solution.

C - Simple ipv6 udp server using select to listen on multiple ports. Receiving message from one port, not the other

Here is my code.
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/select.h>
#include <stdio.h>
#include <string.h>
int max(int socket_handle[]);
int main( void )
{
int max_clients_allowed = 2;
int socket_handle[max_clients_allowed];
int client_handle[max_clients_allowed];
struct sockaddr_in6 server_address[max_clients_allowed];
struct sockaddr_in6 client_address[max_clients_allowed];
char buffer[1000];
socklen_t client_length;
fd_set read_handles;
struct timeval timeout_interval;
int bytes_received;
int port_number = 9000;
int retval;
int i;
printf("Hello, human.\n");
for (i = 0; i < max_clients_allowed; i++)
{
printf("Creating socket%d on port: %d\n", i, port_number + i);
socket_handle[i] = socket(PF_INET6,SOCK_DGRAM,0);
memset( &server_address[i], 0, sizeof( server_address[i] ) );
server_address[i].sin6_family = AF_INET6;
server_address[i].sin6_addr=in6addr_any;
server_address[i].sin6_port=htons( port_number + i );
if(bind( socket_handle[i], (struct sockaddr *)&server_address[i], sizeof( server_address[i] )) < 0)
{
perror("Unable to bind.");
return -1;
}
else
{
printf("Bind %d successful.\n", i);
}
}
while (1) {
FD_ZERO(&read_handles);
FD_SET(socket_handle[0], &read_handles);
FD_SET(socket_handle[1], &read_handles);
timeout_interval.tv_sec = 2;
timeout_interval.tv_usec = 500000;
retval = select(max(socket_handle) + 1, &read_handles, NULL, NULL, &timeout_interval);
if (retval == -1)
{
printf("Select error\n");
//error
}
else if ((retval = 0))
{
printf("timeout\n");
}
else
{
//good
client_length = sizeof(struct sockaddr*);
for (i = 0; i < max_clients_allowed; i++)
{
if (FD_ISSET(socket_handle[i], &read_handles))
{
if((bytes_received = recvfrom(socket_handle[i],buffer,sizeof(buffer),0,(struct sockaddr *)&client_address[i], (socklen_t*)&client_length)) < 0)
{
perror("Error in recvfrom.");
break;
}
printf("\nData received:");
printf("\n--------------\n");
printf("%s", buffer);
}
}
}
}
}
int max(int socket_handle[])
{
if (socket_handle[0] > socket_handle[1])
{
return socket_handle[0];
}
return socket_handle[1];
}
This code is supposed to bind to port 9000 and 9001. It them uses select to see which sockets has incoming data, and then prints the message.
I'm assuming it has something to do with my recvfrom function. I've tried playing around with the parameters with no avail.
Another problem might be when I am setting up the sockets, I am using sin6.addr = in6addr_any. I'm pretty sure PF_INET6 and AF_INET6 are right, but that could be an issue too. I've been playing with this for a bit but I can't find the bug. I would be really grateful if someone could point out my mistake so I could fix it. I know I'm on the cusp of getting this finished.
This is a homework problem, the teacher gave us the test program and all it does is simply send a message on port 9000.
When calling recvfrom(), you are setting the client_length to the wrong value on input. It needs to be set to sizeof(client_address[I]) instead. You also need to reset the client_length each time you call recvfrom().
When you print the received buffer, you need to take bytes_received into account since the buffer will not be null-terminated (unless the client is sending null-terminated data).
Try this instead:
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/select.h>
#include <stdio.h>
#include <string.h>
int main( void )
{
int max_servers = 2;
int server_handle[max_servers];
int max_server_handle = 0;
struct sockaddr_in6 server_address[max_servers];
struct sockaddr_in6 client_address[max_servers];
char buffer[1000];
socklen_t client_length;
fd_set read_handles;
struct timeval timeout_interval;
int bytes_received;
int port_number = 9000;
int retval;
int i;
printf("Hello, human.\n");
for (i = 0; i < max_servers; i++)
{
printf("Creating socket %d on port: %d\n", i, port_number + i);
server_handle[i] = socket(PF_INET6, SOCK_DGRAM, 0);
if (server_handle[i] < 0)
{
perror("Unable to create socket.");
return -1;
}
if (server_handle[i] > max_server_handle)
max_server_handle = server_handle[i];
memset( &server_address[i], 0, sizeof( server_address[i] ) );
server_address[i].sin6_family = AF_INET6;
server_address[i].sin6_addr = in6addr_any;
server_address[i].sin6_port = htons( port_number + i );
if (bind( server_handle[i], (struct sockaddr *)&server_address[i], sizeof( server_address[i] )) < 0)
{
perror("Unable to bind.");
return -1;
}
printf("Bind %d successful.\n", i);
}
while (1)
{
FD_ZERO(&read_handles);
for (i = 0; i < max_servers; i++)
FD_SET(server_handle[i], &read_handles);
timeout_interval.tv_sec = 2;
timeout_interval.tv_usec = 500000;
retval = select(max_server_handle + 1, &read_handles, NULL, NULL, &timeout_interval);
if (retval == -1)
{
printf("Select error\n");
//error
}
else if (retval == 0)
{
printf("timeout\n");
}
else
{
//good
for (i = 0; i < max_servers; i++)
{
if (FD_ISSET(server_handle[i], &read_handles))
{
client_length = sizeof(client_address[i]);
if ((bytes_received = recvfrom(server_handle[i], buffer, sizeof(buffer), 0, (struct sockaddr *)&client_address[i], &client_length)) < 0)
{
perror("Error in recvfrom.");
break;
}
printf("\nData received on socket %d:", i);
printf("\n--------------\n");
printf("%.*s", bytes_received, buffer);
}
}
}
}
}

Usage of htonl() and ntonhl() for unsigned char

I am pasting my client and server code below. My program is running fine, except that i am trying to send an ipaddress in my src and dest field, and for some reason, even though i am sending it as 131.199.166.232, it is printing as 232.166.199.131. But rest of my packet values are printed in a proper way. I have used memcpy(), so I feel its a memcpy thing, which somewhere I did wrong, but in Beej's guide as there is a section # the byte ordering in different computer architectures.....I have not used htonl() and all, so maybe it is because of that.Please guide me as where I am going wrong. Also kindly tell me the way i am sending data, how should the htonl() function can be used in my code....Thanks in advance.
Client:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#define MAXPROFILES 2
int main(int argc, char *argv[])
{
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
unsigned char buf[1024];
unsigned int srcAddress = 2193598184;
unsigned int destAddress = 2193598182;
struct profile_t
{
unsigned char length;
unsigned char type;
unsigned char *data;
};
typedef struct profile_datagram_t
{
unsigned char src[4];
unsigned char dst[4];
unsigned char ver;
unsigned char n;
struct profile_t profiles[MAXPROFILES];
} header;
header outObj;
int j =0;
int i =0;
// for loop for doing the malloc so that we can allocate memory to all profiles
for(i=0;i<MAXPROFILES;i++){
outObj.profiles[i].data = malloc(5);
}
for(i=3;i>=0;i--){
outObj.src[i] = (srcAddress >> (i*8)) & 0xFF;
outObj.dst[i] = (destAddress >> (i*8)) & 0xFF;
printf("%d",outObj.src[i]);
}
outObj.ver = 1;
outObj.n = 2;
memcpy(buf,&outObj.src,4);
memcpy(buf+4,&outObj.dst,4);
memcpy(buf+8,&outObj.ver,1);
memcpy(buf+9,&outObj.n,1);
outObj.profiles[0].length = 5;
outObj.profiles[0].type = 1;
outObj.profiles[1].length = 5;
outObj.profiles[1].type = 2;
for(i=0;i<MAXPROFILES;i++){
for(j=0;j<5;j++){
outObj.profiles[i].data[j] = j+1;
}
}
int k = 10;
// for loop to do memcopy of length,type and data.
for(i=0;i<MAXPROFILES;i++){
memcpy(buf+k,&outObj.profiles[0].length,1);
memcpy(buf+k+1,&outObj.profiles[0].type,1);
memcpy(buf+k+2,outObj.profiles[0].data,5);
k +=7;
}
if (argc < 3) {
fprintf(stderr,"usage: %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]); //Convert ASCII to integer
sockfd = socket(AF_INET, SOCK_STREAM, 0); // socket file descriptor
if (sockfd < 0)
error("ERROR DETECTED !!! Problem in opening socket\n");
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr,"ERROR DETECTED !!!, no such server found \n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr)); //clear the memory for server address
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
printf("Client 1 trying to connect with server host %s on port %d\n", argv[1], portno);
if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
error("ERROR in connection");
printf("SUCCESS !!! Connection established \n");
if (write(sockfd, buf, k) < 0)
{
error("Write error has occured ");
}
return 0;
Server:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define MAXPROFILES 2
int main(int argc, char *argv[])
{
int sockfd, newsockfd, portno, clilen;
struct sockaddr_in serv_addr, cli_addr;
unsigned char buf[1024];
int my_data2[10] = {1,3,9,10};
int my_data[10] = {1,2,3,4,5};
int myDataBinary[500] = {0};
int myDataBinary2[500] = {0};
int recData[500] = {0};
int index1=0;
struct profile_t
{
unsigned char length;
unsigned char type;
unsigned char *data;
};
typedef struct profile_datagram_t
{
unsigned char src[4];
unsigned char dst[4];
unsigned char ver;
unsigned char n;
struct profile_t profiles[MAXPROFILES];
} header;
header outObj;
int j =0;
int i =0;
if (argc < 2) {
fprintf(stderr,"usage: %s port_number1",argv[0]);
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR DETECTED !!! Problem in opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
error("ERROR DETECTED !!! There was a problem in binding");
listen(sockfd, 10);
clilen = sizeof(cli_addr);
printf("Server listening on port number %d...\n", serv_addr.sin_port);
newsockfd = accept(sockfd,(struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0)
error("ERROR DETECTED !!! the connection request was not accepted");
int rc = read(newsockfd,buf,100);
if(rc < 0){
printf("error");
}
else {
printf("success %d",rc);
}
memcpy(&outObj.src,buf+0,4);
memcpy(&outObj.dst,buf+4,4);
memcpy(&outObj.ver,buf+8,1);
memcpy(&outObj.n,buf+9,1);
printf("\nsrc ip = ");
for(int i=0;i<4;i++){
printf("%d ",outObj.src[i]);
}
printf("\ndest ip = ");
for(int i=0;i<4;i++){
printf("%d ",outObj.src[i]);
}
printf("\nversion = %d",outObj.ver);
printf("\nnumber = %d",outObj.n);
int k = 10;
for(i=0;i<outObj.n;i++){
memcpy(&outObj.profiles[i].length,buf+k,1);
memcpy(&outObj.profiles[i].type,buf+k+1,1);
outObj.profiles[i].data = malloc(outObj.profiles[i].length);
memcpy(outObj.profiles[i].data,buf+k+2,5);
k +=7;
}
for(int i=0;i<outObj.n;i++){
printf("\nMessage %d :",i+1);
printf("\nLength : %d",outObj.profiles[i].length);
printf("\nType : %d",outObj.profiles[i].type);
for(int j=0;j<5;j++){
printf("\ndata %d : %d",j,outObj.profiles[i].data[j]);
}
}
for(int i=0; i<sizeof(my_data)/sizeof(int);i++)
{
if(my_data[i] > 0){
index1 = my_data[i];
myDataBinary[index1] = 1;
printf("my data %d = %d\n",index1,myDataBinary[index1]);
}
}
for(int i=0; i<sizeof(my_data2)/sizeof(int);i++)
{
if(my_data2[i] > 0){
index1 = my_data2[i];
myDataBinary2[index1] = 1;
printf("my data %d = %d\n",index1,myDataBinary2[index1]);
}
}
int sumRecievedData = 0;
int sumMyData = 0;
int sumMultpliedData = 0;
float Cov =0;
float sdMyData = 0;
float sdRecievedData =0;
int n = 500;
float rho;
for(int i=0;i<outObj.n;i++){
index1=0;
for (int j=0; j<outObj.profiles[i].length;j++) {
if(outObj.profiles[i].data[j] > 0){
index1 = outObj.profiles[i].data[j];
recData[index1] = 1;
printf("rec data %d = %d\n",index1,recData[index1]);
}
}
}
return 0;
}
an ip address is really just an array of unsigned char.
uchar ip[] = {127,0,0,1};
Is a fine representation for a loopback address. But an array of four bytes, and a int really aren't that large; with one exception endiannes! So suppose I create the int which represents that ip. A naive approach might be:
int ip = (127<<24)|(0<<16)|(0<<8)|(1)
Of course, on little endian machines, like the x86 and arm it doing this:
char *char_ip = (void*)&ip;
and iterating over that aray would yield:
1, 0, 0, 127
But on a big endian machine, like a PowerPC, or a SPARC, we would have what we expect,
127, 0, 0, 1
Big endian is also known as "network byte order" which is what the n in htonl stands for: "host to network long". These functions are frequently used when reading or writing integers over the network. Suppose a server wants to send a client some number:
uint32_t important = htonl(42);
write(client, &important, sizeof important);
Then, to read it, the client goes:
uint32_t important;
read(server, &important, sizeof important);
important = ntohl(important);
The reason your ip address were flipped was because ip addresses are expected to be in network byte order, but yours were little endian instead. htonl on an int-type ip will flip it for you.
This is way too much code for me to read, but if you just want to create a byte array for serializing, you don't need any special functions at all, you can just write it algebraically:
unsigned char buf[sizeof(uint_type)];
uint_type value;
for (size_t i = 0; i != sizeof(uint_type); ++i)
{
// Little-endian
buf[i] = value >> (i * CHAR_BIT);
// Big-endian
buf[sizeof(uint_type - i - 1)] = value >> (i * CHAR_BIT);
}
Note that this code is independent of your system's endianness.
Since you asked, the htonl/ntohl functions are for dealing with uint32_t integers directly, without explicit char arrays:
uint32_t value;
myfile.read((char*)&value, sizeof(value)); // network endianness
value = ntohl(value); // host endianness
/* fiddle fiddle */
value = htonl(value);
yourfile.write((const char*)&value, sizeof(value));
(More typically you'd be writing to a socket rather than a file, I suppose.)

Error in socket programming and use of htonl(),htons() functions in C

I am pasting my client and server code below. My program is running fine, except that i am trying to send an ipaddress in my src and dest field, and for some reason, even though i am sending it as 131.199.166.232, it is printing as 232.166.199.131. But rest of my packet values are printed in a proper way. I have used memcpy(), so I feel its a memcpy thing, which somewhere I did wrong, but in Beej's guide as there is a section # the byte ordering in different computer architectures.....I have not used htonl() and all, so maybe it is because of that.Please guide me as where I am going wrong. Also kindly tell me the way i am sending data, how should the htonl() function can be used in my code....Thanks in advance.
Client:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#define MAXPROFILES 2
int main(int argc, char *argv[])
{
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
unsigned char buf[1024];
unsigned int srcAddress = 2193598184;
unsigned int destAddress = 2193598182;
struct profile_t
{
unsigned char length;
unsigned char type;
unsigned char *data;
};
typedef struct profile_datagram_t
{
unsigned char src[4];
unsigned char dst[4];
unsigned char ver;
unsigned char n;
struct profile_t profiles[MAXPROFILES];
} header;
header outObj;
int j =0;
int i =0;
// for loop for doing the malloc so that we can allocate memory to all profiles
for(i=0;i<MAXPROFILES;i++){
outObj.profiles[i].data = malloc(5);
}
for(i=3;i>=0;i--){
outObj.src[i] = (srcAddress >> (i*8)) & 0xFF;
outObj.dst[i] = (destAddress >> (i*8)) & 0xFF;
printf("%d",outObj.src[i]);
}
outObj.ver = 1;
outObj.n = 2;
memcpy(buf,&outObj.src,4);
memcpy(buf+4,&outObj.dst,4);
memcpy(buf+8,&outObj.ver,1);
memcpy(buf+9,&outObj.n,1);
outObj.profiles[0].length = 5;
outObj.profiles[0].type = 1;
outObj.profiles[1].length = 5;
outObj.profiles[1].type = 2;
for(i=0;i<MAXPROFILES;i++){
for(j=0;j<5;j++){
outObj.profiles[i].data[j] = j+1;
}
}
int k = 10;
// for loop to do memcopy of length,type and data.
for(i=0;i<MAXPROFILES;i++){
memcpy(buf+k,&outObj.profiles[0].length,1);
memcpy(buf+k+1,&outObj.profiles[0].type,1);
memcpy(buf+k+2,outObj.profiles[0].data,5);
k +=7;
}
if (argc < 3) {
fprintf(stderr,"usage: %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]); //Convert ASCII to integer
sockfd = socket(AF_INET, SOCK_STREAM, 0); // socket file descriptor
if (sockfd < 0)
error("ERROR DETECTED !!! Problem in opening socket\n");
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr,"ERROR DETECTED !!!, no such server found \n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr)); //clear the memory for server address
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
printf("Client 1 trying to connect with server host %s on port %d\n", argv[1], portno);
if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
error("ERROR in connection");
printf("SUCCESS !!! Connection established \n");
if (write(sockfd, buf, k) < 0)
{
error("Write error has occured ");
}
return 0;
}
Server Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define MAXPROFILES 2
int main(int argc, char *argv[])
{
int sockfd, newsockfd, portno, clilen;
struct sockaddr_in serv_addr, cli_addr;
unsigned char buf[1024];
int my_data2[10] = {1,3,9,10};
int my_data[10] = {1,2,3,4,5};
int myDataBinary[500] = {0};
int myDataBinary2[500] = {0};
int recData[500] = {0};
int index1=0;
struct profile_t
{
unsigned char length;
unsigned char type;
unsigned char *data;
};
typedef struct profile_datagram_t
{
unsigned char src[4];
unsigned char dst[4];
unsigned char ver;
unsigned char n;
struct profile_t profiles[MAXPROFILES];
} header;
header outObj;
int j =0;
int i =0;
if (argc < 2) {
fprintf(stderr,"usage: %s port_number1",argv[0]);
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR DETECTED !!! Problem in opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
error("ERROR DETECTED !!! There was a problem in binding");
listen(sockfd, 10);
clilen = sizeof(cli_addr);
printf("Server listening on port number %d...\n", serv_addr.sin_port);
newsockfd = accept(sockfd,(struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0)
error("ERROR DETECTED !!! the connection request was not accepted");
int rc = read(newsockfd,buf,100);
if(rc < 0){
printf("error");
}
else {
printf("success %d",rc);
}
memcpy(&outObj.src,buf+0,4);
memcpy(&outObj.dst,buf+4,4);
memcpy(&outObj.ver,buf+8,1);
memcpy(&outObj.n,buf+9,1);
printf("\nsrc ip = ");
for(int i=0;i<4;i++){
printf("%d ",outObj.src[i]);
}
printf("\ndest ip = ");
for(int i=0;i<4;i++){
printf("%d ",outObj.src[i]);
}
printf("\nversion = %d",outObj.ver);
printf("\nnumber = %d",outObj.n);
int k = 10;
for(i=0;i<outObj.n;i++){
memcpy(&outObj.profiles[i].length,buf+k,1);
memcpy(&outObj.profiles[i].type,buf+k+1,1);
outObj.profiles[i].data = malloc(outObj.profiles[i].length);
memcpy(outObj.profiles[i].data,buf+k+2,5);
k +=7;
}
for(int i=0;i<outObj.n;i++){
printf("\nMessage %d :",i+1);
printf("\nLength : %d",outObj.profiles[i].length);
printf("\nType : %d",outObj.profiles[i].type);
for(int j=0;j<5;j++){
printf("\ndata %d : %d",j,outObj.profiles[i].data[j]);
}
}
for(int i=0; i<sizeof(my_data)/sizeof(int);i++)
{
if(my_data[i] > 0){
index1 = my_data[i];
myDataBinary[index1] = 1;
printf("my data %d = %d\n",index1,myDataBinary[index1]);
}
}
for(int i=0; i<sizeof(my_data2)/sizeof(int);i++)
{
if(my_data2[i] > 0){
index1 = my_data2[i];
myDataBinary2[index1] = 1;
printf("my data %d = %d\n",index1,myDataBinary2[index1]);
}
}
int sumRecievedData = 0;
int sumMyData = 0;
int sumMultpliedData = 0;
float Cov =0;
float sdMyData = 0;
float sdRecievedData =0;
int n = 500;
float rho;
for(int i=0;i<outObj.n;i++){
index1=0;
for (int j=0; j<outObj.profiles[i].length;j++) {
if(outObj.profiles[i].data[j] > 0){
index1 = outObj.profiles[i].data[j];
recData[index1] = 1;
printf("rec data %d = %d\n",index1,recData[index1]);
}
}
}
for(int i=0;i<500;i++){
sumRecievedData += recData[i];
sumMyData += myDataBinary[i];
sumMultpliedData += recData[i] * myDataBinary[i];
}
printf("recSum = %d, mySum = %d, multSum = %d",sumRecievedData,sumMyData,sumMultpliedData);
Cov = (1.0/(n-1))*(sumMultpliedData - (1.0/n)*sumMyData*sumRecievedData);
sdMyData = sqrt((1.0/(n-1))*(sumMyData - (1.0/n)*sumMyData*sumMyData));
sdRecievedData = sqrt((1.0/(n-1))*(sumRecievedData - (1.0/n)*sumRecievedData*sumRecievedData));
printf("Covariance = %f, Variance 1 = %f, Variance 2 = %f",Cov,sdMyData,sdRecievedData);
if (sdMyData == 0.0 || sdRecievedData == 0.0){
rho = 0.0;
}else{
rho = Cov/(sdMyData*sdRecievedData);
}
printf("Pearson Coefficient = %f",rho);
return 0;
}
You need to decide how you want to send the data and convert data in that format right before:
if (write(sockfd, buf, k) < 0)
You use either of following:
htons() host to network short
htonl() host to network long
ntohs() network to host short
ntohl() network to host long
In general, you should use regular integers instead of byte arrays in your structs, then use hton...() to put those values be in network byte order when placing them into send buffers, and then use ntoh...() to put the values back into host byte order when copying them out of receive buffers. Your code operates in host byte order. Network transmissions should use network byte order.
With that said, IPv4 addresses are a special case, because there are extra functions available() for working with IP strings, which expect the numeric values to be in network byte order only.
Try something like this:
Client:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#define MAXPROFILES 2
struct profile_t
{
unsigned char length;
unsigned char type;
unsigned char *data;
};
struct profile_datagram_t
{
unsigned long src;
unsigned long dst;
unsigned char ver;
unsigned char n;
profile_t profiles[MAXPROFILES];
};
int main(int argc, char *argv[])
{
if (argc < 3)
{
fprintf(stderr,"usage: %s hostname port\n", argv[0]);
exit(0);
}
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
unsigned char buf[1024];
profile_datagram_t outObj;
int i;
int j;
outObj.src = inet_addr("130.191.166.232");
outObj.dst = inet_addr("130.191.166.230");
outObj.ver = 1;
outObj.n = 2;
memcpy(&buf[0], &outObj.src, 4);
memcpy(&buf[4], &outObj.dst, 4);
memcpy(&buf[8], &outObj.ver, 1);
memcpy(&buf[9], &outObj.n, 1);
int k = 10;
for(i = 0; i < MAXPROFILES; ++i)
{
outObj.profiles[i].length = 5;
outObj.profiles[i].type = i+1;
outObj.profiles[i].data = malloc(5);
for(j = 0; j < 5; ++j)
{
outObj.profiles[i].data[j] = j+1;
}
memcpy(&buf[k], &outObj.profiles[i].length, 1);
memcpy(&buf[k+1], &outObj.profiles[i].type, 1);
memcpy(&buf[k+2], outObj.profiles[i].data, 5);
k +=7;
}
sockfd = socket(AF_INET, SOCK_STREAM, 0); // socket file descriptor
if (sockfd < 0)
error("ERROR in opening socket\n");
server = gethostbyname(argv[1]);
if (server == NULL)
{
closesocket(sockfd);
fprintf(stderr,"ERROR DETECTED !!!, no such server found \n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr)); //clear the memory for server address
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
portno = atoi(argv[2]); //Convert ASCII to integer
serv_addr.sin_port = htons(portno);
printf("Client 1 trying to connect with server host %s on port %d\n", argv[1], portno);
if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
{
closesocket(sockfd);
error("ERROR in connect");
}
printf("SUCCESS !!! Connection established \n");
i = 0;
while (i < k)
{
int rc = write(sockfd, &buf[i], k-i);
if (rc < 0)
{
closesocket(sockfd);
error("ERROR in write");
}
i += rc;
}
closesocket(sockfd);
return 0;
}
Server:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define MAXPROFILES 2
struct profile_t
{
unsigned char length;
unsigned char type;
unsigned char *data;
};
struct profile_datagram_t
{
unsigned long src;
unsigned long dst;
unsigned char ver;
unsigned char n;
profile_t profiles[MAXPROFILES];
};
int main(int argc, char *argv[])
{
if (argc < 2)
{
fprintf(stderr, "usage: %s port_number1", argv[0]);
exit(1);
}
int sockfd, newsockfd, portno, clilen;
struct sockaddr_in serv_addr, cli_addr;
struct in_addr addr;
unsigned char buf[1024];
int buflen;
profile_datagram_t outObj;
int i;
int j;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR in opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
error("ERROR in binding");
if (listen(sockfd, 10)) < 0)
error("ERROR in listening");
printf("Server listening on port number %d...\n", portno);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd,(struct sockaddr *) &cli_addr, &clilen);
closesocket(sockfd);
if (newsockfd < 0)
error("a connection request was not accepted");
buflen = 0;
while (buflen < 10)
{
int rc = read(newsockfd, &buf[buflen], 10-buflen);
if(rc <= 0)
{
closesocket(newsockfd);
error("ERROR in read");
}
buflen += rc;
}
memcpy(&outObj.src, &buf[0], 4);
memcpy(&outObj.dst, &buf[4], 4);
memcpy(&outObj.ver, &buf[8], 1);
memcpy(&outObj.n, &buf[9], 1);
addr.s_addr = outObj.src;
printf("\nsrc ip = %s", inet_ntoa(&addr));
addr.s_addr = outObj.dst;
printf("\ndest ip = %s", inet_ntoa(&addr));
printf("\nversion = %d", outObj.ver);
printf("\nnumber = %d", outObj.n);
for(i = 0; i < outObj.n; ++i)
{
buflen = 0;
while (buflen < 2)
{
int rc = read(newsockfd, &buf[buflen], 2-buflen);
if (rc <= 0)
{
closesocket(newsockfd);
error("ERROR in read");
}
buflen += rc;
}
memcpy(&outObj.profiles[i].length, &buf[0], 1);
memcpy(&outObj.profiles[i].type, &buf[1], 1);
outObj.profiles[i].data = malloc(outObj.profiles[i].length);
buflen = 0;
while (buflen < outObj.profiles[i].length)
{
int rc = read(newsockfd, &buf[buflen], outObj.profiles[i].length-buflen);
if (rc <= 0)
{
closesocket(newsockfd);
error("ERROR in read");
}
buflen += rc;
}
printf("\nMessage %d :",i+1);
printf("\nLength : %d", outObj.profiles[i].length);
printf("\nType : %d", outObj.profiles[i].type);
for(j = 0; j < outObj.profiles[i].length; j)
printf("\ndata[%d] : %d", j, outObj.profiles[i].data[j]);
}
closesocket(newsockfd);
return 0;
}

Resources