gpt4 book ai didi

c++ - 连接()不起作用

转载 作者:行者123 更新时间:2023-11-30 04:12:52 26 4
gpt4 key购买 nike

我正在学习 C++ 网络教程,winsock .

但是到目前为止我编写的代码并不完全有效,我做错了什么?

my "main.cpp"

#include "main.h"

using namespace std;

int winsock()
{

//variables

const int winsock_version = 2;

WSAData wsa;

SOCKET sok;

SOCKADDR_IN server;

//start up
WSAStartup(MAKEWORD(winsock_version,0), &wsa);

sok = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

//check startup
if(WSAStartup(MAKEWORD(winsock_version,0), &wsa) != 0)
{
cout << "An error occured during startup! \n";
WSACleanup();
return -1;
}

//check version
if (LOBYTE(wsa.wVersion) < winsock_version)
{
cout << "Your version of winsock is too low!\n";
cout << "\nWinsock 2.0 or above is required.";
return -1;
}

//check if socket is valid
if (sok == INVALID_SOCKET)
{
cout << "Invalid socket!";
return -1;
}

//set connection type
server.sin_family = AF_INET;
//set port
server.sin_port = htons(80);
//set adress to connect to
server.sin_addr.S_un.S_addr = INADDR_ANY;


//connect
connect(sok,(sockaddr*)(&server), sizeof(server));
//bind socket
bind(sok, (sockaddr*)(&server), sizeof(server));

if(connect(sok,(sockaddr*)(&server), sizeof(server)) !=0)
{
cout << "error during connecting! \n";
WSACleanup();
closesocket(sok);
return -1;
}

cout << "Connection was made!";
//clean up
WSACleanup();
closesocket(sok);
if (WSACleanup() !=0 || closesocket(sok) !=0)
{
cout << "Clean up failed! \n";
return -1;
}
return 0;
}

int main()
{
winsock();
}

和我的“main.h”

#ifndef MAIN_H_INCLUDED
#define MAIN_H_INCLUDED

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif


// std libs
#include <iostream>
#include <fstream>
#include <string>


//windows
#include <windows.h>
//networking libs
#include <winsock2.h>
// layout engine

#endif // MAIN_H_INCLUDED

当我运行该程序时,它显示“连接期间出错!”,这意味着我遇到了某种错误。

我使用 code::blocks 作为我的 IDE。

我做错了什么?

最佳答案

您无法连接到 INADDR_ANY。指定 IP 地址。

为什么要调用 WSAStartup() 两次?

并且您不必使用 bind() 来执行 connect() 除非必须指定您的本地端口非常重要(例如在 SMB 协议(protocol)中).

有很多 exemples on how to use WinSock to connect , 阅读它们。

关于c++ - 连接()不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19666022/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com