SOCKET實現廣播(BoardCast)的傳送和接收 (轉)

worldblog發表於2007-12-13
SOCKET實現廣播(BoardCast)的傳送和接收 (轉)[@more@]

這兩天很多人在問怎麼樣用SOCKET實現廣播(BoardCast)


正好我做過這方面的,這裡用最簡單的程式碼寫一個廣播傳送和接受的例子:


//////


//傳送端程式


#include
#include


int main(int argc, char* argv[])
{
  WSADATA wsaData;  //指向WinSocket資訊結構的指標
  SOCKET sockListener;
  SOCKADDR_IN sin,saUdpServ;
  BOOL fBroadcast = TRUE;
  char senuff[1024];
  int nSize;
  int ncount=0;
  if(Wtartup(MAKE( 1, 1 ), &wsaData )!=0)//進行WinSocket的初始化
  {
  printf("Can't initiates socket!Program stop.n");//初始化失敗返回-1
  return -1;
 }
  sockListener=socket(PF_,SOCK_DGRAM,0);
  setsockopt ( sockListener,SOL_SOCKET,SO_BROADCAST,


  (CHAR *)&fBroadcast,sizeof ( BOOL ));
  sin.sin_family = AF_INET;
  sin.sin_port = htons(0);
  sin.sin_addr.s_addr = htonl(INADDR_ANY);
  if(bind( sockListener, (SOCKADDR *)&sin, sizeof(sin))!=0)
  {
  printf("Can't bind socket to local port!Program stop.n");//初始化失敗返回-1
  return -1;
  }
  saUdpServ.sin_family = AF_INET;
  saUdpServ.sin_addr.s_addr = htonl ( INADDR_BROADCAST );
  saUdpServ.sin_port = htons (7001);//傳送用的埠,可以根據需要更改
  nSize = sizeof ( SOCKADDR_IN );
  while(1)
  {
  sprintf(sendBuff,"Message %d",ncount++);
  sendto ( sockListener,sendBuff,
  lstrlen (sendBuff),
  0,
  (SOCKADDR *) &saUdpServ,
  sizeof ( SOCKADDR_IN ));
  printf("%sn",sendBuff);
  }
return 0;
}


 


/////////////////////


//接收


 


#include
#include
#include


int main(int argc, char* argv[])
{
  WSADATA wsaData;  //指向WinSocket資訊結構的指標
  SOCKET sockListener;
  SOCKADDR_IN sin,saClient;
  char cRecvBuff[1024];
  int nSize,nbSize;
  int iAddrLen=sizeof(saClient);
  if(WSAStartup(MAKEWORD( 1, 1 ), &wsaData )!=0)//進行WinSocket的初始化
  {
 printf("Can't initiates windows socket!Program stop.n");//初始化失敗返回-1
  return -1;
  }
  sockListener=socket(AF_INET, SOCK_DGRAM,0);
  sin.sin_family = AF_INET;
  sin.sin_port = htons(7001);//傳送端使用的傳送埠,可以根據需要更改
  sin.sin_addr.s_addr = htonl(INADDR_ANY);
  if(bind( sockListener, (SOCKADDR FAR *)&sin, sizeof(sin))!=0)
  {
  printf("Can't bind socket to local port!Program stop.n");//初始化失敗返回-1
  return -1;
  }
  while(1)
  {
  nSize = sizeof ( SOCKADDR_IN );
  if((nbSize=recvfrom (sockListener,cRecvBuff,1024,0,


  (SOCKADDR FAR *) &saClient,&nSize))==SOCKET_ERROR)
  {
  printf("Recive Error");
  break;
  }
  cRecvBuff[nbSize] = '';
  printf("%sn",cRecvBuff);


  }
  return 0;
}


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/10752043/viewspace-992490/,如需轉載,請註明出處,否則將追究法律責任。

相關文章