使用winsock2.h在c ++中连接和发送数据时出错

时间:2016-04-07 19:27:15

标签: c++ sockets winsock2

我一直在尝试用c ++执行套接字编程。我已经在互联网上查找了这段代码,根据网站的说法,它的工作正常。但是我通过连接发送数据时收到错误。这是代码段。

#include <iostream>
#include <winsock2.h>
#include <string>
#include <conio.h>

int main()
{
    WSAData version;        //We need to check the version.
    WORD mkword=MAKEWORD(2,2);
    int what=WSAStartup(mkword,&version);
    if(what!=0){
        std::cout<<"This version is not supported! - \n"<<WSAGetLastError()  <<std::endl;
    }
    else{
        std::cout<<"Good - Everything fine!\n"<<std::endl;
    }

    SOCKET u_sock=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
    if(u_sock==INVALID_SOCKET)
        std::cout<<"Creating socket fail\n";

    else
        std::cout<<"It was okay to create the socket\n";

    //Socket address information
    sockaddr_in addr;
    addr.sin_family=AF_INET;
    addr.sin_addr.s_addr=inet_addr("192.168.43.194");
    addr.sin_port=htons(80);
    /*==========Addressing finished==========*/

    //Now we connect
    int conn=connect(u_sock,(SOCKADDR*)&addr,sizeof(addr));
    if(conn==SOCKET_ERROR){
        std::cout<<"Error - when connecting "<<WSAGetLastError()<<std::endl;
        closesocket(u_sock);
        WSACleanup();
    }

    //Send some message to remote host
    char* mymsg="GET / HTTP/1.1\r\n\r\n";
    char vect[512]={0};

    int smsg=send(u_sock,mymsg,sizeof(mymsg),0);
    if(smsg==SOCKET_ERROR){
        std::cout<<"Error: "<<WSAGetLastError()<<std::endl;
        WSACleanup();
    }

    int get=recv(u_sock,vect,512,0);
    if(get==SOCKET_ERROR){
        std::cout<<"Error in Receiving: "<<WSAGetLastError()<<std::endl;
    }
    std::cout<<vect<<std::endl;
    closesocket(u_sock);
    _getch();
    return 0;
}

0 个答案:

没有答案