问题
I'm trying to send images (using IlpImage library) to VLan (media player) through the network so it can play streaming images and "make" a video.
I'm trying to open a socket but the value of "serversock" gives me always -1 and I don't understand why. I'm trying to search for this error but can't find a solution. Can someone help me?
Here's the code:
#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);
While debbuging the value of serversock
should be 0 and it gets -1, not continuing with the program.
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);
}
}
}
回答1:
Use WSAGetLastError() to determine the cause of the failure:
if (serversocket < 0)
{
const DWORD last_error = WSAGetLastError();
// Pass 'last_error' to either the 'quit' function
// or log it somewhere else.
}
WSAStartup() is not present in the posted code and it must be called before using any of the socket API functions.
来源:https://stackoverflow.com/questions/16298423/cant-open-socket-c