使用mingw在套接字上的fprintf

时间:2014-06-19 17:09:22

标签: c sockets mingw

有一篇有趣的帖子Use fprintf on a socket in Windows建议用一个封装器替换fprintf,该封装器将一个格式缓冲区发送到套接字。

但是,似乎可以使用_open_osfhandle将套接字转换为文件描述符。

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <windows.h>

int main(int argc, char* argv[])
{
    if (argc < 3) 
    {
        fprintf(stderr,"usage %s <hostname> <port>\n", argv[0]);
        exit(0);
    }

    WSADATA wsaData;
    WSAStartup(MAKEWORD(2, 2), &wsaData);

    int port = atoi(argv[2]);
    struct hostent *server = gethostbyname(argv[1]);
    if (server == NULL) 
    {
        fprintf(stderr,"ERROR, no such host\n");
        exit(0);
    }

    struct sockaddr_in serv_addr;
    memset(&serv_addr, 0, sizeof(struct sockaddr_in));
    memcpy((char *)&serv_addr.sin_addr.s_addr, (char *)server->h_addr,  server->h_length);
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(port);

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

    int result = connect(sock, (struct sockaddr*)&serv_addr, sizeof(struct sockaddr_in));
    if(result == -1)
    {
        perror("connect");
        exit(0);
    }
    int OSFileHandle = _open_osfhandle(sock, _O_APPEND);
    FILE * fd = fdopen(OSFileHandle, "w+");
    if (fd == NULL)
    {
        perror("fdopen");
        exit(0);
    }   
    fprintf(fd, "Hello World\r\n");
    fclose(fd);

    closesocket(sock);
    WSACleanup();
}

使用此代码连接到服务器(例如nc -l -p)不起作用。没有收到任何东西,netcat只是退出。

2 个答案:

答案 0 :(得分:0)

MSDN documentationThe socket that is created will have the overlapped attribute as a default

使用WSASocket创建没有WSA_FLAG_OVERLAPPED标志的套接字解​​决问题:

int sock = WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0, 0);

答案 1 :(得分:-1)

我猜测问题是sock是套接字句柄,而不是文件句柄。根据MSDN文档,_open_osfhandle仅适用于文件句柄而不适用于任何其他类型的句柄。