C ++中的多播:错误“在getsockopt或setsockopt调用中指定了未知,无效或不受支持的选项或级别”

时间:2010-08-31 07:13:04

标签: c++

我已经开发了一个服务器pgm用于C ++中的多播,当我注册地址时,之后当我使用setsockopt设置套接字选项时它返回-1

如果setsockopt不支持此选项,那么我如何在C ++中进行多播

我的代码如下:

#include"winsock.h"
#include<iostream>
#include<conio.h>

using namespace std;

#define MYPORT 9009 // the port users will be connecting to






#define MAXBUFSIZE 65536 // Max UDP Packet size is 64 Kbyte

int main()
{


    WSADATA wsaData;
    WSAStartup(MAKEWORD(2,2), &wsaData);

   int sock, status, socklen;
   char buffer[MAXBUFSIZE];
   struct sockaddr_in saddr;
   struct ip_mreq imreq;

   // set content of struct saddr and imreq to zero
   memset(&saddr, 0, sizeof(sockaddr_in));
   memset(&imreq, 0, sizeof(ip_mreq));

   // open a UDP socket
   sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
   if ( sock < 0 )
     perror("Error creating socket"), exit(0);

   saddr.sin_family = PF_INET;
   saddr.sin_port = htons(4849); // listen on port 4096
   saddr.sin_addr.s_addr = htonl(INADDR_ANY); // bind socket to any interface
   status = bind(sock, (sockaddr *)&saddr, sizeof(sockaddr_in));

   if ( status < 0 )
     perror("Error binding socket to interface"), exit(0);

   imreq.imr_multiaddr.s_addr = inet_addr("226.0.0.1");
   imreq.imr_interface.s_addr = htonl(INADDR_ANY); // use DEFAULT interface

   // JOIN multicast group on default interface
   **status = setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, 
              (const char *)&imreq, sizeof(ip_mreq));** // This line return -1



   socklen = sizeof(struct sockaddr_in);

   // receive packet from socket
   status = recvfrom(sock, buffer, MAXBUFSIZE, 0, 
                     (struct sockaddr *)&saddr, &socklen);


   if(status < 0)

   {
      printf("Received failed");
   }
   else

   {
       printf("received buffer : %s",buffer);
   }

   // shutdown socket
   shutdown(sock, 2);
   // close socket
   closesocket(sock);

   return 0;
}

//我认为它无法注册接口地址。 有没有人对此有所了解? 提前致谢

2 个答案:

答案 0 :(得分:0)

尝试从GetLastError

获取帮助
DWORD err = GetLastError();

在观察窗口中输入err,hr

它显示An unknown, invalid, or unsupported option or level was specified in a getsockopt or setsockopt call.#define WSAENOPROTOOPT

然后我查看了http://msdn.microsoft.com/en-us/library/ms740476(VS.85).aspx

IPPROTO_IP没有出现在支持的级别列表中。

由于我对此不太熟悉,所以我只能提供帮助。抱歉。希望你可以从这里拿起它

答案 1 :(得分:0)

我解决了上述问题。

只需用wsock32.lib替换ws2_32.lib即可。 这将解决问题。