Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Folks, I am trying to write a simulator based on SIP (session initiation protocol). When it receives a request, it needs to send a response as follows.
Received request:
INVITE sip:bob@biloxi.com SIP/2.0 Via: SIP/2.0/UDP pc33.atlanta.com;branch=z9hG4bK776asdhds Max-Forwards: 70 To: Bob <sip:bob@biloxi.com> From: Alice <sip:alice@atlanta.com>;tag=1928301774 Call-ID: a84b4c76e66710@pc33.atlanta.com CSeq: 314159 INVITE Contact: <sip:alice@pc33.atlanta.com> Content-Length: 0
And the response must be something like
200 SIP/2.0 OK Via: SIP/2.0/UDP pc33.atlanta.com;branch=z9hG4bK776asdhds Max-Forwards: 70 To: Bob <sip:bob@biloxi.com> From: Alice <sip:alice@atlanta.com>;tag=1928301774 Call-ID: a84b4c76e66710@pc33.atlanta.com CSeq: 314159 INVITE Contact: <sip:alice@pc33.atlanta.com> Content-Length: 0
Only the first line in the response changes. Everything else is same from received request. This is what I tried but didnt help....
------------------------------------------
my $length = $sock->recv($sip_request,1000); print "\nReceived message '", $request,"'\n"; my @headers = split/\n/, $request; my $tmp = 0; foreach my $line (@headers) { if ($tmp gt 0) { $sip_response = join($sip_response, $line, "\n"); } $tmp++; } print "Our response is : \n"; print $sip_response;
---------------------------------------------
But I am not able to form the proper response. Could any of you help me out?

Replies are listed 'Best First'.
Re: splitting and joining a network message
by davido (Cardinal) on Apr 12, 2006 at 16:23 UTC

    You are using join wrong. Join's args are (first) the new delimiter, and (second) the list of strings being joined. I think that you probably don't even want join at all, you probably (based on your existing code) simply want concatenation as follows:

    if( $tmp > 0 ) { $sip_response .= "$line\n"; }

    Also notice the use of '>' instead of 'gt'. 'gt' is for strings, and '>' is for numbers. Your use of 'gt' works for you, but only by virtue of the fact that Perl considers any non-empty, non-zero string to be "true".

    Additional thought:
    An easier way to do the whole thing is probably something like this:

    my $sip_response = $response; # Make a copy of the response. if( $sip_response =~ s{^[^\n]+}[200 SIP/2.0 OK] ) { print $sip_response; } else { die "Didn't understand the response: $response\n"; }

    ...just a thought...


    Dave