#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
int so_broadcast=1;
int ret;
wVersionRequested = MAKEWORD( 2, 2 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 ) {
return 1;
}
SOCKET fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (fd == INVALID_SOCKET) {
printf("Error at socket(): %ld\n", WSAGetLastError() );
WSACleanup();
return 1;
}
err = setsockopt(fd,SOL_SOCKET,SO_BROADCAST,(char*)&so_broadcast,sizeof(so_broadcast));
if ( err != 0 ) {
printf("Error at setsockopt(): %ld\n", WSAGetLastError() );
WSACleanup();
return 1;
}
char buf[256];
sprintf(buf,"%d",12345678);
sockaddr_in addr;
addr.sin_family = AF_INET;
//受限广播地址,需要设置调用setsockopt(),用SO_BROADCAST选项!
//addr.sin_addr.s_addr = inet_addr( "255.255.255.255");
//直接广播地址
addr.sin_addr.s_addr = inet_addr( "192.168.1.255");
addr.sin_port = htons( 5005);
ret = sendto(fd,buf,strlen(buf)+1,0,(sockaddr*)&addr,sizeof(addr));
printf("sended len=%d \n",ret);
if (ret==-1){
err = WSAGetLastError();
printf("err=%d \n",err);
}
WSACleanup();
return 0;
}