马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
在bind 广播地址 会一直返回-1,忽略即可~
广播你懂的,局域网virus,通信必备。
服务器代码:#include <stdio.h>
#include <windows.h>
#pragma comment(lib,"ws2_32.lib")
#define ServicPort 1447
void showerr(char * err,bool exit1)
{
printf(err);
if(exit1)
{
getchar();
exit(0);
}
}
int main()
{
WSAData wdata;
WSAStartup(MAKEWORD(2,2),&wdata);
SOCKET service;
SOCKADDR_IN saddr={0};
service = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
int iaddrlen;
if(service == INVALID_SOCKET)
{
showerr("不能创建套接字!\n",true);
return 0;
}
saddr.sin_port = htons(ServicPort);
saddr.sin_family = AF_INET;
saddr.sin_addr.S_un.S_addr = INADDR_BROADCAST;
iaddrlen = sizeof(SOCKADDR_IN);
//设置该套接字为广播类型
bool bOpt = true;
setsockopt(service,SOL_SOCKET,SO_BROADCAST,(char *)&bOpt,sizeof(bOpt));
int err = bind(service,(SOCKADDR * )&saddr,iaddrlen);
while(true)
{
char * buffer = "Hello world!\n There is socket broadcast test !\n";
int iret =
sendto(service,buffer,strlen(buffer),0,(SOCKADDR * )&saddr,iaddrlen);
if(iret == SOCKET_ERROR)
printf("Send failed!\n");
else
printf("Success \n");
Sleep(500);
}
return 0;
}
接收器代码:#include <stdio.h>
#include <windows.h>
#pragma comment(lib,"ws2_32.lib")
#define ServicPort 1447
void showerr(char * err,bool exit1)
{
printf(err);
if(exit1)
{
getchar();
exit(0);
}
}
int main()
{
WSAData wdata;
WSAStartup(MAKEWORD(2,2),&wdata);
SOCKET connect_sock;
SOCKADDR_IN saddr={0};
SOCKADDR_IN saddr_from={0};
connect_sock = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
int iaddrlen;
if(connect_sock == INVALID_SOCKET)
{
showerr("不能创建套接字!\n",true);
return 0;
}
saddr.sin_port = htons(ServicPort);
saddr.sin_family = AF_INET;
saddr.sin_addr.S_un.S_addr = 0;
saddr_from.sin_port = htons(ServicPort);
saddr_from.sin_family = AF_INET;
saddr_from.sin_addr.S_un.S_addr = INADDR_BROADCAST;
iaddrlen = sizeof(SOCKADDR_IN);
//设置该套接字为广播类型
bool bOpt = true;
setsockopt(connect_sock,SOL_SOCKET,SO_BROADCAST,(char *)&bOpt,sizeof(bOpt));
int err = bind(connect_sock,(SOCKADDR * )&saddr,iaddrlen);
if(err != 0)
{
printf("%d %d\n",err,WSAGetLastError());
showerr("绑定套接字失败!\n",true);
}
int count = 0;
while(true)
{
char buffer[1024]={0};
int nsize;
nsize = recvfrom(connect_sock,buffer,1024,0,(SOCKADDR *)&saddr_from,&iaddrlen);
if(nsize>0)
printf("%d : %s \n\n",count++,buffer);
Sleep(2000);
}
return 0;
}
|