使用C#发送SIP消息

时间:2016-12-05 22:05:33

标签: c# sip

我正在尝试向我们的SIP电话发送预定义的消息,这将在C#中触发事件(重新启动)。我发现了一些其他语言的脚本(perl / python),这些脚本正是我想要做的,但之前从未这样做过。我有大部分移植,但实际上不知道我是否拥有所有正确的元素。这是我试图移植的脚本:

#!/usr/bin/perl -w

use Net::Ping;
use Socket;

my $phone_ip = $ARGV[0];
sub reboot_sip_phone {    # Send the phone a check-sync to reboot it

$local_ip = $phone_ip;
$sip_to   = $phone_ip;
$sip_from = "0";
$tm       = time();
$call_id  = $tm . "msgto$sip_to";
$httptime = `date -R`;
$MESG     = "NOTIFY sip:$sip_to\@$phone_ip:5060 SIP/2.0
             Via: SIP/2.0/UDP $local_ip
             From: <sip:$sip_from\@$local_ip>
             To: <sip:$sip_to\@$phone_ip>
             Event: check-sync
             Date: $httptime
             Call-ID: $call_id\@$local_ip
             CSeq: 1300 NOTIFY
             Contact: <sip:$sip_from\@$local_ip>
             Content-Length: 0 ";

$proto = getprotobyname('udp');
socket( SOCKET, PF_INET, SOCK_DGRAM, $proto );
$iaddr = inet_aton("$phone_ip");
$paddr = sockaddr_in( 5060, $iaddr );
bind( SOCKET, $paddr );
$port = 5060;

$hisiaddr = inet_aton($phone_ip);
$hispaddr = sockaddr_in( $port, $hisiaddr );

if ( send( SOCKET, $MESG, 0, $hispaddr ) ) {
    print "reboot of phone ", "$phone_ip", " was successful", "\n";
}
else { print "reboot of phone ", "$phone_ip", " failed", "\n"; }

}
exit;

到目前为止,这是我的代码:

class Driver
{

    static void Main(string[] args)
    {
        if (!String.IsNullOrEmpty(args[0]))
        {
            var phone_ip = args[0];
            SipMessage newMsg = new SipMessage(phone_ip);
            IPAddress addr = IPAddress.Parse(phone_ip);
            IPEndPoint end_point = new IPEndPoint(addr, 5060);
            Socket socket = new Socket(AddressFamily.InterNetwork,SocketType.Dgram, ProtocolType.Udp);
            byte[] send_buffer = Encoding.ASCII.GetBytes(newMsg.ToString());
            Console.WriteLine("sending message: " + newMsg.ToString());
            socket.SendTo(send_buffer, end_point);
            Console.WriteLine("Sent message to " + phone_ip);
        }
        else Console.WriteLine("Message did not send");
    }
}

class SipMessage
{
    private string _to, _from, _call_id, _msg;
    private DateTime _time;

    public SipMessage(string p_ip = "")
    {
        _to = p_ip;
        _from = "<sip:test>";
        _time = DateTime.Now;
        _call_id = _time.ToString() + "msgto" + _to;
        _msg = String.Format("NOTIFY sip:" + _to + ":5060 SIP/2.0" +
                            "\nVia: SIP/2.0/UDP " + _to +
                            "\nFrom: {0};tag=1530231855-106746376154 " +
                            "\nTo: <sip:{1}:5060> " +
                            "\nEvent: check-sync " +
                            "\nDate: {2} " +
                            "\nCall-ID: {3} " +
                            "\nCSeq: 1 NOTIFY " +
                            "\nContact: {0} " +
                            "\nContent-Length: 0 ", _from, _to, _time, _call_id);
    }
    public override string ToString()
    {
         return _msg;
    }
}

}

我已经运行了代码并在手机上进行了测试,但它不会启动事件。我是在正确的轨道上吗?我错过了什么吗?

1 个答案:

答案 0 :(得分:2)

作为替代方案,您可以使用我的C#sipsorcery nuget包。

using System;
using System.Net;
using System.Threading;
using SIPSorcery.SIP;
using SIPSorcery.SIP.App;
using SIPSorcery.Sys;
using SIPSorcery.Sys.Net;

namespace SipSendNotify
{
    class Program
    {
        private const int _defaultSIPUdpPort = SIPConstants.DEFAULT_SIP_PORT;             // The default UDP SIP port.
        private static SIPTransport _sipTransport;

        static void Main(string[] args)
        {
            try
            {
                // Configure the SIP transport layer.
                _sipTransport = new SIPTransport(SIPDNSManager.ResolveSIPService, new SIPTransactionEngine());

                // Use default options to set up a SIP channel.
                var localIP = LocalIPConfig.GetDefaultIPv4Address(); // Set this manually if needed.
                int port = FreePort.FindNextAvailableUDPPort(_defaultSIPUdpPort);
                var sipChannel = new SIPUDPChannel(new IPEndPoint(localIP, port));
                _sipTransport.AddSIPChannel(sipChannel);

                SIPCallDescriptor callDescriptor = new SIPCallDescriptor("test", null, "sip:500@67.222.131.147", "sip:you@somewhere.com", null, null, null, null, SIPCallDirection.Out, null, null, null);
                SIPNonInviteClientUserAgent notifyUac = new SIPNonInviteClientUserAgent(_sipTransport, null, callDescriptor, null, null, (monitorEvent) => { Console.WriteLine("Debug: " + monitorEvent.Message); });
                notifyUac.ResponseReceived += (resp) => { Console.WriteLine(resp.ToString()); };

                notifyUac.SendRequest(SIPMethodsEnum.NOTIFY);

                ManualResetEvent mre = new ManualResetEvent(false);
                mre.WaitOne();
            }
            catch (Exception excp)
            {
                Console.WriteLine("Exception Main. " + excp);
            }
            finally
            {
                Console.WriteLine("Press any key to exit...");
                Console.ReadLine();
            }
        }
    }
}