sending an array of structs across a socket





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







-2















What if I had a an array of struct. Is it possible for me to send an array of structs over a socket? The struct size will be updated continuously and at any time I would be able to print out the content of the structs. I hope this makes sense, my explanation might not be cleared. My syntax is definitely not correct for some areas, it's just a snippet of what I think it would look like. I just need some guidance.



This will send the array of structs acorss the socket.



void sendOpenMessage(int num0, int num1, int num2){

struct openMessage{
int num0;
int num1;
int num2

};
struct openMessage open[100];
int i = 0;
open[i].num0 = 1;
open[i].num1 = 2;
open[i].num2 = 3;

int length = sizeof(open);
if(send(socket, &open[i], length, 0) == -1){
fprintf(stderr, "Send() failed");
}else{
printf("Open message is being sentn");
}
i++;
}




This will receive the struct and display the contents in a message



  struct openMessage open[100];
if(recv(clnSocket, &open, sizeof(open), 0) < 0){
fprintf(stderr,"Recv() failedn");
printf("Error code: %dn", errno);
}

//Get size of the current struct
//Print out the messages from the structs that have messages?
void printStruct(struct openMessage open){
for(int i = 0; i < sizeof(the struct); i++){
printf("%dn",open[i].num0);
printf("%dn", open[i].num1);
printf("%dn", open[i].num2);
}
}









share|improve this question




















  • 1





    Please try it first. If you get some specific errors or problems, then you're more than welcome to ask about that. Also please review about how to ask good questions, as well as this question checklist. And don't forget how to create a Minimal, Complete, and Verifiable example.

    – Some programmer dude
    Nov 22 '18 at 6:54











  • @Someprogrammerdude I did. Implemented it that way. I got a bunch of errors for example "subscripted value is neither array nor pointer nor vector struct - Google Search". Currently what I have right now I pass just a typedef socket over the socket.

    – pennyBoy
    Nov 22 '18 at 7:04











  • @Someprogrammerdude but thanks for the tips for future use. I appreciate it.

    – pennyBoy
    Nov 22 '18 at 7:05






  • 2





    If you ask about build errors, then besides the Minimal, Complete, and Verifiable example also show us the complete and full output of the compiler, copy-pasted as text into the question. And in the code mark out the places where the errors are with comments. If you get run-time errors or crashes or unexpected results, then please learn how to debug your programs. And tell us the input, the expected and the actual output. Or point out where in your code the crash is. We can't really help you much otherwise.

    – Some programmer dude
    Nov 22 '18 at 7:09













  • I guess, the actual error is in the code which is not exposed. If struct openMessage open[100]; is a local variable in the function where recv() is called its storage is lost after leaving that function. A returned pointer to that array becomes dangling. Using it later (e.g. to call printStruct() with that pointer) would be undefined behavior. Agree: A Minimal, Complete, and Verifiable example is needed to answer this sufficiently.

    – Scheff
    Nov 22 '18 at 7:36


















-2















What if I had a an array of struct. Is it possible for me to send an array of structs over a socket? The struct size will be updated continuously and at any time I would be able to print out the content of the structs. I hope this makes sense, my explanation might not be cleared. My syntax is definitely not correct for some areas, it's just a snippet of what I think it would look like. I just need some guidance.



This will send the array of structs acorss the socket.



void sendOpenMessage(int num0, int num1, int num2){

struct openMessage{
int num0;
int num1;
int num2

};
struct openMessage open[100];
int i = 0;
open[i].num0 = 1;
open[i].num1 = 2;
open[i].num2 = 3;

int length = sizeof(open);
if(send(socket, &open[i], length, 0) == -1){
fprintf(stderr, "Send() failed");
}else{
printf("Open message is being sentn");
}
i++;
}




This will receive the struct and display the contents in a message



  struct openMessage open[100];
if(recv(clnSocket, &open, sizeof(open), 0) < 0){
fprintf(stderr,"Recv() failedn");
printf("Error code: %dn", errno);
}

//Get size of the current struct
//Print out the messages from the structs that have messages?
void printStruct(struct openMessage open){
for(int i = 0; i < sizeof(the struct); i++){
printf("%dn",open[i].num0);
printf("%dn", open[i].num1);
printf("%dn", open[i].num2);
}
}









