简体   繁体   English

Winsock C TCP套接字

[英]Winsock C TCP Socket

I've worked with TCP sockets before in Python. 我之前在Python中使用过TCP套接字。 It looks pretty similar in C but I can't get anything to work. 它在C中看起来非常相似但我无法获得任何工作。 socket(AF_INET, SOCK_STREAM, 0); returns -1, which of course indicates an error. 返回-1,这当然表示错误。 How could I go so wrong so fast? 我怎么会这么快走错路? If you could help me with this problem, that would be nice, but it would be incredibly helpful if you could provide me with some simple, bare bones source code. 如果你可以帮我解决这个问题,那就太好了,但如果你能给我一些简单的,简单的骨头源代码,那将会非常有帮助。 It doesn't need to even do anything really, and it doesn't need to handle errors. 它甚至不需要做任何事情,也不需要处理错误。 I just need to see how to properly create a server socket, bind it, listen on it, and accept clients and how to create and connect a client socket. 我只需要看看如何正确创建服务器套接字,绑定它,监听它,接受客户端以及如何创建和连接客户端套接字。 I can figure out all the bells and whistles on my own. 我可以自己弄清楚所有的花里胡哨。

Thanks! 谢谢!

在进行任何其他winsock调用之前,您是否调用了WSAStartup

You need to initialise WinSock with the WSAStartup function before you can use sockets. 在使用套接字之前,需要使用WSAStartup函数初始化WinSock。 Python's implementation of sockets on Windows likely calls this automatically so you don't need to worry about it, however when using WinSock directly it is important to call WSAStartup before any other WinSock calls, and when your program is done with sockets, you need to call WSACleanup . Python在Windows上实现套接字可能会自动调用它,所以你不必担心它,但是当直接使用WinSock时,在任何其他WinSock调用之前调用WSAStartup很重要,当你的程序完成套接字时,你需要调用WSACleanup

WSAData data;

if (WSAStartup(MAKEWORD(2, 2), &data) != 0)
{
    // unable to initialise WinSock, time to quit
}

// WinSock has been successfully initialised, time to make sockets!
int s = socket(...);

// After all WinSock stuff is done, balance out your WSAStartup with a cleanup:
WSACleanup();

Probably it's just that the process has no permission to create sockets ( errno == EACCES ). 可能只是该进程无权创建套接字( errno == EACCES )。

Perhaps your python interpreter is getting a different security context, check that. 也许你的python解释器获得了不同的安全上下文,检查一下。

Anyway, better safe than sorry, so put there something like: 无论如何,比抱歉更安全,所以放在那里:

sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
        perror("myapp");
        exit(1);
}

IDK if Winsock actually sets errno , but it should... IDK,如果Winsock实际设置errno ,但它应该...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM