Solved

Creating SOckets

Posted on 1999-01-27
4
238 Views
Last Modified: 2013-12-04
I'm looking for an example and explination on an effiecient way to create sockets under WIN NT.  And how to create and connectect to a Named Pipe to this socket!!!  Any sample code with comments would be greatly appreciated!!!

Thanks
0
Comment
Question by:ReddDogg
  • 2
4 Comments
 

Expert Comment

by:b9
Comment Utility
Connect a pipe to it?  You can't.  One is a Windows thing, the other is a tcp/ip protocol.  As far as socket code.. I'll post some here later.
0
 
LVL 1

Expert Comment

by:arbitrary
Comment Utility
you can pipe your input output by using Overlapped I/O.
manipulation and WSAEvents winsock2 gives you the option to use
Overlapped I/O.
as for code examples goto : http://www.sockets.com/samples.htm
and choose WAL .
you should get aquinted with WSARecv , and the WSASend and all the structures involved (s.a WSAOVERLAPPED)

0
 

Author Comment

by:ReddDogg
Comment Utility
OK - b9, I'll be waiting for that codE!!!  Thanks

Redd
0
 

Accepted Solution

by:
b9 earned 50 total points
Comment Utility
ok - I wrote this winsock class a long time ago - don't think I ever finished it completely.  But, should be enough to get you well started with winsock.  have fun.



///////////////////////////////////////////////////////////
//
// iSock.cpp : ine's winsock class
//             spring 1998
//
///////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////
// headers
//

#include "iSock.h"
#include <winsock.h>
#include <windows.h>

///////////////////////////////////////////////////////////
// initialize global static members
//

int     iSock::NumLocalIP    = 0;
char ** iSock::LocalIP       = NULL;
int     iSock::WinsockStatus = ISK_WINSOCK_NOTYETINIT;

///////////////////////////////////////////////////////////
//
// CONSTRUCTOR
//
///////////////////////////////////////////////////////////

iSock::iSock()
    {
    SocketStatus = ISK_SOCKET_FAIL;

    if (!iSockCheckWinsock())
        {
        if (!iSockStartup())
            return;
        }

    s = socket(AF_INET, SOCK_STREAM, 0);
   
    if (s == INVALID_SOCKET)
        {
        return;
        }

    SocketStatus = ISK_SOCKET_OK;
    }

///////////////////////////////////////////////////////////
//
// DESTRUCTOR
//
///////////////////////////////////////////////////////////

iSock::~iSock()
    {
    closesocket(s);
    SocketStatus = ISK_SOCKET_FAIL;
    }

///////////////////////////////////////////////////////////
//
// CONNECT(char*cIP, unsigned int iPort)
//
///////////////////////////////////////////////////////////

bool iSock::connect(char *cIP, unsigned int iPort)
    {
    SOCKADDR_IN dest_addr;  
    char cResolvedIP[16];

    // winsock and socket must be stable
    //
    if (!iSockCheckWinsock() || !iSockCheckSocket())
        {
        return false;
        }    

    // bogus ip?
    //
    if (!cIP)
        {
        return false;
        }

    // bogus port?
    //
    if (iPort < 1 || iPort > 65535)
        {
        return false;
        }
       
    dest_addr.sin_family = AF_INET;
    dest_addr.sin_port = htons(iPort);

    resolveIP(cIP, cResolvedIP);

    dest_addr.sin_addr.s_addr = inet_addr(cResolvedIP);
    memset(&(dest_addr.sin_zero), 0, 8);

    // try connect
    //
    if (-1 == ::connect(s, (PSOCKADDR)&dest_addr, sizeof(SOCKADDR_IN)))
        {
        return false;
        }

    return true;
    }

///////////////////////////////////////////////////////////
//
// LISTEN(const unsigned int iPort)
//
///////////////////////////////////////////////////////////

bool iSock::listen(const unsigned int iPort)
    {
    SOCKADDR_IN sa;

    if (!iSockCheckWinsock() || !iSockCheckSocket())
        {
        return false;
        }
   
    sa.sin_family = AF_INET;      // default mode
    sa.sin_port = htons(iPort);   // port number to listen on
    sa.sin_addr.s_addr = inet_addr(iSock::LocalIP[0]);
    memset(&(sa.sin_zero), 0, 8);

    if (0 != bind(s, (LPSOCKADDR)&sa, sizeof(SOCKADDR)))
        {
        return false;
        }
   
    if (0 != ::listen(s, 20))
        {
        return false;
        }

    s = accept(s, NULL, NULL);
    if (s == INVALID_SOCKET)
        {
        closesocket(s);
        return false;
        }

    return true;
    }

///////////////////////////////////////////////////////////
//
// CLOSE()
//
///////////////////////////////////////////////////////////