share|improve this question




















  • 1





    Please try it first. If you get some specific errors or problems, then you're more than welcome to ask about that. Also please review about how to ask good questions, as well as this question checklist. And don't forget how to create a Minimal, Complete, and Verifiable example.

    – Some programmer dude
    Nov 22 '18 at 6:54











  • @Someprogrammerdude I did. Implemented it that way. I got a bunch of errors for example "subscripted value is neither array nor pointer nor vector struct - Google Search". Currently what I have right now I pass just a typedef socket over the socket.

    – pennyBoy
    Nov 22 '18 at 7:04











  • @Someprogrammerdude but thanks for the tips for future use. I appreciate it.

    – pennyBoy
    Nov 22 '18 at 7:05






  • 2





    If you ask about build errors, then besides the Minimal, Complete, and Verifiable example also show us the complete and full output of the compiler, copy-pasted as text into the question. And in the code mark out the places where the errors are with comments. If you get run-time errors or crashes or unexpected results, then please learn how to debug your programs. And tell us the input, the expected and the actual output. Or point out where in your code the crash is. We can't really help you much otherwise.

    – Some programmer dude
    Nov 22 '18 at 7:09













  • I guess, the actual error is in the code which is not exposed. If struct openMessage open[100]; is a local variable in the function where recv() is called its storage is lost after leaving that function. A returned pointer to that array becomes dangling. Using it later (e.g. to call printStruct() with that pointer) would be undefined behavior. Agree: A Minimal, Complete, and Verifiable example is needed to answer this sufficiently.

    – Scheff
    Nov 22 '18 at 7:36














-2












-2








-2








What if I had a an array of struct. Is it possible for me to send an array of structs over a socket? The struct size will be updated continuously and at any time I would be able to print out the content of the structs. I hope this makes sense, my explanation might not be cleared. My syntax is definitely not correct for some areas, it's just a snippet of what I think it would look like. I just need some guidance.



This will send the array of structs acorss the socket.



void sendOpenMessage(int num0, int num1, int num2){

struct openMessage{
int num0;
int num1;
int num2

};
struct openMessage open[100];
int i = 0;
open[i].num0 = 1;
open[i].num1 = 2;
open[i].num2 = 3;

int length = sizeof(open);
if(send(socket, &open[i], length, 0) == -1){
fprintf(stderr, "Send() failed");
}else{
printf("Open message is being sentn");
}
i++;
}




This will receive the struct and display the contents in a message



  struct openMessage open[100];
if(recv(clnSocket, &open, sizeof(open), 0) < 0){
fprintf(stderr,"Recv() failedn");
printf("Error code: %dn", errno);
}

//Get size of the current struct
//Print out the messages from the structs that have messages?
void printStruct(struct openMessage open){
for(int i = 0; i < sizeof(the struct); i++){
printf("%dn",open[i].num0);
printf("%dn", open[i].num1);
printf("%dn", open[i].num2);
}
}









share|improve this question
















What if I had a an array of struct. Is it possible for me to send an array of structs over a socket? The struct size will be updated continuously and at any time I would be able to print out the content of the structs. I hope this makes sense, my explanation might not be cleared. My syntax is definitely not correct for some areas, it's just a snippet of what I think it would look like. I just need some guidance.



This will send the array of structs acorss the socket.



void sendOpenMessage(int num0, int num1, int num2){

struct openMessage{
int num0;
int num1;
int num2

};
struct openMessage open[100];
int i = 0;
open[i].num0 = 1;
open[i].num1 = 2;
open[i].num2 = 3;

int length = sizeof(open);
if(send(socket, &open[i], length, 0) == -1){
fprintf(stderr, "Send() failed");
}else{
printf("Open message is being sentn");
}
i++;
}




This will receive the struct and display the contents in a message



  struct openMessage open[100];
if(recv(clnSocket, &open, sizeof(open), 0) < 0){
fprintf(stderr,"Recv() failedn");
printf("Error code: %dn", errno);
}

//Get size of the current struct
//Print out the messages from the structs that have messages?
void printStruct(struct openMessage open){
for(int i = 0; i < sizeof(the struct); i++){
printf("%dn",open[i].num0);
printf("%dn", open[i].num1);
printf("%dn", open[i].num2);
}
}






c linux sockets






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 22 '18 at 7:29









Scheff

8,36821426




8,36821426










asked Nov 22 '18 at 6:51









pennyBoypennyBoy

809




