0

How do I send the data in struct in UDP sendto in C++?

struct routingTable{
    int numServers;
    int numNeighbors;
    int selfId,neighborNode[5];
    int Cost[6][6];
};

routingTable selfRoutingTable;
sendto(listener_socket,<This is a char *> , strlen(my_message), 0, (struct sockaddr *)&nbaddr, sizeof(nbaddr)
1
  • 1
    Err, with a cast, and sizeof instead of strlen(), but you should not do this. Don't use structs as network protocols. Commented Nov 18, 2016 at 21:36

1 Answer 1

3
sendto(listener_socket,<This is a char *> , strlen(my_message), 0, (struct sockaddr *)&nbaddr, sizeof(nbaddr)

No it's not, it's a const void *. From a man page:

ssize_t sendto(int sockfd, const void *buf, size_t len, int flags,
               const struct sockaddr *dest_addr, socklen_t addrlen);

Technically you could send your struct with: &selfRoutingTable and use sizeof for the size, but see below.


As EJP mentioned this is a pretty bad idea and you'll quickly run into issues with representations of the struct and its fields on different implementations (and you'll find out all about struct field padding and the like).

Look into a serialization mechanism (json, capnproto, protobufs, xml, asn.1 anything).


I now realize that "no it's not" is not always true. Apparently MSDN lists sendto as taking a const char *.

int sendto(
  _In_       SOCKET                s,
  _In_ const char                  *buf,
  _In_       int                   len,
  _In_       int                   flags,
  _In_       const struct sockaddr *to,
  _In_       int                   tolen
);

The idea (of passing the pointer to whatever one wants) stands.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.