bool iSock::close()
    {
    if (0 == closesocket(s))
        return true;
    else
        return false;
    }

///////////////////////////////////////////////////////////
//
// SEND(char *cData)
//
///////////////////////////////////////////////////////////

int iSock::send(char *cData)
    {
    unsigned int iBytesTotal, iBytesSent;
    char *cPtr;

    if (!iSockCheckWinsock())
        return false;

    iBytesTotal = 0;
    cPtr = cData;

    do
        {
        iBytesSent = ::send(s, cPtr, strlen(cPtr), 0);
        if (iBytesSent == SOCKET_ERROR)
            return iBytesTotal;

        iBytesTotal += iBytesSent;
        cPtr += iBytesSent;
        }
    while (iBytesSent < (unsigned int)lstrlen(cData));

    return iBytesTotal;
    }

///////////////////////////////////////////////////////////
//
// SEND(char *cData, unsigned int iBytes)
//
///////////////////////////////////////////////////////////

int iSock::send(char *cData, unsigned int iBytes)
    {
    unsigned int iBytesTotal, iBytesSent;
    char *cPtr;

    if (!iSockCheckWinsock())
        return false;

    iBytesTotal = 0;
    cPtr = cData;

    do
        {
        iBytesSent = ::send(s, cPtr, strlen(cPtr), 0);
        if (iBytesSent == SOCKET_ERROR)
            return iBytesTotal;

        iBytesTotal += iBytesSent;
        cPtr += iBytesSent;
        }
    while (iBytesSent <= iBytes);

    return iBytesTotal;
    }

///////////////////////////////////////////////////////////
//
// RECV(char *cData, unsigned int iBytes)
//
///////////////////////////////////////////////////////////

int iSock::recv(char *cData, unsigned int iBytes)
    {
    int ret;

    if (!iSockCheckWinsock())
        return false;

    ret = ::recv(s, cData, iBytes, 0);

    if (ret == 0)
        {
        return 0;
        }

    if (ret == SOCKET_ERROR)
        {
        return 0;
        }

    return ret;
    }

///////////////////////////////////////////////////////////
//
// ISOCKSTARTUP()
//
///////////////////////////////////////////////////////////

bool iSockStartup()
    {
    char cBuf[100];
    WSADATA dat;    
    HOSTENT *h;
    int i;

    // if already initialized, exit
    //
    if (iSock::WinsockStatus == ISK_WINSOCK_OK)
        return true;
   
    // load dll
    //
    if (0 != WSAStartup(MAKEWORD(1, 1), &dat))
        {
        iSock::WinsockStatus = ISK_WINSOCK_FAIL;
        return false;
        }
   
    // get local hostname
    //
    if (0 != gethostname(cBuf, 100))
        {
        iSock::WinsockStatus = ISK_WINSOCK_FAIL;
        return false;
        }
   
    // resolve hostname
    //
    h = gethostbyname(cBuf);
    if (h == NULL)
        {
        iSock::WinsockStatus = ISK_WINSOCK_FAIL;
        return false;
        }
   
    // get number of local ip addresses
    //
    i = 0;
    while (h->h_addr_list[i] != NULL)
        ++i;

    iSock::LocalIP = new char*[i];
    iSock::NumLocalIP = i;

    // save local ips
    //
    i = 0;
    while (i < iSock::NumLocalIP)
        {
        iSock::LocalIP[i] = new char[16];

        wsprintf(iSock::LocalIP[i],
                 "%u.%u.%u.%u",
                 (unsigned char)h->h_addr_list[i][0],
                 (unsigned char)h->h_addr_list[i][1],
                 (unsigned char)h->h_addr_list[i][2],
                 (unsigned char)h->h_addr_list[i][3]
                 );
        i++;
        }

    // success initialization
    //
    iSock::WinsockStatus = ISK_WINSOCK_OK;

    return true;
    }

///////////////////////////////////////////////////////////
//
// ISOCKCLEANUP()
//
///////////////////////////////////////////////////////////

bool iSockCleanup()
    {
    int i;

    // if winsock loaded ok, unload it
    //
    if (iSockCheckWinsock())
        WSACleanup();

    // if no ip array to destroy, return
    //
    if (!iSock::LocalIP)
        return false;

    // delete ip strings
    //
    for (i = 0; i < iSock::NumLocalIP; i++)
        delete [] iSock::LocalIP[i];

    delete [] iSock::LocalIP;

    // reset winsock status
    //
    iSock::NumLocalIP = 0;
    iSock::WinsockStatus = ISK_WINSOCK_NOTYETINIT;
    return true;    
    }

///////////////////////////////////////////////////////////
//
// ISOCKGETNUMIP()
//
///////////////////////////////////////////////////////////

int iSockGetNumIP()
    {
    return iSock::NumLocalIP;
    }

