Solved

Creating SOckets

Posted on 1999-01-27
4
273 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
4 Comments
 

Expert Comment

by:b9
ID: 1419349
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
ID: 1419350
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
ID: 1419351
OK - b9, I'll be waiting for that codE!!!  Thanks

Redd
0
 

Accepted Solution

by:
b9 earned 50 total points
ID: 1419352
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

Salesforce Made Easy to Use

On-screen guidance at the moment of need enables you & your employees to focus on the core, you can now boost your adoption rates swiftly and simply with one easy tool.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

After several hours of googling I could not gather any information on this topic. There are several ways of controlling the USB port connected to any storage device. The best example of that is by changing the registry value of "HKEY_LOCAL_MACHINE\S…
A theme is a collection of property settings that allow you to define the look of pages and controls, and then apply the look consistently across pages in an application. Themes can be made up of a set of elements: skins, style sheets, images, and 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…
There's a multitude of different network monitoring solutions out there, and you're probably wondering what makes NetCrunch so special. It's completely agentless, but does let you create an agent, if you desire. It offers powerful scalability …

623 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