c_sharp
c_sharp

Reputation: 281

trying to send parts of a struct from tcp server to client in c

I am trying to pass parts of a struct to the client and having a hard time with it. I tested my case 1 condition with the following print statement:

printf("%d %s", data[i].course, data[i].Dept);

This worked with no problems. Now what I am trying to do is send it through the socket. My send statement is:

send(connected, send_data, strlen(send_data), 0);

Now I tried the following statements of:

send_data = data[i].couurse;
strcpy(send_data, data[i].course);
send_data = atoi(data[i].course);

and to know avail, neither worked. I know there has to be a way and am hoping someone can show me how. I have included the relevant parts of the code:

int switchInput;
int i = 0;
int connected;
int sock;
int bytes_received;
int sin_size;
int true = 1;
int tempCourse = 0;
char send_data[BUF];
char recv_data[BUF];
char tempDept[5];
char tempDay[1];
char tempTime[1];
FILE *filePointer;
sched_record data[MAX_RECORD];
filePointer = fopen (BINFILE, "rb");

and:

 while(1) {

        bytes_received = recv(connected, recv_data, BUF, 0);
        recv_data[bytes_received] = '\0';
        switchInput = atoi(recv_data);

        switch(switchInput) {

        case 1:

            fread(data, sizeof(sched_record), MAX_RECORD, filePointer);
            fclose(filePointer);
            char send_data[] = "Enter Department Name";
            send(connected, send_data, strlen(send_data), 0);
            bytes_received = recv(connected, recv_data, BUF, 0);
            recv_data[bytes_received] = '\0';
            strcpy(tempDept, recv_data);
               for (i=0; i<MAX_RECORD; i++){
                if ((strcmp(tempDept, data[i].Dept)==0) && tempCourse != data[i].course){
                        send(connected, &data[i].Dept, sizeof(data[i].Dept), 0);
                        tempCourse = data[i].course;
                        send(connected, &tempCourse, sizeof(tempCourse), 0);
                }
            }

        break;

In this particular case I need to send the course and department. Also is there a better way to do this? This seems kinda messy. If so, can you show me a more simplified version?

Upvotes: 0

Views: 188

Answers (1)

violet313
violet313

Reputation: 1932

You must have got compilation errors all over the place.

You don't want atoi. you want itoa or sprintf

but this may be what you really want:

tempCourse = data[i].course;
send(connected, &tempCourse, sizeof(tempCourse), 0);

(you provide the address of the tempCourse variable and it's bytes size in memory. see send)

(although you might need to worry about network byte order)


Alternatively, if you wish to convert the .course struct member into a string, then try this:

sprintf(send_data, "%d", data[i].course);
send(connected, send_data, strlen(send_data), 0);

Upvotes: 2

Related Questions