void drawUploadTransfer() {
	sceDisplaySetMode(0, SCR_WIDTH, SCR_HEIGHT);

	sceGuStart(GU_DIRECT, list);
	sceGuTexFilter(GU_LINEAR, GU_LINEAR);
	sceGuFinish();
	sceGuSync(0, 0);

	// This time, we only need one buffer.
	switchBuf(0, GU_PSM_8888);
	drawTexFlush(2, 2, 16, GU_PSM_T8, imageData, clutAddOne, vertices1);

	sceDisplayWaitVblank();

	// Okay, let's draw a totally different pattern in memory.
	for (int y = 0; y < 272; ++y) {
		for (int x = 0; x < 512; ++x) {
			copybuf[y * 512 + x] = (x & 1) + (y & 1);
		}
	}
	sceKernelDcacheWritebackInvalidateAll();
	sceDmacMemcpy(getBufAddr(0), copybuf, sizeof(copybuf));
	sceKernelDcacheWritebackInvalidateAll();

	// Now download should display out pattern.
	displayBuffer("Pattern");
}
void testBlendFunc(const char *title, u32 prev, u32 c, int op, int src, int dst, u32 fixa, u32 fixb) {
	for (size_t i = 0; i < sizeof(copybuf) / 4; ++i) {
		copybuf[i] = prev;
	}
	sceKernelDcacheWritebackInvalidateAll();
	sceDmacMemcpy(sceGeEdramGetAddr(), copybuf, sizeof(copybuf));
	sceKernelDcacheWritebackInvalidateAll();

	sceGuStart(GU_DIRECT, list);

	sceGuEnable(GU_BLEND);
	sceGuBlendFunc(op, src, dst, fixa, fixb);

	sceGuEnable(GU_STENCIL_TEST);
	sceGuStencilFunc(GU_ALWAYS, 0xAA, 0xFF);
	sceGuStencilOp(GU_REPLACE, GU_REPLACE, GU_REPLACE);

	drawBoxCommands(c);

	sceGuFinish();
	sceGuSync(GU_SYNC_WAIT, GU_SYNC_WHAT_DONE);

	displayBuffer(title);

	sceGuDisable(GU_BLEND);
}
void drawWithIndexOffsetsFmt(int clutfmt) {
	static const int masks[] = {0x00, 0x01, 0x02, 0x0F, 0xF0, 0x77, 0x80, 0x55};
	for (size_t i = 0; i < ARRAY_SIZE(masks); ++i) {
		char temp[128];
		snprintf(temp, sizeof(temp), "  Index mask %02x", masks[i]);

		drawTexFlush(1, 1, 16, GU_PSM_T32, imageData255, clutPattern, clutfmt, 0xFF, vertices2, masks[i]);
		sceDisplayWaitVblank();
		displayBuffer(temp);
	}
}
Exemple #4
0
    uint16_t ZMCamera::receiveData(unsigned long int timeout) {
      unsigned long int timestamp = millis();
      uint16_t t_buflen = bufferLen;

      while ((millis()-timestamp) < timeout) {
        while(camStream->available()) {
          int inByte = camStream->read();
          camBuffer[bufferLen++] = inByte;
        };
      };
      if (_debug)
        displayBuffer();
      return(bufferLen-t_buflen);
    };
