如果您费心使用调试器并自己调试代码,您会发现您的mySocket
变量始终为 0,因为您没有正确初始化它。
这一行:
if (mysocket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)==INVALID_SOCKET){
实际上与此相同:
if (mysocket=(socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)==INVALID_SOCKET)){
如果socket()
成功,==INVALID_SOCKET
则评估为 false,因此将 0 分配给mysocket
。阅读Operator Precedence。运算符的==
优先级高于=
运算符。
要修复它,请将该行改为:
if ((mysocket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))==INVALID_SOCKET){
或者更好的是,摆脱在同一语句中分配和比较变量的习惯:
mysocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if (mysocket==INVALID_SOCKET){
此外,如果您费心注意编译器的输出消息,您会看到您的"CONNECTED!"
消息是永远无法到达的代码,因为它位于失败时的大括号内connect()
,但return
在您打印消息之前有一个。
试试这个代码:
#include <winsock2.h>
#include <iostream.h>
#include <windows.h>
//#define portnumber 80
using namespace std;
//Winsock Library
int main(int argc, char* argv[])
{
WSADATA ws = {0};
int v = WSAStartup(MAKEWORD(2,2), &ws);
if (v != 0)
{
cout << "error initialising winsock: " << v << endl;
getchar();
return 1;
}
cout << "winsock started" << endl;
SOCKET mysocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (mysocket == INVALID_SOCKET)
{
cout << "error creating socket: " << WSAGetLastError() << endl;
getchar();
return 1;
}
cout << "socket created" << endl;
struct sockaddr_in server = {0};
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_addr("84.95.234.174");
//cout << inet_ntoa(server.sin_addr) << endl;
server.sin_port = htons(80);
if (connect(mysocket, (struct sockaddr *)&server, sizeof(server)) == SOCKET_ERROR)
{
cout << "error connecting to server: " << WSAGetLastError() << endl;
getchar();
return 1;
}
cout << "CONNECTED!" << endl;
getchar();
closesocket(mysocket);
return 0;
}