Re: copy struct to buffer
- From: Giorgos Keramidas <keramida@xxxxxxxxxxxxxxx>
- Date: Fri, 02 Jun 2006 22:09:12 +0300
On 2 Jun 2006 10:49:13 -0700, bofh1234@xxxxxxxxxxx wrote:
Hello everyone,
I am writing a multicast application and I am having a small
problem converting a struct to a string. Right now I have my
program setup so when msgtype=1 the program calls the showinfo
function which builds the showinfop packet. When I got to the
write statement in the showinfo function I removed it and put
sendmessage(serverinfo, &showinfop); //warning showinfop is a struct.
sendmessage is supposed to send off the data but instead I get
a segmentation fault. The obvious fix is to have 7 different
sendmessage functions (1 for each packet type), but that is a
lot of redundant code. How can I make sendmessage generic
enough so it works for all 7 types. My guess is that I will
have to convert the packet I built to a long string, but I
don't know how to that. I do get a warning: passing argument 2
of 'sendmessage' from incompatible pointer type
Thanks.
void sendmessage(char *serverinfo, char sendBuf[256])
{
struct sockaddr_in dest;
int Sock=-1, i;
char *server, *portnum;
char serverstring[64];
if ((Sock = socket(PF_INET, SOCK_DGRAM, 0)) < 0) {
printf("can't create socket: %s \n", strerror(errno));
exit(-1);
}
server = strtok(serverinfo, "/");
portnum = strtok(NULL, "/");
dest.sin_family = AF_INET;
dest.sin_port = atoi(portnum);
dest.sin_addr.s_addr = inet_addr(server);
printf("HERE\n");
for (i = 1; i <= numofservers; i++) {
printf("Msg Sent:%s", sendBuf); //seg fault here
strncpy(serverstring, server[i], 64);
printf("ss \n",serverstring);
dest.sin_addr.s_addr = inet_addr(serverstring);
if (sendto(Sock,sendBuf,strlen(sendBuf), 0,
(struct sockaddr *)&dest,sizeof(dest)) < 0 ) {
printf("error in sendto \n");
exit(-1);
}
sleep(1);
}
}
If you are passing arbitrary binary data (like a raw struct
object) to sendmessage(), you cannot assume that normal C string
functions can work on that raw data.
printf() cannot be used to print sendBuf[], even though the type
of sendBuf[] is 'array of char'. The same is true for all
functions that assume a C string (i.e. zero or more characters
which are *not* '\0', terminated by a '\0' character).
.
- References:
- copy struct to buffer
- From: bofh1234
- copy struct to buffer
- Prev by Date: copy struct to buffer
- Next by Date: Re: Scheduling algorithm
- Previous by thread: copy struct to buffer
- Next by thread: Re: copy struct to buffer
- Index(es):
Relevant Pages
|