Question

We've got some old serial code which checks whether a serial port is available simply by opening it and then closing it. Now we are adding network support to the app I want to reuse the function by supplying the ip address as a string.

/**
 * 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;
    }

I know I could use connect followed by shutdown but I want to reuse the function with minimal changes. If I can reuse the function so much the better. If not then I will have to write code that determines whether it is a socket or not.

I was wondering what the correct way of opening a socket via CreateFile is?

Was it helpful?

Solution

You can not create a socket via CreateFile. You should use the windows socket API for this purpose. For creating the SOCKET handle, you use WSASocket. Note that the SOCKET returned by this function can be used as a Windows Handle with some Windows functions, such as ReadFile and WriteFile.

OTHER TIPS

I don't believe you can manipulate sockets with CreateFile(). Sockets are an abstraction imported from BSD (iirc) and implemented in a name-compatible way (originally via winsock.h, and currently winsock2.h). I don't think MS ever added support for sockets to CreateFile().

More rationale: Most (everything?) CreateFile() manipulates returns a native Windows handle. Because sockets are a non-native abstraction, they don't have a native handle in the OS, so it wouldn't make sense for CreateFile() to handle them.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top