809








  • 1





    Please try it first. If you get some specific errors or problems, then you're more than welcome to ask about that. Also please review about how to ask good questions, as well as this question checklist. And don't forget how to create a Minimal, Complete, and Verifiable example.

    – Some programmer dude
    Nov 22 '18 at 6:54











  • @Someprogrammerdude I did. Implemented it that way. I got a bunch of errors for example "subscripted value is neither array nor pointer nor vector struct - Google Search". Currently what I have right now I pass just a typedef socket over the socket.

    – pennyBoy
    Nov 22 '18 at 7:04











  • @Someprogrammerdude but thanks for the tips for future use. I appreciate it.

    – pennyBoy
    Nov 22 '18 at 7:05






  • 2





    If you ask about build errors, then besides the Minimal, Complete, and Verifiable example also show us the complete and full output of the compiler, copy-pasted as text into the question. And in the code mark out the places where the errors are with comments. If you get run-time errors or crashes or unexpected results, then please learn how to debug your programs. And tell us the input, the expected and the actual output. Or point out where in your code the crash is. We can't really help you much otherwise.

    – Some programmer dude
    Nov 22 '18 at 7:09













  • I guess, the actual error is in the code which is not exposed. If struct openMessage open[100]; is a local variable in the function where recv() is called its storage is lost after leaving that function. A returned pointer to that array becomes dangling. Using it later (e.g. to call printStruct() with that pointer) would be undefined behavior. Agree: A Minimal, Complete, and Verifiable example is needed to answer this sufficiently.

    – Scheff
    Nov 22 '18 at 7:36














  • 1





    Please try it first. If you get some specific errors or problems, then you're more than welcome to ask about that. Also please review about how to ask good questions, as well as this question checklist. And don't forget how to create a Minimal, Complete, and Verifiable example.

    – Some programmer dude
    Nov 22 '18 at 6:54











  • @Someprogrammerdude I did. Implemented it that way. I got a bunch of errors for example "subscripted value is neither array nor pointer nor vector struct - Google Search". Currently what I have right now I pass just a typedef socket over the socket.

    – pennyBoy
    Nov 22 '18 at 7:04











  • @Someprogrammerdude but thanks for the tips for future use. I appreciate it.

    – pennyBoy
    Nov 22 '18 at 7:05






  • 2





    If you ask about build errors, then besides the Minimal, Complete, and Verifiable example also show us the complete and full output of the compiler, copy-pasted as text into the question. And in the code mark out the places where the errors are with comments. If you get run-time errors or crashes or unexpected results, then please learn how to debug your programs. And tell us the input, the expected and the actual output. Or point out where in your code the crash is. We can't really help you much otherwise.

    – Some programmer dude
    Nov 22 '18 at 7:09













  • I guess, the actual error is in the code which is not exposed. If struct openMessage open[100]; is a local variable in the function where recv() is called its storage is lost after leaving that function. A returned pointer to that array becomes dangling. Using it later (e.g. to call printStruct() with that pointer) would be undefined behavior. Agree: A Minimal, Complete, and Verifiable example is needed to answer this sufficiently.

    – Scheff
    Nov 22 '18 at 7:36








1




1





Please try it first. If you get some specific errors or problems, then you're more than welcome to ask about that. Also please review about how to ask good questions, as well as this question checklist. And don't forget how to create a Minimal, Complete, and Verifiable example.

– Some programmer dude
Nov 22 '18 at 6:54





Please try it first. If you get some specific errors or problems, then you're more than welcome to ask about that. Also please review about how to ask good questions, as well as this question checklist. And don't forget how to create a Minimal, Complete, and Verifiable example.

– Some programmer dude
Nov 22 '18 at 6:54













@Someprogrammerdude I did. Implemented it that way. I got a bunch of errors for example "subscripted value is neither array nor pointer nor vector struct - Google Search". Currently what I have right now I pass just a typedef socket over the socket.

– pennyBoy
Nov 22 '18 at 7:04





@Someprogrammerdude I did. Implemented it that way. I got a bunch of errors for example "subscripted value is neither array nor pointer nor vector struct - Google Search". Currently what I have right now I pass just a typedef socket over the socket.

– pennyBoy
Nov 22 '18 at 7:04













@Someprogrammerdude but thanks for the tips for future use. I appreciate it.

– pennyBoy
Nov 22 '18 at 7:05





@Someprogrammerdude but thanks for the tips for future use. I appreciate it.

– pennyBoy
Nov 22 '18 at 7:05




2




2





If you ask about build errors, then besides the Minimal, Complete, and Verifiable example also show us the complete and full output of the compiler, copy-pasted as text into the question. And in the code mark out the places where the errors are with comments. If you get run-time errors or crashes or unexpected results, then please learn how to debug your programs. And tell us the input, the expected and the actual output. Or point out where in your code the crash is. We can't really help you much otherwise.

– Some programmer dude
Nov 22 '18 at 7:09







If you ask about build errors, then besides the Minimal, Complete, and Verifiable example also show us the complete and full output of the compiler, copy-pasted as text into the question. And in the code mark out the places where the errors are with comments. If you get run-time errors or crashes or unexpected results, then please learn how to debug your programs. And tell us the input, the expected and the actual output. Or point out where in your code the crash is. We can't really help you much otherwise.

– Some programmer dude
Nov 22 '18 at 7:09















I guess, the actual error is in the code which is not exposed. If struct openMessage open[100]; is a local variable in the function where recv() is called its storage is lost after leaving that function. A returned pointer to that array becomes dangling. Using it later (e.g. to call printStruct() with that pointer) would be undefined behavior. Agree: A Minimal, Complete, and Verifiable example is needed to answer this sufficiently.

– Scheff
Nov 22 '18 at 7:36