///////////////////////////////////////////////////////////
//
// ISOCKGETIP(int iNum = 0)
//
///////////////////////////////////////////////////////////

char *iSockGetIP(int iNum = 0)
    {
    if (iNum > iSock::NumLocalIP)
        return NULL;

    return iSock::LocalIP[iNum];
    }

///////////////////////////////////////////////////////////
//
// ISOCKCHECKWINSOCK()
//
///////////////////////////////////////////////////////////

bool iSockCheckWinsock()
    {
    return (iSock::WinsockStatus == ISK_WINSOCK_OK) ? true : false;
    }

///////////////////////////////////////////////////////////
//
// ISOCKCHECKSOCKET
//
///////////////////////////////////////////////////////////

bool iSock::iSockCheckSocket()
    {
    return (iSock::SocketStatus == ISK_SOCKET_OK) ? true : false;
    }

///////////////////////////////////////////////////////////
//
// RESOLVEIP(char *cIn, char *cOut)
//
///////////////////////////////////////////////////////////

void resolveIP(char *cIn, char *cOut)
    {
    int i;

    // easy check, see if the string is longer than possible
    if (strlen(cIn) > 15)
        {
        hostnameToNumeric(cIn);
        strcpy(cOut, cIn);
        return;
        }

    // bleh, check for a non numeric + "." string
    for (i = 0; i < lstrlen(cIn); i++)
        {
        if (cIn[i] == '.')
            continue;

        if (cIn[i] < '0' || cIn[i] > '9')
            {
            strcpy(cOut, cIn);
            hostnameToNumeric(cOut);            
            return;
            }
        }

    strcpy(cOut, cIn);  
    }

///////////////////////////////////////////////////////////
//
// HOSTNAMETONUMERIC(char *cBuf)
//
///////////////////////////////////////////////////////////

void hostnameToNumeric(char *cBuf)
    {
    HOSTENT *h;

    h = gethostbyname(cBuf);
   
    if (!h)
        {
        strcpy(cBuf, "0.0.0.0");
        return;
        }

    strcpy(cBuf, inet_ntoa(*((struct in_addr *)h->h_addr)));
    }

///////////////////////////////////////////////////////////





///////////////////////////////////////////////////////////
//
// iSock.h : ine's winsock object
//
///////////////////////////////////////////////////////////

#ifndef _ISOCK_H
#define _ISOCK_H

///////////////////////////////////////////////////////////

#include <windows.h>
#include <winsock.h>

///////////////////////////////////////////////////////////

class iSock
    {
    protected:
        static int WinsockStatus;     // global winsock initialization status
        int SocketStatus;             // local socket status

        static char **LocalIP;        // global local ip list
        static int NumLocalIP;        // global number of local ips

        SOCKET s;                     // local socket
        char RemoteIP[16];            // who we are connected to
        unsigned int LocalPort;       // our port
        unsigned int RemotePort;      // their port      

    public:
        iSock();                                          // constructor      
        ~iSock();                                         // destructor

        bool connect(char *cIP, unsigned int iPort);      // make connection
        bool listen(unsigned int iPort);                  // wait for connection

        bool close();                                     // terminate current connection

        int send(char *cData);                            // send asciiz data
        int send(char *cData, unsigned int iBytes);       // send binary data

        int recv(char *cData, unsigned int iBytes);       // receive data

        friend bool iSockStartup();                       // initialize
        friend bool iSockCleanup();                       // shutdown and cleanup

        friend int iSockGetNumIP();                       // get # of local ips
        friend char *iSockGetIP(int iNum);                // get local ip

        bool iSockCheckSocket();                          // check socket status, member version
        friend bool iSockCheckSocket(const iSock &s);     // check socket status, friend version
        friend bool iSockCheckWinsock();                  // check winsock status

        friend void resolveIP(char *cIn, char *cOut);
        friend void hostnameToNumeric(char *cBuf);
    };

///////////////////////////////////////////////////////////

const int ISK_WINSOCK_NOTYETINIT = 1<<1;  // winsock has not yet been initialized
const int ISK_WINSOCK_OK         = 1<<2;  // winsock initialization ok
const int ISK_WINSOCK_FAIL       = 1<<3;  // winsock initialization failed

const int ISK_SOCKET_OK          = 1<<1;  // socket was created ok
const int ISK_SOCKET_FAIL        = 1<<2;  // socket creation failed

///////////////////////////////////////////////////////////

#endif

///////////////////////////////////////////////////////////

0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

If you have ever found yourself doing a repetitive action with the mouse and keyboard, and if you have even a little programming experience, there is a good chance that you can use a text editor to whip together a sort of macro to automate the proce…
For a while now I'v been searching for a circular progress control, much like the one you get when first starting your Silverlight application. I found a couple that were written in WPF and there were a few written in Silverlight, but all appeared o…
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now