Software & Finance

Visual C++ - Introduction to Socket Programming

Sockets are very important for establishing communication between the server and client. A socket can be a raw socket or TCP streaming socket or a datagram socket.

Here is the sample code for client application that connects to the server and sends the data.

Source Code


    if(s == -1)


        AfxMessageBox("Socket Initialiation Error");

        return false;


    SOCKADDR_IN serveraddr;

    struct hostent *hostentry;


    int portno = 80;

    bool bSent = false;


    hostentry = gethostbyname("");

    char *pipaddr = inet_ntoa (*(struct in_addr *)*hostentry->h_addr_list);



     memset(&serveraddr,0, sizeof(serveraddr));

     serveraddr.sin_family = AF_INET;

     serveraddr.sin_port = htons(portno);

     serveraddr.sin_addr.s_addr = inet_addr(pipaddr);


    //serv_addr.sa_data = htons(portno);


    if (connect(s,(SOCKADDR*)&serveraddr,sizeof(SOCKADDR_IN)) < 0)


         AfxMessageBox("ERROR connecting to the server");




    char sbuf[1024] = "Data", rbuf[1024];


    recv(s, rbuf, 1024, 0);

    send(s, sbuf, strlen(sbuf), 0);




The main difference for server side sockets are that will use bind command to bind with the address and use listen command for accepting the incoming connection. Usually binding and listen part is implemented from the main thread and when there is an incoming connection, the client connection established by creating a new thread. The child thread is responsible for serving the clients request.

The datagram sockets use sendto and recvfrom functions for communication. I will create a sample fro datagram sockets in the near future and post it to this site shortly.