I guess, the actual error is in the code which is not exposed. If struct openMessage open[100]; is a local variable in the function where recv() is called its storage is lost after leaving that function. A returned pointer to that array becomes dangling. Using it later (e.g. to call printStruct() with that pointer) would be undefined behavior. Agree: A Minimal, Complete, and Verifiable example is needed to answer this sufficiently.

– Scheff
Nov 22 '18 at 7:36












1 Answer
1






active

oldest

votes


















0














First of all, you need to read up about byte ordering and serialisation.



Secondly, length is the size of the whole array, so when i is zero you send the whole array, when i is 1 you send all but the first element plus some garbage at the end, and so on.
Thirdly, when receiving you iterate across sizeof(the struct) members of the array. Don't you want to iterate across the whole array?



When you say the struct size will be updated continuously, do you mean the number of elements in the array? Your struct has a fixed size.



If you are sending variable quantities of data, i.e. if you want to send a piece of data that has one length at one time and another length at another time, or even if you want the number of elements in the array to update dynamically, then you MUST send that size across the socket, and send it before the data. Send the size first, read it first on the receiving end, and then the receiving end will know how much more data to read, and more importantly, where the data ends so that if there is more data later it doesn't all get mixed up.






share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53425334%2fsending-an-array-of-structs-across-a-socket%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    First of all, you need to read up about byte ordering and serialisation.



    Secondly, length is the size of the whole array, so when i is zero you send the whole array, when i is 1 you send all but the first element plus some garbage at the end, and so on.
    Thirdly, when receiving you iterate across sizeof(the struct) members of the array. Don't you want to iterate across the whole array?



    When you say the struct size will be updated continuously, do you mean the number of elements in the array? Your struct has a fixed size.



    If you are sending variable quantities of data, i.e. if you want to send a piece of data that has one length at one time and another length at another time, or even if you want the number of elements in the array to update dynamically, then you MUST send that size across the socket, and send it before the data. Send the size first, read it first on the receiving end, and then the receiving end will know how much more data to read, and more importantly, where the data ends so that if there is more data later it doesn't all get mixed up.






    share|improve this answer




























      0














      First of all, you need to read up about byte ordering and serialisation.



      Secondly, length is the size of the whole array, so when i is zero you send the whole array, when i is 1 you send all but the first element plus some garbage at the end, and so on.
      Thirdly, when receiving you iterate across sizeof(the struct) members of the array. Don't you want to iterate across the whole array?



      When you say the struct size will be updated continuously, do you mean the number of elements in the array? Your struct has a fixed size.



      If you are sending variable quantities of data, i.e. if you want to send a piece of data that has one length at one time and another length at another time, or even if you want the number of elements in the array to update dynamically, then you MUST send that size across the socket, and send it before the data. Send the size first, read it first on the receiving end, and then the receiving end will know how much more data to read, and more importantly, where the data ends so that if there is more data later it doesn't all get mixed up.






      share|improve this answer


























        0












        0








        0







        First of all, you need to read up about byte ordering and serialisation.



        Secondly, length is the size of the whole array, so when i is zero you send the whole array, when i is 1 you send all but the first element plus some garbage at the end, and so on.
        Thirdly, when receiving you iterate across sizeof(the struct) members of the array. Don't you want to iterate across the whole array?



        When you say the struct size will be updated continuously, do you mean the number of elements in the array? Your struct has a fixed size.



        If you are sending variable quantities of data, i.e. if you want to send a piece of data that has one length at one time and another length at another time, or even if you want the number of elements in the array to update dynamically, then you MUST send that size across the socket, and send it before the data. Send the size first, read it first on the receiving end, and then the receiving end will know how much more data to read, and more importantly, where the data ends so that if there is more data later it doesn't all get mixed up.






        share|improve this answer













        First of all, you need to read up about byte ordering and serialisation.



        Secondly, length is the size of the whole array, so when i is zero you send the whole array, when i is 1 you send all but the first element plus some garbage at the end, and so on.
        Thirdly, when receiving you iterate across sizeof(the struct) members of the array. Don't you want to iterate across the whole array?



        When you say the struct size will be updated continuously, do you mean the number of elements in the array? Your struct has a fixed size.



        If you are sending variable quantities of data, i.e. if you want to send a piece of data that has one length at one time and another length at another time, or even if you want the number of elements in the array to update dynamically, then you MUST send that size across the socket, and send it before the data. Send the size first, read it first on the receiving end, and then the receiving end will know how much more data to read, and more importantly, where the data ends so that if there is more data later it doesn't all get mixed up.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 22 '18 at 8:40









        AlastairGAlastairG

        2,47621630




        2,47621630
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53425334%2fsending-an-array-of-structs-across-a-socket%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Guess what letter conforming each word

            Port of Spain

            Run scheduled task as local user group (not BUILTIN)