Can't open socket C++

2019-11-02 02:47发布

我试图通过网络发送图像(使用IlpImage库)到VLAN(媒体播放器),因此它可以播放流图像和“做”的视频。

我试图打开一个套接字但“serversock”的价值带给我总是-1,我不明白为什么。 我试图寻找这个错误,但无法找到一个解决方案。 有人能帮我吗?

下面的代码:

#include <stdio.h>
#include <stdlib.h>
#include <direct.h>
#include <iostream>
#include <WinSock2.h>
#include <Windows.h>
#include <iostream>
#include <string.h>
#include <time.h>
#include <errno.h>
//#include <fstream>

//#include "Packet.h"

#include <opencv2/core/core.hpp>        // Basic OpenCV structures (cv::Mat, Scalar)
#include <opencv2/highgui/highgui.hpp>  // OpenCV window I/O

using namespace std;

#define PORT 8888
#define GROUP "127.0.0.1"

int serversock, clientsock;
int is_data_ready = 0;

//methods
void quit(char* msg, int retval);
void sendImg (IplImage *img);

void sendImg(IplImage *img) {

    struct sockaddr_in server;
    int opt = 1;

    /* setup server's IP and port */
    memset(&server,0,sizeof(server));
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(GROUP);
    server.sin_port = htons(PORT);

    //serversock = socket(AF_INET, SOCK_STREAM, 0);

    serversock = socket(AF_INET, SOCK_DGRAM, 0);

虽然debbuging的价值serversock应为0,它得-1,不与程序仍在进行中。

    if (serversock < 0) { // or == -1
        quit("socket() failed", 1);
    } //else {cout<< "Consegui!" << endl

    cout << "socket() succeeded" << endl;

    if(setsockopt(serversock,SOL_SOCKET,SO_BROADCAST, (const char*) &opt,sizeof(int))==-1){
        quit("setsockopt failed",0);
    }

    /*
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(PORT);
    server.sin_addr.s_addr = INADDR_ANY;*/

    /* bind the socket */
    if (bind(serversock, (const sockaddr*)&server, sizeof(server)) == -1) {
        quit("bind() failed", 1);
    }

    /* wait for connection */
    if (listen(serversock, 10) == -1) {
        quit("listen() failed.", 1);
    }

    /* accept a client */
    if ((clientsock = (int)accept(serversock, NULL, NULL)) == -1) {
        quit("accept() failed", 1);
    }

    /* the size of the data to be sent */
    int imgsize = img->imageSize;
    int bytes=0;

    //start sending images
    if (is_data_ready) {
        is_data_ready = 0;
        if( (bytes = sendto(serversock, img->imageData, imgsize, 0, (struct sockaddr*)&server, sizeof(server)) ) == -1) {
            quit("sendto FAILED", 1);
        }
    }
}

Answer 1:

使用WSAGetLastError()以确定故障的原因:

if (serversocket < 0)
{
    const DWORD last_error = WSAGetLastError();
    // Pass 'last_error' to either the 'quit' function
    // or log it somewhere else.
}

WSAStartup()中不存在的发布代码,并且必须使用任何的套接字API函数之前被调用。



文章来源: Can't open socket C++