I’m new to C89, and trying to do some 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 on Windows. Visual Studio complains that there is no such file if I use these include statements:
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
What should I do? Does this mean that I won’t have portability to Linux?
On Windows, instead of the includes you have mentioned, the following should suffice:
You’ll also have to link to
ws2_32.lib. It’s kind of ugly to do it this way, but for VC++ you can do this via:#pragma comment(lib, "ws2_32.lib")Some other differences between Winsock and POSIX include:
You will have to call
WSAStartup()before using any socket functions.close()is now calledclosesocket().Instead of passing sockets as
int, there is a typedefSOCKETequal to the size of a pointer. You can still use comparisons with-1for error, though Microsoft has a macro calledINVALID_SOCKETto hide this.For things like setting non-blocking flags, you’ll use
ioctlsocket()instead offcntl().You’ll have to use
send()andrecv()instead ofwrite()andread().As for whether or not you will lose portability with Linux code if you start coding for Winsock… If you are not careful, then yes. But you can write code that tries to bridge the gaps using
#ifdefs..For example:
Then once you do something like this, you can code against the functions which appear in both OS’s, using these wrappers where appropriate.