Change the values in a text and store it a char array in C
I need some information regarding a scenario开发者_开发问答 where I have an array stored with SIP INVITE message
char array_invite[] = "INVITE sip:302@1.2.3.4 SIP/2.0\r\n"
"Via:SIP/2.0/UDP 5.6.7.8:39708;\r\n"
"Max-Forwards: 70\r\n"
"Contact:<sip:305@ 5.6.7.8>\r\n"
"To: <sip:302@1.2.3.4>; \r\n"
"From: \042Client\042<sip:305@5.6.7.8>;\r\n"
"Call-ID: abcdefg\r\n"
"CSeq: 1 INVITE\r\n"
"Content-Type: application/sdp\r\n"
"Content-Length: 142\r\n";
I want to change the hard code values for the IP Address (1.2.3.4 and 5.6.7.8) and the ID number(302 and 305) and make it dynamic such that I want to enter the values manually in my terminal output so that for each session I can connect to different remote addresses. Since I am not that fluent in C I am posting this question.
Anybody has an idea of how this can be done in C, may be an example would be good
Regards Dev
Using sprintf
will work.
char array_invite[MAXLENGTH];
sprintf(array_invite,"Meet me at port %d\n",portnum);
You should use snprintf()
to build the string from a formatting "template", like so:
char buffer[4096];
int ip{[4];
ip[0] = 1;
ip[1] = 2;
ip[2] = 3;
ip[3] = 4;
snprintf(buffer, sizeof buffer, "INVITE sip:302@%d.%d.%d.%d SIP/2.0\r\n"
"Via:SIP/2.0/UDP 5.6.7.8:39708;\r\n"
"Max-Forwards: 70\r\n"
"Contact:<sip:305@ 5.6.7.8>\r\n"
"To: <sip:302@1.2.3.4>; \r\n"
"From: \042Client\042<sip:305@5.6.7.8>;\r\n"
"Call-ID: abcdefg\r\n"
"CSeq: 1 INVITE\r\n"
"Content-Type: application/sdp\r\n"
"Content-Length: 142\r\n", ip[0], ip[1], ip[2], ip[3]);
Here, I only templatized the first IP address, and represented it as four int
:s. You will need to extend this for the rest of the fields that you want to format dynamically.
精彩评论