sip协议的通信是在应用层,传输层依靠UDP进行传输。
注册流程简单来说就是:客户端发送register请求,服务器通过鉴权判断客户端号码是否存在,如果需要密码就回复401 Unauthorized,如果不需要密码就直接回复200 OK,客户端收到鉴权要求后根据401 Unauthorized携带的编号以及加密协议(例如MD5)将密码添加进去,重新发送register,服务器判断正确后回复200 OK,注册成功。
代码层面上则是:以C# 使用LumiSoft.Net.SIP 组件为例
1、先UDP bind,将网络打通。
SIP_Stack m_pStack = null;
//先检查音频输入输出设备是否正常
if(AudioOut.Devices.Length == 0 || AudioIn.Devices.Length == 0)
{
Log.Debug(string.Format("audioOutDev: {0}, audioInDev: {1}", AudioOut.Devices.Length, AudioIn.Devices.Length));
return;
}
m_pAudioOut = null;
m_pAudioOutDevice = AudioOut.Devices[0];
m_pAudioInDevice = AudioIn.Devices[0];
m_pAudioCodecs = new Dictionary<int,AudioCodec>();
m_pAudioCodecs.Add(0,new PCMU());
m_pAudioCodecs.Add(8,new PCMA());
m_NatHandlingType = "no_nat";
//将ip,端口,用户别名 添加至stack中
string gw = TelephoneConfigure.GetInstance().IP;
m_pStack = new SIP_Stack(IpToInt(gw));
m_pStack.UserAgent = "LumiSoft SIP UA 1.0";
m_pStack.BindInfo = new IPBindInfo[]{new IPBindInfo("",BindInfoProtocol.UDP,IPAddress.Any,m_SipPort)};
m_pStack.Error += new EventHandler<ExceptionEventArgs>(m_pStack_Error);
m_pStack.RequestReceived += new EventHandler<SIP_RequestReceivedEventArgs>(m_pStack_RequestReceived);//绑定状态接收函数
m_pStack.Start();
2、发起注册请求
//将目的ip端口转换成路径格式 RegistrarServer:"sip:服务器地址:端口"
SIP_Uri registrarServer = SIP_Uri.Parse(account.RegistrarServer);
//AOR:"客户端号码@服务器地址" RegisterInterval:注册间隔
SIP_UA_Registration registration = m_pStack.CreateRegistration(
registrarServer,
account.AOR,
AbsoluteUri.Parse(registrarServer.Scheme + ":" + account.AOR.Split('@')[0] + "@auto-allocate"),
account.RegisterInterval
);
//注册请求回复状态处理函数
registration.StateChanged += new EventHandler(Registration_StateChanged);
registration.BeginRegister(true);