C89: getaddrinfo () on Windows?

I am new to C89 and trying to do socket programming:

void get(char *url) {
    struct addrinfo *result;
    char *hostname;
    int error;

    hostname = getHostname(url);

    error = getaddrinfo(hostname, NULL, NULL, &result);

}

I am developing Windows. Visual Studio complains that there is no such file if I use the following include statements:

#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>

What should I do? Does this mean that I will not have portability for Linux?

+3
source share
1 answer

On Windows, instead of the inclusions you mentioned should be enough:

#include <winsock2.h>
#include <windows.h>

You will also have to link to ws2_32.lib. It is disgusting to do it this way, but for VC ++ you can do it through:#pragma comment(lib, "ws2_32.lib")

Some other differences between Winsock and POSIX include:

  • WSAStartup() .

  • close() closesocket().

  • int typedef SOCKET, . - -1 , Microsoft INVALID_SOCKET, .

  • , , ioctlsocket() fcntl().

  • send() recv() write() read().

, Linux, Winsock... , . , , #ifdef s..

:

#ifdef _WINDOWS

/* Headers for Windows */
#include <winsock2.h>
#include <windows.h>

#else

/* Headers for POSIX */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

/* Mimic some of the Windows functions and types with the
 * POSIX ones.  This is just an illustrative example; maybe
 * it'd be more elegant to do it some other way, like with
 * a proper abstraction for the non-portable parts. */

typedef int SOCKET;

#define INVALID_SOCKET  ((SOCKET)-1)

/* OK, "inline" is a C99 feature, not C89, but you get the idea... */
static inline int closesocket(int fd) { return close(fd); }
#endif

, - , , , , .

+6

Source: https://habr.com/ru/post/1733993/


All Articles