示例代码:
Sock_UDP::Sock_UDP()
{
m_socket = INVALID_SOCKET;
WSAData ws;
//每个Winsock程序必须使用WSAStartup载入合适的Winsock动态链接库,如果载入失败,WSAStartup将返回SOCKET_ERROR,这个错误就是WSANOTINITIALISED
if (WSAStartup(MAKEWORD(2,2),&ws)!=0)
{
LOG("WSAStartup failed! Error: %d", WSAGetLastError());
}
}
Sock_UDP::~Sock_UDP()
{
}
/******************************************************************
* 函数介绍:对连接进行初始化
* 输入参数: strIPAddress:广播的ip地址,strPort: 端口号
* 输出参数:
* 返回值 :
*******************************************************************/
BOOL Sock_UDP::InitSocket(const CString strIPAddress,const CString strPort)
{
//创建套接字,ipv4,报文,udp协议
m_socket = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
//创建socket失败
if (INVALID_SOCKET == m_socket)
{
LOG("failed to create socket");
return false;
}
//初始化sock地址
InitSockAddress(strIPAddress,strPort);
// 绑定
if (bind (m_socket,
(struct sockaddr FAR *) &m_sockLocalAddress,
sizeof (m_sockLocalAddress)) == SOCKET_ERROR)
{
//报错
LOG("Binding socket failed! Error: %d" ,WSAGetLastError());
closesocket (m_socket);
return false;
}
int iOptVal=64; //1秒
// 设置组播存活时间
if (setsockopt (m_socket,
IPPROTO_IP,
3,
(char FAR *)&iOptVal,
sizeof (int)) == SOCKET_ERROR)
{
//报错
LOG("setsockopt failed! Error: %d" ,WSAGetLastError());
closesocket (m_socket);
return false;
}
return true;
}
/******************************************************************
* 函数介绍:关闭socket
* 输入参数:
* 输出参数:
* 返回值 :
*******************************************************************/
void Sock_UDP::CleanSocket()
{
shutdown(m_socket,0x01);
closesocket(m_socket);
WSACleanup();
}
/******************************************************************
* 函数介绍:初始化IP组播地址和端口
* 输入参数:strIPAddress:ip地址,strPort: 端口号
* 输出参数:
* 返回值 :
*******************************************************************/
void Sock_UDP::InitSockAddress(const CString strIPAddress,const CString strPort)
{
//本地sock地址设置
m_sockLocalAddress.sin_family = AF_INET; //ipv4地址类型
m_sockLocalAddress.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
m_sockLocalAddress.sin_port = htons(0);
memset(m_sockLocalAddress.sin_zero,0,8);
//目的sock地址设置
//IPv4版本
m_sockDesAddress.sin_family = AF_INET;
//端口
m_sockDesAddress.sin_port = htons (atol(strPort));
//地址
m_sockDesAddress.sin_addr.s_addr = inet_addr (strIPAddress);
}
posted on 2013-06-19 18:00
王海光 阅读(6873)
评论(0) 编辑 收藏 引用 所属分类:
C++