winsock socket as file handle
Asked Answered
U

2

5

i have been scratching my head and been searching for an answer for this for hours now. Basically what I do is open a socket to some other machine and reading the data from it. This socket is than "converted" to a file handle via an fdopen call passing in the int that represent the socket. The resulting file handle is then passed to a bison parser which directly parsed the data received over the socket. All of this works fine on linux. Now I have tried to port this code to windows and I dismally fail. The code looks something like this:

        FILE* fileHandle;
        #if defined WINCE || defined WIN32
        int fd = _open_osfhandle(socket, _O_RDONLY);
        if (fileHandle = fdopen(fd, "r")) {
        #else
        if (fileHandle = fdopen(socket, "r")) {
        #endif
           ... // code to call my parser with fileHandle as argument

The bison/flex parser fails in the windows version since the filehandle seems to point to an empty stream/file. Can anybody point to a comprehensive resource that explains this stuff or hint at an alternative solution?

Thanks and best Regards,

André

Unalienable answered 9/4, 2012 at 17:44 Comment(0)
R
9

In Windows, a socket handle is not a file handle, and you cannot treat it as such in the C API. In Linux, you can. However, in Windows, a socket handle can be passed to the ReadFile/Ex() and WriteFile/Ex() functions, which support numerous handle types, not just files, despite their names.

Renfroe answered 9/4, 2012 at 18:43 Comment(3)
This does not help me directly since the code that I call is basically generated. I cannot call the windows specific functions inside it unless I create some wrapper or override some of the flex/bison generated code which I would like to avoid.Bonina
Then you are out of luck. You need to re-write something. You can't use C file I/O functions on a socket handle in Windows.Renfroe
Yeap that is also my conclusion. Parts of this need to be rewritten.Bonina
A
-1

You need to fake a little bit, but this one works for me - nSocketFd a file descriptor return by socket()

    FILE* fpSocket = NULL;

#ifdef WIN32
    fpSocket = new FILE;
    fpSocket->_file = nSocketFd;
    fpSocket->_cnt = 0;
    fpSocket->_ptr = NULL;
    fpSocket->_base = NULL;
    fpSocket->_flag = 0;
#else
    // build the file pointer from the file descriptor
    fpSocket = fdopen (nSocketFd, "rb+");
#endif
Alluvion answered 7/12, 2015 at 18:0 Comment(1)
The FILE struct is opaque in later editions of the Windows SDK.Hutchison

© 2022 - 2024 — McMap. All rights reserved.