udp - Format string error in C over network -


why code segment give output? need packet count increment.

    while(1) {             if(argv[3]) {                     strcpy(buf, argv[3]);             } else {                     msg = "this udp test string! (packet %d)\n", ++pktcnt;                     strcpy(buf, msg);             }              ret = sendto(udpsocket, buf, strlen(buf)+1, 0, (struct sockaddr*)&udpserver, sizeof(udpserver));             if(ret == -1) {                     fprintf(stderr, "could not send message!\n");                     return -1;             } else {                     printf("message sent. (packet %d)\n", pktcnt);             }             sleep(1);     } 

output on receiver:

this udp test string! (packet %d) udp test string! (packet %d) udp test string! (packet %d) 

clearly there problem format string cant figure out :| i'm sure simple error don't know c yet, work in python!

msg = "this udp test string! (packet %d)\n", ++pktcnt 

that not how put formatted string variable in c.

you need use sprintf, , need make sure adequate space allocated in string. example

char msg[200]; sprintf(msg, "this udp test string! (packet %d)\n", ++pktcnt); 

or can put directly buf:

sprintf(buf, "this udp test string! (packet %d)\n", ++pktcnt); 

assuming had enough space there. remember in c must allocate space - functions not , lots of segmentation faults until message….


Comments

Popular posts from this blog

c++ - How to add Crypto++ library to Qt project -

jQuery Mobile app not scrolling in Firefox -

How to use vim as editor in Matlab GUI -