您好我是初学者socket / c程序员,从本教程我有连接函数返回10038错误。请帮忙。我做错了什么?
还有什么是winsock和winsock2之间的区别?
在connect()函数定义中还有int PASCAL
什么是pascal?
#include <iostream>
#include <winsock.h>
using namespace std;
int main(){
WSADATA wsa;
cout<< "Iinitializing winsock....";
SOCKET sa;
struct sockaddr_in server;
if (WSAStartup(MAKEWORD(2,2), &wsa)!=0)
cout << "Failed";
cout << "initialized";
if ((sa = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP) == INVALID_SOCKET))
cout << "Could not create socket " << WSAGetLastError();
cout << "Socket created";
server.sin_addr.s_addr = inet_addr ("213.165.64.44");
server.sin_family = AF_INET;
server.sin_port = htons(7);
//connect
if (connect(sa, (struct sockaddr *)&server, sizeof(server)) < 0){
cerr << "connect error" << WSAGetLastError();
return 1;
}
cout << "connected";
return 0;
}
答案 0 :(得分:3)
您应该查看文档10038的含义:
WSAENOTSOCK
10038 (0x2736)
An operation was attempted on something that is not a socket.
所以sa
不是套接字。打印sa
到cerr
会显示它为零,因此调用socket()
函数的内容很糟糕。仔细查看该行会显示该行中有一个括号错误:
if ((sa = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP) == INVALID_SOCKET))
首先执行==,并且由于socket()
函数的返回值不是无效套接字,因此将零分配给sa。
正确的表达方式是:
if ((sa = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)
对于问题的其他部分:
PASCAL
是__stdcall
˙的宏,Windows API函数通常使用此calling convention。