socket(AF_INET, SOCK_STREAM…

在尝试使用socket(AF_INET, SOCK_STREAM, IPPROTO_IP)创建套接字时遇到错误,总是返回-1。解决方案是需要在调用socket函数前先调用WSAStartup进行初始化。这是因为在Windows Socket API中,WSAStartup必须是应用程序首次调用的函数,它用于指定所需的Windows Sockets版本并获取实现细节。" 127902354,14915408,Java毕业设计:二手图书回收销售系统Mybatis实现,"['Java', 'Mybatis', '数据库设计', 'Web开发', '毕业设计']
Issue: socket(AF_INET, SOCK_STREAM, IPPROTO_IP);   总是返回-1
Code: (省略了头文件的引用)
int _tmain(int argc, _TCHAR* argv[])
{
    int socketId;

    socketId = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
    cout<<"socketId="<<socketId<<endl;
    
    return 0;
}

Solution:添加红色代码。(注意:简单起见,这里没有对函数返回值做应有的验证。)

#include

int _tmain(int argc, _TCHAR* argv[])
{
    int socketId;
   
    WSADATA wsData;   
    WSAStartup(MAKEWORD(2,2),&wsData);  
    
    socketId = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
    cout<<"socketId="<<socketId<<endl;

    return 0;
}

调Windows Socket相关函数时,要先调 WSAStartup  ,该函数会做些准备工作。

" The WSAStartup function must be the first Windows Sockets function called by an application or DLL. It allows an application or DLL to specify the version of Windows Sockets required and retrieve details of the specific Windows Sockets implementation. "(摘自: http://msdn.microsoft.com/en-us/library/windows/desktop/ms742213(v=vs.85).aspx



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值