Winsock代码不起作用

时间:2016-01-19 15:26:53

标签: c++ winsock

我已经完成了我的c ++教程并转到了winsock,但对这个主题还是有点新意。我制作了一个客户端代码,尝试使用端口80(http)连接到网站,但每当我运行它时,我得到一个错误代码10049,它没有连接到服务器。这是代码..

Defenitions.h:

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

using namespace std;

//Prototypes:
WORD version = MAKEWORD(2, 2);
WSADATA info;
SOCKET hSocket;
USHORT port;
sockaddr_in hSockAddr;
char website[50];
void initWSA();
void createSocket();
hostent* websiteInfo;
void getPort();
void connectSocket();
void cleanUp();

//Functions:
void initWSA(){
    if(WSAStartup(version, &info) == 0){
        cout << "WinSock initialization successful!" << endl;
    }else{
        cout << "WinSock initialization failed!" << endl;
    }
}
void createSocket(){
    hSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if(hSocket != INVALID_SOCKET){
        cout << "Socket Creation Successful!" << endl;
    }else{
        cout << "Socket Creation Failed!" << endl;
    }
}
void getPort(){
    cout << "Enter the port number to connect to:" << endl;
}
void connectSocket(){
    if(connect(hSocket, (SOCKADDR*)&hSockAddr, sizeof(hSockAddr)) == 0){
        cout << "Connection to server successful!" << endl;
    }else{
        cout << "Connection to server failed! error code: " << WSAGetLastError() << endl;
    }
}

void cleanUp(){
    if(closesocket(hSocket) == 0){
        cout << "Socket Closure Successful!" << endl;
    }else{
        cout << "Socket Closure Failed!" << endl;
    }
    if(WSACleanup() == 0){
        cout << "WinSock cleanup successful!\a" << endl;
    }else{
        cout << "WinSock cleanup failed!\a" << endl;
    }
}

main.cpp中:

#include "Definitions.h"

int main(int argc, char *argv[]){
    initWSA();
    createSocket();
    cout << "IP Address of: " << "www.google.com" << " is: "<< gethostbyname("www.google.com") << endl;
    getPort();
    cin >> port;
    hSockAddr.sin_family = AF_INET;
    hSockAddr.sin_port = htons(port);
    hSockAddr.sin_addr.S_un.S_addr = inet_addr("www.google.com");
    connectSocket();
    cleanUp();
    return 0;
}

这总是我得到的:

http://i.imgur.com/EsvJr5A.png

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

问题在于如何将主机地址转换为ip,

inet_addr用于IP地址:

  

inet_addr函数 将包含IPv4点分十进制地址 的字符串转换为IN_ADDR结构的正确地址。

而不是:

hSockAddr.sin_addr.S_un.S_addr = inet_addr("www.google.com");

使用:

struct hostent *he = gethostbyname("www.google.com");
memcpy(&hSockAddr.sin_addr, he->h_addr_list[0], he->h_length);

// Or:
//hSockAddr.sin_addr.s_addr = ((in_addr *)(he->h_addr))->s_addr;

见这里:converting host to ip by sockaddr_in gethostname etc

[编辑]

正如Remy Lebeau在评论中写的那样,gethostbyname被删除了,应该使用getaddrinfo,下面是使用getaddrinfo的示例代码:

  // Resolve host name
  struct addrinfo hints, *servinfo, *p;
  memset(&hints, 0, sizeof hints);
  hints.ai_family = AF_UNSPEC;
  hints.ai_socktype = SOCK_STREAM;
  int rv;
  std::string str_port = std::to_string(port);
  if ((rv = getaddrinfo("www.google.com", str_port.c_str(), &hints, &servinfo)) != 0) {
    std::cerr << "getaddrinfo: " << rv << ": " << gai_strerrorA(rv) << std::endl;
    return 1;
  }

  // Loop over all returnd addresses, first one that works is the one we want to use
  for (p = servinfo; p != NULL; p = p->ai_next) {
    createSocket();
    if (connect(hSocket, p->ai_addr, p->ai_addrlen) == 0) {
      cout << "Connection to server successful!" << endl;
      break;
    }
    else {
      cout << "Connection to server failed! error code: " << WSAGetLastError() << endl;
      closesocket(hSocket);
    }
  }
  freeaddrinfo(servinfo);

答案 1 :(得分:0)

在这种情况下,请参阅Windows Sockets Error Codes

  

<强> WSAEADDRNOTAVAIL
  10049

     

无法分配请求的地址。

     

请求的地址在其上下文中无效。这通常是由于尝试<div class="col-md-6"> <div class="panel panel-default" ng-controller="FileInfo"> <div class="panel-heading"> <h3 class="panel-title">Files</h3> </div> <form class="form-inline padding-left"> <select class="form-control padding-left" name="selectedFile" ng-model="fileSelection" ng-change="FileInfo()" ng-options="opt.filename as opt.basename for opt in files"> </select> {{ fileInfo }} </form> </div> </div> <div class="col-md-6"> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">File Info</h3> <br> {{ fileInfo }} </div> 到对本地计算机无效的地址。当远程地址或端口对远程计算机无效时,bindconnectsendtoWSAConnectWSAJoinLeaf也会产生此问题(对于例如,地址或端口0)。

你看到你的IP地址输出了吗?我认为这不是你想要的。

我认为您应该看到此示例以获取IP地址:

Winsock程序员的常见问题解答
示例:Get the Local IP Address(es)