#include <winsock2.h> #pragma comment(lib, "ws2_32.lib")
void wsaShowError();//Вывод сообщений о ошибках
int main() { WSADATA wsaData; if(!WSAStartup(0x0202,&wsaData)) { SOCKET SockBroad = socket(AF_INET,SOCK_DGRAM,0); if(SockBroad != INVALID_SOCKET) { BOOL bBroad = TRUE; if(!setsockopt(SockBroad,SOL_SOCKET,SO_BROADCAST,(char*)&bBroad,sizeof(BOOL))) { SOCKADDR_IN saUdp; saUdp.sin_family = AF_INET; saUdp.sin_addr.s_addr = htonl(INADDR_BROADCAST); saUdp.sin_port = htons(4004); char * szMessage ="Test Broadcast Message"; if(sendto(SockBroad,szMessage,lstrlen(szMessage),0,(SOCKADDR*)&saUdp,sizeof(SOCKADDR_IN)) != SOCKET_ERROR) { closesocket(SockBroad); }else{wsaShowError();} }else{wsaShowError();} }else{wsaShowError();} }else{wsaShowError();} if(WSACleanup()){wsaShowError();} return 0; }
void wsaShowError() { LPVOID lpMsgBuf = NULL; FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM, NULL, WSAGetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, NULL); MessageBox(NULL,(LPCTSTR)lpMsgBuf,"Error",MB_OK|MB_ICONSTOP); LocalFree(lpMsgBuf); }
Пример создавался в Win32 Console Application, для работы программы необходимо в свойствах проекта(Alt+F7) указать «Use MFC in a Shared DLL»
#include <afxsock.h>
int main() { if(AfxSocketInit()) { CSocket m_sock; if(m_sock.Create(3004,SOCK_DGRAM)) { BOOL bBroadcast = TRUE; if(m_sock.SetSockOpt(SO_BROADCAST,&bBroadcast,sizeof(BOOL))!=SOCKET_ERROR) { CString m_message = "Test Broadcast Message"; if(m_sock.SendTo(LPCTSTR(m_message),m_message.GetLength(),4004,NULL,0)==SOCKET_ERROR) {/*error*/} }else{/*error*/} m_sock.Close(); }else{/*error*/} }else{/*error*/} return 0; }
|