gpt4 book ai didi

c++ - 使用 CreateFile 打开套接字

转载 作者:行者123 更新时间:2023-11-30 03:12:43 24 4
gpt4 key购买 nike

我们有一些旧的串行代码,可以通过打开然后关闭串行端口来检查串行端口是否可用。现在我们正在向应用程序添加网络支持,我想通过以字符串形式提供 IP 地址来重用该功能。

/**
* So far I have tried:
* A passed in portPath normally looks like:
\\?\acpi#pnp0501#1#1#{GUID}
10.2.0.155:2001
//10.2.0.155:2001/
\\.\10.2.0.155:2001\
\\?\10.2.0.155:2001\
* all without success.
*/
bool PortIsAvailable( const CString& portPath )
{
HANDLE hCom = ::CreateFile( portPath,
GENERIC_READ | GENERIC_WRITE,
0, // comm devices must be opened with exclusive-access
NULL, // no security attributes
OPEN_EXISTING, // comm devices must use OPEN_EXISTING
FILE_FLAG_OVERLAPPED, // not overlapped I/O
NULL ); // hTemplate must be NULL for comm devices
if (INVALID_HANDLE_VALUE != hCom )
{
::CloseHandle( hCom );
return true;
}
return false;
}

我知道我可以先连接再关闭,但我想以最少的更改重用该功能。如果我能重用这个功能就更好了。如果不是,那么我将不得不编写代码来确定它是否是套接字。

我想知道通过 CreateFile 打开套接字的正确方法是什么?

最佳答案

您不能通过 CreateFile 创建套接字。您应该使用 Windows socket API以此目的。要创建 SOCKET 句柄,请使用 WSASocket .请注意,此函数返回的 SOCKET 可用作带有某些 Windows functions, such as ReadFile and WriteFile 的 Windows 句柄。 .

关于c++ - 使用 CreateFile 打开套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/516763/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com