Hi all:
I wrote a simple program to open a socket to localhost port 8201.

Codes:
......

if (WSAStartup(VERSION, &wsadata) != NO_ERROR)
    {
        WSACleanup();
        return EXIT_FAILURE;
    }

open_socket(serverName, port);

SOCKET open_socket (const char *serverName, const int port)
{
    struct hostent *server = NULL;
    SOCKADDR_IN serverAddress;

    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock!= INVALID_SOCKET)
    {
        server = gethostbyname(serverName);
        if (server == NULL)
        {
            sock = INVALID_SOCKET;
        }
        else 
        {
            char *ip = server->h_addr;
            SOCKADDR_IN serverAddress = 
            {
                AF_INET,
                htons(port),
                {ip[0], ip[1], ip[2], ip[3]}
            };
        }
        if (connect(sock, (SOCKADDR*) &serverAddress, sizeof(serverAddress))<0)
        {
            sock = INVALID_SOCKET;
            printf("Connection failed.");
        }
        printf("Connection successed.");
    }
    return sock;
}

It always results in "INVALID_SOCKET". I am very confused. The header file I used is #include <winsock.h>.

Thanks

Dani AI

Generated

A short, practical follow-up that complements ’s diagnosis and helps future readers who hit an INVALID_SOCKET/connect failure when talking to localhost.

correctly spotted the local SOCKADDR_IN being shadowed; referencing an uninitialized sockaddr in the call to connect explains the symptom. Beyond that, a few common causes and safer practices frequently prevent similar problems on Windows sockets:

  • Winsock initialization and headers: WSAStartup(MAKEWORD(2,2)) must happen before any socket calls. Prefer <winsock2.h> (include it before <windows.h>) and link ws2_32.lib to avoid header/link conflicts.
  • Initialization: zero the SOCKADDR_IN structure before use and explicitly set sin_family and sin_port. Leaving fields uninitialized (or shadowing the variable) lets garbage values reach connect.
  • Address copying: copy the resolved address into sin_addr (use memcpy from server->h_addr_list[0] or convert a literal with inet_addr) instead of relying on fragile byte indexing.
  • Error reporting: Winsock functions return socket-specific errors via WSAGetLastError() (use that to map error codes such as connection refused, host unreachable, etc.). Check return values for socket(), gethostbyname()/getaddrinfo(), and connect() and clean up with closesocket() + WSACleanup().

Example pattern for filling the sockaddr (keeps fields explicit and avoids shadowing):

memset(&serverAddress, 0, sizeof(serverAddress));
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(port);
memcpy(&serverAddress.sin_addr, server->h_addr_list[0], server->h_length);

Additional notes: prefer getaddrinfo() over gethostbyname() for thread-safety and IPv6 support; verify the server is actually listening on port 8201 (tools like netstat/telnet or an equivalent listener check) and confirm local firewall/anti-virus is not blocking. After removing the shadowed variable and applying the initialization and error-checking practices above, the connect failure seen by is the expected next thing to re-test.

Recommended Answers

All 3 Replies

Now there are two or three places in your code where the socket may return INVALID_SOCKET, e.g the call of socket, and where the Winsock functions may fail, e,g gethostname(). So why don't you use the GetLastError() function at these places to get the error number when that happens? Then you can search for the description for that error number in MSDN or google, and you will find what is wrong. That will be better than we pointing the error for you.

if (WSAStartup(VERSION, &wsadata) != NO_ERROR)
    {
        WSACleanup();
        return EXIT_FAILURE;
    }

open_socket(serverName, port);

SOCKET open_socket (const char *serverName, const int port)
{
    struct hostent *server = NULL;
    SOCKADDR_IN serverAddress;

    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock!= INVALID_SOCKET)
    {
        server = gethostbyname(serverName);
        if (server == NULL)
        {
            sock = INVALID_SOCKET;
        }
        else 
        {
            char *ip = server->h_addr;
            SOCKADDR_IN serverAddress = 
            {
                AF_INET,
                htons(port),
                {ip[0], ip[1], ip[2], ip[3]}
            };
        }
        if (connect(sock, (SOCKADDR*) &serverAddress, sizeof(serverAddress))<0)
        {
            sock = INVALID_SOCKET;
            printf("Connection failed.");
        }
        printf("Connection successed.");
    }
    return sock;
}

Okay I think it is because you are initializing a newly defined SOCKADDR local variable inside the else branch, but using the uninitialized SOCKADDR variable of the same name. See the lines marked in Red.

Here is a version that would work

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

SOCKET open_socket (const char *serverName, const int port)
{
    struct hostent *server = NULL;

    SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP );
    if (sock!= INVALID_SOCKET)
    {
        server = gethostbyname(serverName);
        if (server == NULL)
        {
            sock = INVALID_SOCKET;
            printf("GethostName Failed\n");
            return INVALID_SOCKET;
        }
        else
        {
            char *ip = server->h_addr;
            SOCKADDR_IN serverAddress =
            {
                AF_INET,
                htons(port),
                {ip[0], ip[1], ip[2], ip[3]}
            };
            printf("Server Address %d %d %d %d \n", ip[0], ip[1], ip[2], ip[3]);
            if (connect(sock, (SOCKADDR*) &serverAddress, sizeof(serverAddress))<0)
            {
                printf("Connection failed.%d", GetLastError());
                return INVALID_SOCKET;
            }
            printf("Connection successed.");
        }
    }
    else
    {
        printf("Create Socket Failed\n");
        return INVALID_SOCKET;
    }
    return sock;
}


int main()
{
    WSADATA wsadata;
    if (WSAStartup(MAKEWORD(2, 2), &wsadata) != NO_ERROR)
    {
        printf("Startup Failure\n");
        WSACleanup();
        return EXIT_FAILURE;
    }
    open_socket("localhost", 8201);
    WSACleanup();
    return 0;
}

Thank you very much. I do not know what to say. Good reply in such a short notice. I am very much obiliged.
Thank you again.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.