void drawInterTransfer() {
	sceDisplaySetMode(0, SCR_WIDTH, SCR_HEIGHT);

	// First draw a texture to buffer 1.  We'll use a clut here from memory.
	switchBuf(0, GU_PSM_8888);
	drawTexFlush(2, 2, 16, GU_PSM_T8, imageData, clutAddOne, vertices1);

	// Second, another texture to buffer 2.  With a different clut so that they are visibly different.
	switchBuf(1, GU_PSM_8888);
	drawTexFlush(2, 2, 16, GU_PSM_T8, imageData, clutAddThree, vertices1);

	sceDisplayWaitVblank();

	// Okay, at this point we have two buffers.  Let's display one to make sure download works.
	displayBuffer("Initial download");

	// Next, let's copy between them.
	sceKernelDcacheWritebackInvalidateAll();
	sceDmacMemcpy(getBufAddr(1), getBufAddr(0), sizeof(copybuf));
	sceKernelDcacheWritebackInvalidateAll();

	// Now download should display the other buffer.
	displayBuffer("Copied buffer");
}
Exemple #6
0
void vowel_length(int socket_descriptor, lab_1_request *request) {
    vlength_response *response = (vlength_response *)malloc(sizeof(vlength_response));
    response->request_id = request->request_id;
    response->vlength = 0;

    int i;
    char *response_payload = (char *)malloc(sizeof(char) * MAX_MESSAGE_SIZE);
    memset(response_payload, 0, sizeof(char) * MAX_MESSAGE_SIZE);

    printf("Received for vowel length: %s\n", request->message);
    for(i = 0; i < request->total_message_length - 5; i++) {
        switch(request->message[i]) {        
            case 'a':
            case 'A':
            case 'e':
            case 'E':
            case 'i':
            case 'I':            
            case 'o':
            case 'O':
            case 'u':
            case 'U':
                response->vlength += 1;
                break;
            default:
                break;
        }
    }

    response->total_message_length = 6;
    int bytes_to_send = response->total_message_length;

    printf("\nSending:\n\nTotal Message Length: %d\nRequest ID: %d\nVlength: %d\n", 
            response->total_message_length, 
            response->request_id,
            response->vlength);    
    displayBuffer((char *)response, sizeof(vlength_response));

    to_network_byte_order((lab_1_request *) response);
    if(!is_big_endian()) {
        response->vlength = htons(response->vlength);
    }
   
    send(socket_descriptor, response, bytes_to_send, 0);
}
void init() { 
	sceGuInit();
	sceGuStart(GU_DIRECT, list);
	sceGuDrawBuffer(GU_PSM_8888, fbp0, 512);
	sceGuDispBuffer(480, 272, fbp0, 512);
	sceGuDepthBuffer(dbp0, 512);
	sceGuOffset(2048 - (240 / 2), 2048 - (136 / 2));
	sceGuViewport(2048, 2048, 240, 136);
	sceGuDepthRange(65535, 0);
	sceGuDepthMask(0);
	sceGuScissor(0, 0, 480, 272);
	sceGuEnable(GU_SCISSOR_TEST);
	sceGuFrontFace(GU_CW);
	sceGuShadeModel(GU_SMOOTH);
	sceGuDisable(GU_TEXTURE_2D);

	ScePspFMatrix4 ones = {
		{1, 0, 0, 0},
		{0, 1, 0, 0},
		{0, 0, 1, 0},
		{0, 0, 0, 1},
	};

	sceGuSetMatrix(GU_MODEL, &ones);
	sceGuSetMatrix(GU_VIEW, &ones);
	sceGuSetMatrix(GU_PROJECTION, &ones);

	sceGuFinish();
	sceGuSync(0, 0);
 
	sceDisplayWaitVblankStart();
	sceGuDisplay(1);

	memset(copybuf, 0x44, sizeof(copybuf));
	sceKernelDcacheWritebackInvalidateAll();
	sceDmacMemcpy(sceGeEdramGetAddr(), copybuf, sizeof(copybuf));
	sceKernelDcacheWritebackInvalidateAll();

	displayBuffer("Initial");
}
void drawIntraTransfer() {
	sceDisplaySetMode(0, SCR_WIDTH, SCR_HEIGHT);

	sceGuStart(GU_DIRECT, list);
	sceGuTexFilter(GU_LINEAR, GU_LINEAR);
	sceGuFinish();
	sceGuSync(0, 0);

	// This time, we only need one buffer.
	switchBuf(0, GU_PSM_8888);
	drawTexFlush(2, 2, 16, GU_PSM_T8, imageData, clutAddOne, vertices1);

	sceDisplayWaitVblank();

	// Next, let's copy from this buffer to itself.
	sceKernelDcacheWritebackInvalidateAll();
	sceDmacMemcpy(getBufAddr(0), (u8 *)getBufAddr(0) + sizeof(copybuf) / 2, sizeof(copybuf) / 2);
	sceKernelDcacheWritebackInvalidateAll();

	// Now download should display a different buffer.
	displayBuffer("Spliced buffer");
}
Exemple #9
0
int main(int argc, char** argv )
{
    IplImage *img, *filterMask = NULL;
    CvAdaptiveSkinDetector filter(1, CvAdaptiveSkinDetector::MORPHING_METHOD_ERODE_DILATE);
    ASDFrameSequencer *sequencer;
    CvFont base_font;
    char caption[2048], s[256], windowName[256];
    long int clockTotal = 0, numFrames = 0;
    std::clock_t clock;

    if (argc < 4)
    {
        help(argv);
        sequencer = new ASDFrameSequencerWebCam();
        (dynamic_cast<ASDFrameSequencerWebCam*>(sequencer))->open(-1);

        if (! sequencer->isOpen())
        {
            std::cout << std::endl << "Error: Cannot initialize the default Webcam" << std::endl << std::endl;
        }
    }
    else
    {
        sequencer = new ASDFrameSequencerImageFile();
        (dynamic_cast<ASDFrameSequencerImageFile*>(sequencer))->open(argv[1], std::atoi(argv[2]), std::atoi(argv[3]) ); // A sequence of images captured from video source, is stored here

    }
    std::sprintf(windowName, "%s", "Adaptive Skin Detection Algorithm for Video Sequences");

    cvNamedWindow(windowName, CV_WINDOW_AUTOSIZE);
    cvInitFont( &base_font, CV_FONT_VECTOR0, 0.5, 0.5);

    // Usage:
    //      c:\>CvASDSample "C:\VideoSequences\sample1\right_view\temp_%05d.jpg" 0 1000

    std::cout << "Press ESC to stop." << std::endl << std::endl;
    while ((img = sequencer->getNextImage()) != 0)
    {
        numFrames++;

        if (filterMask == NULL)
        {
            filterMask = cvCreateImage( cvSize(img->width, img->height), IPL_DEPTH_8U, 1);
        }
        clock = std::clock();
        filter.process(img, filterMask);    // DETECT SKIN
        clockTotal += (std::clock() - clock);

        displayBuffer(img, filterMask, 0, 255, 0);

        sequencer->getFrameCaption(caption);
        std::sprintf(s, "%s - %d x %d", caption, img->width, img->height);
        putTextWithShadow(img, s, cvPoint(10, img->height-35), &base_font);

        std::sprintf(s, "Average processing time per frame: %5.2fms", (double(clockTotal*1000/CLOCKS_PER_SEC))/numFrames);
        putTextWithShadow(img, s, cvPoint(10, img->height-15), &base_font);

        cvShowImage (windowName, img);
        cvReleaseImage(&img);

        if (cvWaitKey(1) == 27)
            break;
    }

    sequencer->close();
    delete sequencer;

    cvReleaseImage(&filterMask);

    cvDestroyWindow(windowName);

    std::cout << "Finished, " << numFrames << " frames processed." << std::endl;

    return 0;
}
Exemple #10
0
int main(int argc, char *argv[]) // _M1 
{
    int client_waiting = 0;
    int waiting_client_ip = -1;
    int waiting_client_port = -1;
	int sockfd;
	struct addrinfo hints, *servinfo, *p;
	int rv;
	int numbytes;
	struct sockaddr_storage their_addr;
	char buf[MAXBUFLEN];
	socklen_t addr_len;
	char s[INET6_ADDRSTRLEN];

	/* _M1 Begin */
	if (argc != 2) {
		fprintf(stderr,"usage: ServerUDP Port# \n");
		exit(1);
	}
	/* _M1 End*/

	memset(&hints, 0, sizeof hints);
	hints.ai_family = AF_UNSPEC; // set to AF_INET to force IPv4
	hints.ai_socktype = SOCK_DGRAM;
	hints.ai_flags = AI_PASSIVE; // use my IP

	if ((rv = getaddrinfo(NULL, argv[1] /* _M1 MYPORT */, &hints, &servinfo)) != 0) {
		fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
		return 1;   
	}

	// loop through all the results and bind to the first we can
	for(p = servinfo; p != NULL; p = p->ai_next) {
		if ((sockfd = socket(p->ai_family, p->ai_socktype,
				p->ai_protocol)) == -1) {
			perror("listener: socket");
			continue;
		}

		if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
			close(sockfd);
			perror("listener: bind");
			continue;
		}

		break;
	}

	if (p == NULL) {
		fprintf(stderr, "listener: failed to bind socket\n");
		return 2;
	}

	freeaddrinfo(servinfo);


	while (1){ 	// _M2 

	    printf("\n >>>> listener: waiting for a datagram...\n");

	    addr_len = sizeof their_addr;

        lab_3_request *request = (lab_3_request *)malloc(sizeof(lab_3_request));

        if ((numbytes = recvfrom(sockfd, request, /*MAXBUFLEN*/sizeof(lab_3_request), 0,
                        (struct sockaddr *)&their_addr, &addr_len)) == -1) {
            perror("recvfrom");
            exit(1);
        }

        printf("Received raw bytes:\n");
        displayBuffer((char *) request, numbytes);

        request_to_host_byte_order(request);

        printf("Bytes after endianness conversion:\n");
        displayBuffer((char *)request, numbytes);
        printf("Received from client:\n");
        printf("Magic number: %u\n", request->magic_number);
        printf("Group ID: %u\n", request->group_id);
        printf("Port Number: %u\n", request->port_number);

        printf("listener: got packet from %s\n",
                inet_ntop(their_addr.ss_family,
                    get_in_addr((struct sockaddr *)&their_addr),
                    s, sizeof s));
        printf("listener: packet is %d bytes long\n", numbytes);
    
        int error_code = get_error_code(request->group_id, 
                request->port_number, request->magic_number);

        if(error_code)
        {
            lab_3_error_response *response = malloc(sizeof(lab_3_error_response));
            response->magic_number = MAGIC_NUMBER;
            response->group_id = GROUP_ID;
            response->padding = PADDING;
            response->error_code = error_code;

            printf("Sending error response:\n");
            displayBuffer((char *)response, 
                    ERROR_RESPONSE_SIZE);
            printf("Magic Number: %u\n", response->magic_number);
            printf("Group ID: %u\n", response->group_id);
            printf("Padding: %u\n", response->padding);
            printf("Error Code: %u\n", response->error_code);

            //TODO: To network byte order
            error_to_network_byte_order(response);
            sendto(sockfd, response, ERROR_RESPONSE_SIZE, 0,
                    (struct sockaddr *)&their_addr, addr_len);

        }
        else if(client_waiting) {
            lab_3_client_waiting_response *response = malloc(sizeof(lab_3_client_waiting_response));
            response->magic_number = MAGIC_NUMBER;
            response->group_id = GROUP_ID;
            response->ip_address = waiting_client_ip;
            response->port_number = waiting_client_port;

            printf("\nSending response to matched player:");
            displayBuffer((char *)response, 
                    CLIENT_WAITING_RESPONSE_SIZE);
            printf("Magic Number: %u\n", response->magic_number);
            printf("Group ID: %u\n", response->group_id);
            printf("IP Address (in decimal): %u\n", response->ip_address);
            printf("Port Number: %u\n", response->port_number);

            //TODO: To network byte order
            client_waiting_response_to_network_byte_order(response);
            sendto(sockfd, response, CLIENT_WAITING_RESPONSE_SIZE, 0,
                    (struct sockaddr *)&their_addr, addr_len);

            //Flush stored information
            client_waiting = 0;
            waiting_client_ip = -1;
            waiting_client_port = -1;
        } else {
            client_waiting = -1;
            //TODO: verify this correctly converts IP addresses
            waiting_client_ip = get_ip_address(&their_addr);
            waiting_client_port = request->port_number;
            
            lab_3_no_client_waiting_response *response = malloc(sizeof(lab_3_client_waiting_response));
            
            response->magic_number = request->magic_number;
            response->group_id = request->group_id;
            response->port_number = request->port_number;

            printf("\nSending Response to new game host:");
            displayBuffer((char *)response, 
                    NO_CLIENT_WAITING_RESPONSE_SIZE);
            printf("Magic Number: %u\n", response->magic_number);
            printf("Group ID: %u\n", response->group_id);
            printf("Port Number: %u\n", response->port_number);

            no_client_waiting_response_to_network_byte_order(response);
            sendto(sockfd, response, NO_CLIENT_WAITING_RESPONSE_SIZE, 0,
                    (struct sockaddr *)&their_addr, addr_len);
        }

	} // _M2 
	close(sockfd);

	return 0;
}
Exemple #11
0
int generateSign(char* inputFile, char* privKeyFile, char* signedFile)
{
		unsigned char* buf = (unsigned char*)malloc(MSG_BUF_LEN*sizeof(unsigned char));
		int* encoded_buf = (int*)malloc(MSG_BUF_LEN * sizeof(int));
		int size_encrypted, len_d_2 = 0;
		unsigned char md5hash[MD5_DIGEST_LENGTH];
		int i, index = MSG_BUF_LEN -1, numOctetsAdded=0, totalLength = 0, octet_string_len = 0, num_octets;
		int n = readFileInBuffer(inputFile, buf);
		num_octets = N_NUM_BITS/8;
		MD5(buf, n, md5hash);
		int protoLen = strlen(Md5OidValue)/2;
		#ifdef DEBUG3
			printf("MD5 HASH\n");
			for (i = 0; i < MD5_DIGEST_LENGTH; i++) 
			{
				printf("%02x ", md5hash[i]);
			}
			printf("\n");
		#endif
		
		//embed the md5 buffer
		embed_md5_buffer(encoded_buf, md5hash, &index, MD5_DIGEST_LENGTH);
		totalLength+= MD5_DIGEST_LENGTH;
		
		//append the length octet
		numOctetsAdded = appendLengthToBuffer( MD5_DIGEST_LENGTH , encoded_buf, &index);
		totalLength+=numOctetsAdded;
		//append the identifier octet
		appendIdentifierOctet(TAG_OCTET_STRING, PRIMITIVE, 0, encoded_buf, &index);
		totalLength++;
		
		//Add length octet - 0
		numOctetsAdded = appendLengthToBuffer( 0 , encoded_buf, &index);
		totalLength+=numOctetsAdded;
		len_d_2 += numOctetsAdded;
		
		//Add identifier octet
		appendIdentifierOctet(TAG_NULL, PRIMITIVE, UNIVERSAL, encoded_buf, &index);
		totalLength++;
		len_d_2++;
		
		//append the MD5 object identifier value
		addOID(encoded_buf, &index, Md5OidValue);
		totalLength+=protoLen;
		len_d_2+=protoLen;
		
		//add length of the identifier
		numOctetsAdded = appendLengthToBuffer( protoLen , encoded_buf, &index);
		totalLength+=numOctetsAdded;
		len_d_2+=numOctetsAdded;
		
		//add identifier octet
		appendIdentifierOctet(TAG_OID, PRIMITIVE, UNIVERSAL, encoded_buf, &index);
		totalLength++;
		len_d_2++;
		
		//add length octet
		numOctetsAdded = appendLengthToBuffer( len_d_2 , encoded_buf, &index);
		totalLength+=numOctetsAdded;
		
		//add identifier octet
		appendIdentifierOctet(TAG_SEQUENCE, CONSTRUCTED, UNIVERSAL, encoded_buf, &index);
		totalLength++;
		
		//add length octet
		appendLengthToBuffer( totalLength , encoded_buf, &index);
		
		//add identifier octet
		appendIdentifierOctet(TAG_SEQUENCE, CONSTRUCTED, UNIVERSAL, encoded_buf, &index);
		#ifdef DEBUG2
			displayBuffer(encoded_buf, index+1,  MSG_BUF_LEN);
		#endif
		
		octet_string_len = (MSG_BUF_LEN - index - 1)/8;

		unsigned char* octet_string = (unsigned char*)malloc(octet_string_len * sizeof(unsigned char));
		memset(octet_string, 0, octet_string_len);
		
		getOctetString(encoded_buf, octet_string, index+1, MSG_BUF_LEN);
		
		unsigned char* encrypted_buff = (unsigned char*)malloc(num_octets*sizeof(unsigned char));
		memset(encrypted_buff, 0, num_octets);
		
		encrypt_buff(octet_string, encrypted_buff, privKeyFile, PRIVATE_KEY, octet_string_len, &size_encrypted);
		writeEncryptedBuffer(signedFile, encrypted_buff, size_encrypted);
	
		//decrypt(signedFile, "decr", "pub.der", PUBLIC_KEY);
		//writeKeyBuffer(signedFile, encoded_buf, index+1, MSG_BUF_LEN);
}
Exemple #12
0
int main(int argc, char *argv[])
{

    int sockfd, numbytes;  
    struct addrinfo hints, *servinfo, *p;
    int rv;
    char s[INET6_ADDRSTRLEN];

    //client servername PortNumber Operation String
    if (argc != 5) {
        fprintf(stderr,"usage: client servername PortNumber Operation String\n");
        exit(1);
    }

    
    const int SERVER_NAME = 1;
    const int PORT_NUMBER = 2;
    const int OPERATION = 3;
    const int MESSAGE_INDEX = 4;

    //char* server_name = argv[SERVER_NAME];
    char* server_name = (char *)malloc(strlen(argv[SERVER_NAME]));
    memcpy(server_name, argv[SERVER_NAME], strlen(argv[SERVER_NAME]));
    printf("\nServer name: %s\n", server_name);

    char* port_number = (char *)malloc(strlen(argv[PORT_NUMBER]));
    memcpy(port_number, argv[PORT_NUMBER], strlen(argv[PORT_NUMBER]));
    printf("Port number: %s\n", port_number);

    char* operation = (char *)malloc(strlen(argv[OPERATION]));
    memcpy(operation, argv[OPERATION], strlen(argv[OPERATION]));
    printf("Operation: %s\n", operation);

    char* message = (char *)malloc(strlen(argv[MESSAGE_INDEX]));
    memcpy(message, argv[MESSAGE_INDEX], strlen(argv[MESSAGE_INDEX]));
    printf("String: %s\n", message);
    //displayBuffer(message, strlen(message));

    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;

    if ((rv = getaddrinfo(server_name, port_number, &hints, &servinfo)) != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
        return 1;
    }

    // loop through all the results and connect to the first we can
    for(p = servinfo; p != NULL; p = p->ai_next) {
        if ((sockfd = socket(p->ai_family, p->ai_socktype,
                p->ai_protocol)) == -1) {
            perror("client: socket");
            continue;
        }

        if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
            close(sockfd);
            perror("client: connect");
            continue;
        }

        break;
    }

    if (p == NULL) {
        fprintf(stderr, "client: failed to connect\n");
        return 2;
    }

    inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr),
            s, sizeof s);
    printf("client: connecting to %s\n", s);

    freeaddrinfo(servinfo); // all done with this structure

    lab_1_request *request = (lab_1_request *)malloc(sizeof(lab_1_request));
    memcpy(request->message, message, strlen(message));
    request->request_id = 1;
    request->operation = atoi(operation);
    request->total_message_length = 5 + strlen(request->message);

    int bytes_to_send = request->total_message_length;
    to_network_byte_order(request);

    clock_t begin, end;
    double time_spent = 0;

    begin = clock();
    /* here, do your time-consuming job */
    
    if(send(sockfd, request, bytes_to_send, 0) == -1) {
        perror("send");
    }

    if(request->operation == VLENGTH_REQUEST) {
        vlength_response *response = (vlength_response *)malloc(sizeof(vlength_response));

        if ((numbytes = recv(sockfd, response, sizeof(vlength_response), 0)) == -1) {
            perror("recv");
            exit(1);
        }

        end = clock();
        time_spent = (double)(end - begin) / CLOCKS_PER_SEC;


	    displayBuffer((char *)response, numbytes);

        to_host_byte_order((lab_1_request *) response);
        if(!is_big_endian()) {
            response->vlength = ntohs(response->vlength);
        }

        printf("client: Total round trip '%f' seconds\n", time_spent);
	    printf("client: message length '%d'\n", response->total_message_length);
	    printf("client: request ID '%d'\n", response->request_id);
        printf("client: received vlength '%d'\n\n", response->vlength);

    } else if (request->operation == VOWEL_REMOVAL_REQUEST) {
        disemvowel_response *response = (disemvowel_response *)malloc(sizeof(disemvowel_response));
        memset(response, 0, MAX_MESSAGE_SIZE);

        if ((numbytes = recv(sockfd, response, sizeof(disemvowel_response), 0)) == -1) {
            perror("recv");
            exit(1);
        }

        end = clock();
        time_spent = (double)(end - begin) / CLOCKS_PER_SEC;

        to_host_byte_order((lab_1_request *) response);

	    displayBuffer((char *)response, numbytes);
        printf("client: Total round trip '%f' seconds\n", time_spent);
	    printf("client: message length '%d'\n", response->total_message_length);
	    printf("client: request ID '%d'\n", response->request_id);
        printf("client: received message '%s'\n\n", response->message);

    }

    close(sockfd);

    return 0;
}
Exemple #13
0
int main(int argc, char *argv[])
{

    if(argc != 2) {
        printf("\nUsage:\n\nserver portnumber\n\n");
        return -1;
    }
    
    char* port_number = (char *)malloc(sizeof(argv[1]));
    memcpy(port_number, argv[1], sizeof(argv[1]));
    printf("Port number: %s\n", port_number);

    int sockfd, new_fd;  // listen on sock_fd, new connection on new_fd
    struct addrinfo hints, *servinfo, *p;
    struct sockaddr_storage their_addr; // connector's address information
    socklen_t sin_size;
    struct sigaction sa;
    int yes=1;
    char s[INET6_ADDRSTRLEN];
    int rv;

    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE; // use my IP

    if ((rv = getaddrinfo(NULL, port_number, &hints, &servinfo)) != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
        return 1;
    }

    // loop through all the results and bind to the first we can
    for(p = servinfo; p != NULL; p = p->ai_next) {
        if ((sockfd = socket(p->ai_family, p->ai_socktype,
                p->ai_protocol)) == -1) {
            perror("server: socket");
            continue;
        }

        if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes,
                sizeof(int)) == -1) {
            perror("setsockopt");
            exit(1);
        }

        if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
            close(sockfd);
            perror("server: bind");
            continue;
        }

        break;
    }

    if (p == NULL)  {
        fprintf(stderr, "server: failed to bind\n");
        return 2;
    }

    freeaddrinfo(servinfo); // all done with this structure

    if (listen(sockfd, BACKLOG) == -1) {
        perror("listen");
        exit(1);
    }

    sa.sa_handler = sigchld_handler; // reap all dead processes
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_RESTART;
    if (sigaction(SIGCHLD, &sa, NULL) == -1) {
        perror("sigaction");
        exit(1);
    }

    printf("server: waiting for connections...\n");

    while(1) {  // main accept() loop
        sin_size = sizeof their_addr;
        
        new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
        if (new_fd == -1) {
            perror("accept");
            continue;
        }

        inet_ntop(their_addr.ss_family,
            get_in_addr((struct sockaddr *)&their_addr),
            s, sizeof s);
        printf("server: got connection from %s\n", s);

        if (!fork()) { // this is the child process
            close(sockfd); // child doesn't need the listener
            //read in data
            //do appropriate action
            lab_1_request *request = (lab_1_request *)malloc(sizeof(lab_1_request));
            int num_bytes;
            if(num_bytes = recv(new_fd, request, sizeof(lab_1_request), 0) == -1) {
                perror("read error");
                exit(-1);
            }
            
            printf("Read %d bytes\n", num_bytes);
            
            to_host_byte_order(request);

            displayBuffer((char *) request, num_bytes);
            printf("\nReceived from client:\n");
            printf("Message size: %d\n", request->total_message_length);
            printf("Request id: %d\n", request->request_id);
            printf("Operation: %d\n", request->operation);
            printf("Message: %s\n\n", request->message);

            if(request->operation == VLENGTH_REQUEST) {
                vowel_length(new_fd, request);
            } else if (request->operation == VOWEL_REMOVAL_REQUEST) {
                remove_vowels(new_fd, request);
            } else {
                printf("Invalid request id\n");
            }
            close(new_fd);
            exit(0);
        }
        close(new_fd);  // parent doesn't need this
    }
    
    free(port_number);

    return 0;
}