Example #1
0
STDMETHODIMP CBUDPSocket::Bind(BSTR strAddr, LONG port)
{
	SOCKADDR_IN sockAddr;
	HRESULT hr = FillAddress(strAddr, port, &sockAddr);
	if(FAILED(hr))return hr;

	if(bind(m_hSocket, (SOCKADDR*)&sockAddr, sizeof(sockAddr)))
		return GetErrorResult();

	GetLocalInfo();

	return S_OK;
}
Example #2
0
STDMETHODIMP CBUDPSocket::SendTo(BSTR strAddr, LONG port, VARIANT varData)
{
	SOCKADDR_IN sockAddr;
	HRESULT hr = FillAddress(strAddr, port, &sockAddr);
	if(FAILED(hr))return hr;

	CBVarPtr varPtr;

	hr = varPtr.Attach(varData);
	if(FAILED(hr))return hr;

	if(sendto(m_hSocket, (const char *)varPtr.m_pData, varPtr.m_nSize, 0, (SOCKADDR*)&sockAddr, sizeof(sockAddr)) == SOCKET_ERROR)
		return GetErrorResult();

	if(!m_nPort)GetLocalInfo();
	return S_OK;
}
Example #3
0
//--------------------------------------------------------------------------
int main(int iArgC, char **ppcArgV){
    struct sockaddr_in sAddress;
    char *pcWWWServer, *pcPage, *pcPos;
    if (iArgC != 2) printerror("Command Line requires one parameter = website");
    // If the provided URL begins with "http://" then set pcWWWServer to point
    // to the next character otherwise set it to point to the entire provided URL
	//
	// strstr() - find a string in another string. return the first position
    if (pcWWWServer = strstr(ppcArgV[1], "http://"))
        pcWWWServer+= 7; //skip our pointer pcWWWServer forward 7 characters. Past the "http://"
    else
        pcWWWServer = ppcArgV[1]; //It doesnt have http://, just grab the pointer to the string
	//Work out what the page part of the path is
    // If there is a "/" in the URL (after the http:// has been stripped) then
    // replace it with a 0 so the string terminates as just the name.  Create
    // a new string pointer (pcPage) to be a copy of the remaining string OR
    // just "/" if no page details have been provided
	//
	// strstr() - find a string in another string. return the first position
	// strdup() - duplicate a string, return a pointer to a new string that's a copy. New memory!
    if (pcPos = strstr(pcWWWServer, "/"))
    {
        pcPage = strdup(pcPos);
        pcPos[0] = 0; //We're splitting the original string by doing this. But entering a null
    } else
        pcPage = strdup("/");
    // Call FillAddress() to fill sAddress with the IP address details (and port
    // number 80) of the requested URL
	//
	// INPUT OUTPUT
    FillAddress(pcWWWServer, &sAddress);
    /* Download The Webpage */
    //Get some memory ready to store the entire page
    //What if our page was bigger than this?!
    //This is a bad design and we wouldn't use it in production code.
    char bufferAllOfPage[1000000];
    bzero(bufferAllOfPage, sizeof(bufferAllOfPage));
	//Get the variables we need to open a network socket to the webserver
    //and get data back
	int sockfd; //This will the be the var we communicate with the server through
	char buffer[1024]; //We'll use this for recieving data
	int bytes_read; //This is to know how much data we've got
    //Try to create a new network socket
    if( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
        printerror("Socket error");
    //Try to connect that socket to the webserver
    //See we use sAddress that we got earlier
    if( connect(sockfd, (struct sockaddr*)&sAddress, sizeof(sAddress)) != 0)
        printerror("Couldn't connect");
    //Ok, we're connected
    //Tell the webserver what page we want to retrieve
    //Don't forget to tell them which site we're asking for (The host bit)
    // and which page we want
    sprintf(buffer, "GET %s HTTP/1.0\nHost: %s\n\n", pcPage, pcWWWServer);
    send(sockfd, buffer, strlen(buffer), 0);
    //Start recieving data from the server
    //Grab a chunk at a time and put it into the temporary buffer
    //we made before called....buffer
    do
    {
        //Blank out our buffer of retreived data
        //Then ask the network stack to give us some more
        bzero(buffer, sizeof(buffer));
        bytes_read = recv(sockfd, buffer, sizeof(buffer), 0);
        if( bytes_read > 0) //Did we get any?
        {
            //Copy the text we just got from the server into the
            //buffer we're storing the whole page in
            strncat(bufferAllOfPage, buffer, bytes_read);
            //strncat stuffs one string on to the end of another string. It's smart
            //enough to find the right place by itself. We still pass along bytes_read
            //so that it only copies as many characters as we want it to.
        }
    }
    while ( bytes_read > 0); //keep going through this loop until we have all the page
    //Clean up our network socket
	close(sockfd);
    /* Now lets try and parse out the links and images */
    //We're doing to do some very nieve searching, so first thigns first, make
    //the whole string lower case. (Uses the ctype.h library)
    int i = 0;
    while(bufferAllOfPage[i])
    {
        bufferAllOfPage[i] = tolower(bufferAllOfPage[i]);
        i++;
    }
    printf("\nLooking for Links:\n");
    //Step through the string looking for things like this
    // href=' ...... '
    //These are links to other pages and documents
    //Work out where it starts and ends, then print this URL out to the user
    char *posStartLink;
    char *posEndLink;
    char *placeToStartLooking;
    placeToStartLooking = bufferAllOfPage;
    do
    {
        //Find the first text saying ' href="'
        posStartLink = strstr(placeToStartLooking, " href=\"");
        if(posStartLink)
        {
            //If we found the start of a link, then try to find the end of it
            posStartLink += 7; //+7 to get us past the href=" characters
            posEndLink = strstr(posStartLink, "\"");
        }
        //Did we find anything (start AND end)?
        if(posStartLink && posEndLink)
        {
            //Ok we found a link
            //Extract the text of that link into a new string
            int linkLength;
            char linkBuf[1000];
            linkLength = posEndLink - posStartLink;
            strncpy(linkBuf, posStartLink, linkLength);
            linkBuf[linkLength] = 0;
            //Print out the link we found
            printf("%s\n", linkBuf);
            //Move up the position of where to look
            placeToStartLooking = posEndLink;
        }
        else
            break; //We didnt find anything, so stop looking.
    }
    while(posEndLink <= (bufferAllOfPage + strlen(bufferAllOfPage)) );
    //Keep going until the end of the HTML we got
    return 0;
}
Example #4
0
int main(int argc, char *argv[])
#endif
{
    int       list_s;
    int       sock;
    short int port;
    struct    sockaddr_in servaddr;
    int maxBuffer = PHS_GetRequestBufferLength();
    unsigned char* request;
    unsigned int requestLen;
    unsigned int responseType;
    int res;
    unsigned char responseHeader[4];
    unsigned char* response;
    unsigned int responseLength;
    char** cursor;
    int ok;
    int repeat;

#if defined(WIN32)
    WSADATA data;
    if(WSAStartup(MAKEWORD(2, 2), &data))
    {
	printf("WSAStartup failed\n");
	exit(1);
    }
#endif

    request = malloc(maxBuffer);

    if(argc < 3)
    {
	printf("Usage %s [ip4address:]port request ...\n",argv[0]);
	printf("where request is one of\n");
	printf("  status logid\n");
	printf("  fetch logid blockid\n");
	printf("  stream logid latency buffersize\n");
	exit(1);
    }

    /* Set up server address */
    if(!FillAddress(argv[1],&servaddr))
    {
	printf( "%s: Invalid server address %s\n",argv[0], argv[1]);
	exit(1);
    }
    cursor = argv+2;
    argc-=2;

    /*  Create the socket  */
    if((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0 )
    {
      printf( "Error creating socket %d.\n",sock);
	perror("Error");
	exit(1);
    }

    if(connect(sock, (struct sockaddr *) &servaddr, sizeof(servaddr))<0)
    {
	printf("Error calling connect()\n");
	exit(1);
    }

    /* Loop round all requests on the command line */
    ok = 1;
    while(argc)
    {
	/* Create a request */
	if(!strcmp("status",cursor[0]))
	{
	    int logid;
	    if(argc<2)
	    {
		printf("Usage: status logid\n");
		exit(1);
	    }
	    logid = ParseInt(cursor[1],&ok);
	    if(!ok)
	    {
		printf("Invalid logid\n");
		exit(1);
	    }
	    requestLen = PHS_MakeStatusRequest(request,maxBuffer,&responseType,logid);
	    printf("Sending Status Request logid %d\n",logid);
	    cursor += 2;
	    argc -= 2;
	}
	else if(!strcmp("fetch",cursor[0]))
	{
	    int logid, blockid;
	    if(argc<3)
	    {
		printf("Usage: fetch logid blockid\n");
		exit(1);
	    }
	    logid = ParseInt(cursor[1],&ok);
	    if(!ok)
	    {
		printf("Invalid logid\n");
		exit(1);
	    }
	    blockid = ParseInt(cursor[2],&ok);
	    if(!ok)
	    {
		printf("Invalid blockid\n");
		exit(1);
	    }
	    requestLen = PHS_MakeFetchRequest(request,maxBuffer,&responseType,
					      logid,blockid);
	    printf("Sending Fetch Request logid %d blockid %d\n",
		   logid,blockid);
	    cursor += 3;
	    argc -= 3;
	}
	else if(!strcmp("stream",cursor[0]))
	{
	    int logid, latency, buffersize, tag;
	    if(argc<5)
	    {
		printf("Usage: stream logid latency buffersize highesttag\n");
		exit(1);
	    }
	    logid = ParseInt(cursor[1],&ok);
	    if(!ok)
	    {
		printf("Invalid logid\n");
		exit(1);
	    }
	    latency = ParseInt(cursor[2],&ok);
	    if(!ok)
	    {
		printf("Invalid latency\n");
		exit(1);
	    }
	    buffersize = ParseInt(cursor[3],&ok);
	    if(!ok)
	    {
		printf("Invalid buffersize\n");
		exit(1);
	    }
	    tag = ParseInt(cursor[4],&ok);
	    if(!ok)
	    {
		printf("Invalid highesttag\n");
		exit(1);
	    }
	    requestLen = PHS_MakeStreamRequest(request,maxBuffer,&responseType,
					       logid,latency,buffersize,tag);
	    printf("Sending Stream Request logid %d latency %d buffersize %d tag %d\n",
		   logid,latency,buffersize,tag);
	    cursor += 5;
	    argc -= 5;
	}
	else
	{
	    printf("Request %s is not understood\n",cursor[0]);
	    exit(1);
	}

	/* Send request out */
	res = send(sock,request,requestLen,0);
	if(res != requestLen)
	{
	    printf("Expected to write %d but only wrote %d\n",requestLen,res);
	}

	repeat = 1;
	while(repeat)
	{
	    /* Read the length back */
	    res = Recv(sock,responseHeader,4,0);
	    if(res != 4)
	    {
		printf("Could not read response header\n");
		exit(1);
	    }

	    /* Make space for the response */
	    responseLength=PHS_GetResponseRemaining(responseHeader);
	    response = malloc(responseLength);

	    /* Read the rest of the response */
	    res = Recv(sock,response,responseLength,0);
	    if(res != responseLength)
	    {
		printf("Could not read response body\n");
		exit(1);
	    }

	    printf("Read %d bytes in body\n",responseLength);

	    /* Check that response is valid or in error */
	    res = PHS_GetResponseError(response,responseLength,responseType);
	    if(res)
	    {
		printf("Response has error %d\n",res);
		exit(1);
	    }

	    switch(responseType)
	    {
	    case PHS_RQ_STATUS:
		ProcessStatus(response);
		repeat = 0;
		break;
	    case PHS_RQ_FETCH:
		ProcessFetch(response);
		repeat = 0;
		break;
	    case PHS_RQ_STREAM:
		ProcessStream(response);
		break;
	    default:
		printf("Cannot handle response type %d\n",responseType);
		break;
	    }
	    free(response);
	}
    }
    return 0;
}