Winsock C TCP 套接字
我之前在 Python 中使用过 TCP 套接字。它在 C 中看起来非常相似,但我无法让任何东西工作。 socket(AF_INET, SOCK_STREAM, 0);
返回 -1,这当然表示错误。我怎么会这么快就出错了呢? 如果你能帮助我解决这个问题,那就太好了,但如果你能为我提供一些简单的、简单的源代码,那将会非常有帮助。它甚至不需要做任何事情,也不需要处理错误。我只需要了解如何正确创建服务器套接字、绑定它、侦听它并接受客户端,以及如何创建和连接客户端套接字。我可以自己弄清楚所有的花里胡哨的事情。
谢谢!
I've worked with TCP sockets before in Python. It looks pretty similar in C but I can't get anything to work. socket(AF_INET, SOCK_STREAM, 0);
returns -1, which of course indicates an error. 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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您是否已致电
WSAStartup
< /a> 在进行任何其他winsock 调用之前?Have you called
WSAStartup
before making any other winsock calls?您需要使用
WSAStartup< 初始化 WinSock /code>
函数之后才能使用套接字。 Windows 上的 Python 套接字实现可能会自动调用此函数,因此您无需担心它,但是,当直接使用 WinSock 时,在任何其他 WinSock 调用之前以及当您的程序运行时,调用
WSAStartup
非常重要。完成套接字后,您需要调用WSACleanup
。You need to initialise WinSock with the
WSAStartup
function before you can use sockets. 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 callWSAStartup
before any other WinSock calls, and when your program is done with sockets, you need to callWSACleanup
.客户:
http://msdn.microsoft。 com/en-us/library/windows/desktop/ms737591(v=VS.85).aspx
服务器:
http://msdn.microsoft。 com/en-us/library/windows/desktop/ms737593(v=vs.85).aspx
Client:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms737591(v=VS.85).aspx
Server:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms737593(v=vs.85).aspx
可能只是该进程没有创建套接字的权限(
errno == EACCES
)。也许您的 python 解释器正在获取不同的安全上下文,请检查一下。
不管怎样,安全总比后悔好,所以写上类似这样的内容:
如果 Winsock 实际上设置了 errno,则 IDK,但它应该...
Probably it's just that the process has no permission to create sockets (
errno == EACCES
).Perhaps your python interpreter is getting a different security context, check that.
Anyway, better safe than sorry, so put there something like:
IDK if Winsock actually sets
errno
, but it should...