Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 586191
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T15:04:53+00:00 2026-05-13T15:04:53+00:00

Hey im writing an echo client, and for some reason the connectsock function is

  • 0

Hey im writing an echo client, and for some reason the connectsock function is returning an error, and returning an INVALID_SOCKET. I can’t figure out why is this. Can someone tell me why

/*********************************
*   echo1.cpp                    *
*                                *
*   Echo client - version 1      *
**********************************/
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
#include <string>
#include <iostream>
using namespace std;

const int  MAXBUF  = 128;
const int  MAXNAME = 80;

SOCKET connectsock (char*, char*, char*);

int main (int argc, char **argv) 
{
    char msg[MAXBUF] = "";
    char buf[MAXBUF] = "";
    char host[MAXNAME] = "";
    char service[MAXNAME] = "";
    int  len;
    SOCKET s;

    /* Must always initialize the Windows Sockets TCP/IP library */
    WORD wVersion = 0x0202;
    WSADATA wsaData;
    int iResult = WSAStartup( wVersion, &wsaData);
    if (iResult != 0) 
    {
        cout << "Unable to initialize Windows Socket library." << endl;
        return 0;
    }


    string hostaddress = argv[1];

    if(argv[2] == NULL)
    {
        strcpy_s(service, MAXNAME, "7");
    }
    else
    {
        strcpy_s(service, MAXNAME, argv[2]);
    }

    strcpy_s( host, MAXNAME, hostaddress.c_str() );



    s = connectsock(host, service, "tcp");
    if (s != INVALID_SOCKET) 
    {

        cout <<"Message?";
        cin.getline(msg, MAXBUF);


        // Now, let's try to send the message to the remote machine


        len = send(s, msg, (int) strlen(msg), 0);
        if (len > 0) 
        {
            cout << "Number of bytes sent: " << len << endl;
            cout << endl;
        } 
        else 
        {
            cout << "Unable to send message to remote machine." << endl;
            return 0;
        }

        // Message was sent.  Is there a reply from the remote machine?
        len = recv(s, buf, sizeof(buf), 0);
        if (len > 0) 
        {
            cout << "Received message: ";
            for (int i=0; i<len; i++) cout << buf[i];
            cout << endl;
            cout << "Number of bytes received: " << len << endl << endl;
        }
        cout << endl << endl;

        /* Close the socket (and thus the connection) */
        shutdown(s,1);
        closesocket(s);
    }
    WSACleanup();
}


/*------------------------------------------------------------------
* connectsock - allocate & connect a remote socket using TCP or UDP
*------------------------------------------------------------------
*/
SOCKET connectsock (char *host, char *service, char *protocol)
{   
    struct  hostent *phe;   
    struct  servent *pse;
    short   port;   
    int     ihost;  


    port = htons( (u_short) atoi(service)); // 1st try to convert string to integer
    if (port == 0)
    {                       // if that doesn't work, call service function
        pse = getservbyname(service,NULL);
        if (pse) 
        {
            port = pse->s_port;
        }
        else
        {
            cout << "Invalid service request." << endl;
            return INVALID_SOCKET;
        }
    }
/*
    cout << "Service: " << service << endl;
    cout << "Port:    " << htons(port) << endl;
*/


    ihost = inet_addr(host);    
    if (ihost == INADDR_NONE) 
    {   
        phe = gethostbyname(host);
        if (phe)
        {
            memmove(&ihost, phe->h_addr, phe->h_length);
        }
        else
        {
            cout << "Invalid Host." << endl;
            return INVALID_SOCKET;
        }
    }
/*
    cout << "Network address for hostname:         " << host << endl;
    cout << "32-bit address in Network Byte Order: " << ihost << endl;
    cout << "32-bit address in Host Byte Order:    " << ntohl(ihost) << endl;

    struct in_addr in;
    in.S_un.S_addr = ihost;
    cout << "Address as dotted decimal:            " << inet_ntoa(in) << endl;

*/

    struct sockaddr_in remote;  
    SOCKET s;                   

    if (_stricmp(protocol, "tcp") == 0) 
    {   
        s = socket(AF_INET, SOCK_STREAM, 0);

        if (s < 0 || s == INVALID_SOCKET)
        {
            cout << "Cannot create socket" << endl;
            return INVALID_SOCKET;
        }


        memset(&remote, 0, sizeof(remote));
        remote.sin_family = AF_INET;
        remote.sin_port = htons( (u_short) atoi(service));
        remote.sin_addr.s_addr = inet_addr(host);


        int status = connect(s, (LPSOCKADDR) &remote, sizeof(SOCKADDR));

        if (status == SOCKET_ERROR) 
        {
            cout << "Remote host/service not found - or connection refused" << endl;
            return INVALID_SOCKET;
        }
    }

    else if (_stricmp(protocol,"udp") == 0) 
    {   
        s = socket(AF_INET, SOCK_DGRAM,  0);
        if (s < 0 || s == INVALID_SOCKET) 
        {
            cout << "Cannot create socket" << endl;
            return INVALID_SOCKET;
        }
    }
    else 
    {                                   // Unknown or unsupported protocol request
        cout << "Invalid Protocol" << endl;
        return INVALID_SOCKET;
    }

    return s;
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T15:04:54+00:00Added an answer on May 13, 2026 at 3:04 pm

    I think that you should use

          remote.sin_port = port;
    

    instead of what you use:

          remote.sin_port = htons( (u_short) atoi(service));
    

    because at some point before in the function you already try to convert the service into a port number. If the service is specified by name, as it seems in your example, this code will always give a remote.sin_port of 0.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 375k
  • Answers 375k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer If you want to insert a record if a value… May 14, 2026 at 8:12 pm
  • Editorial Team
    Editorial Team added an answer From the API: The after_find and after_initialize exceptions Because after_find… May 14, 2026 at 8:12 pm
  • Editorial Team
    Editorial Team added an answer You want to simply call interrupt() - this will interrupt… May 14, 2026 at 8:12 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.