2
votes

I have been trying to do this in ms visual studio 2008 using the winsock2 package but whenever i try to resolve the input ip address, which is valid, I get an "Invalid ip..." error. My only guess is that there is some permissions error, but I really have no clue whats wrong. Please help!

if(WSAStartup(MAKEWORD(2,2), &wsaData) != 0){
    error("WSAStartup() failed\n\r");
}

// validate port
if( port <= 0 || port > 65535){
    sprintf(msg, "Invalid port - %d. Ports must be between 0 and 65536\n\r",
                    port);
    error(msg);
}

// validate ip
    inet_addr = inet_addr(ip);
if( inet_addr == INADDR_NONE){
    sprintf(msg, "Not an ip - %s\n\r", ip);
    error(msg);
} else {
        info = gethostbyaddr((char*)&inet_addr, 4, PF_INET);
    if(info == NULL){
        sprintf(msg, "Invalid ip - %s\n\r", ip);
        error(msg);
    }
}
4

4 Answers

4
votes

You need to link with ws2_32.lib:

#pragma comment(lib, "ws2_32.lib")

Or put it in your project configuration as an additional linker input.

2
votes

Check if you are linking to ws2_32.lib. I believe that's what you need.

1
votes

Unless there's a compelling reason to stay at a Winsock 2.0 compatibility level (running on a very old version of Windows; using other code that relies on older Winsock behavior, etc.), you might also want to consider changing:

if(WSAStartup(MAKEWORD(2,0), &wsaData) != 0){

to

if(WSAStartup(MAKEWORD(2,2), &wsaData) != 0){

2.2 is the latest version of the Winsock API.

1
votes

The port number sin_port needs to be in network byte order, too, otherwise you'll be binding your socket to a totally different port from what you think. Use htons() and see other examples.

(This only applies on little-endian systems but is a good idea anyway. Most Windows systems are little-endian.)