예제 #1
0
파일: ex6_04.c 프로젝트: NoMan2000/c-prog
int main(void)
{
  char sentence[MAX_LEN];                        // Stores the sentence to be tested
  char sentence_chars[MAX_LEN];                  // Stores the sentence without punctuation and spaces
  size_t j = 0;                                  // Index to character position
  size_t length = 0;                             // Length of a string

  printf("Enter a sentence to be tested:\n");
  gets_s(sentence, MAX_LEN);

  // Copy only letters as lowercase
  for (size_t i = 0 ; i < strnlen_s(sentence, MAX_LEN) ; ++i)
    if(isalpha(sentence[i]))
      sentence_chars[j++] = tolower(sentence[i]);
  sentence_chars[j] = '\0';                      // Append string terminator

  length = strnlen_s(sentence_chars, MAX_LEN);   // Get the string length

  // Compare matching characters in the string
  // If any pair are not the same, then it's not a palindrome
  bool isPalindrome = true;
  for(size_t i = 0 ; i < length/2 ; ++i)
  {
    if(sentence_chars[i] != sentence_chars[length - 1 - i])
    {
      isPalindrome = false;
      break;
    }
  }
  printf("\n The sentence you entered is%sa palindrome.\n", isPalindrome ? " " : " not ");
    return 0;
}
예제 #2
0
/*
 * This function verifies the content type header and also
 * returns the length of the content header.  The
 * content type is important.  For example, the content
 * type is expected to be pkcs7 on a simple enrollment.
 */
static int est_io_check_http_hdrs (HTTP_HEADER *hdrs, int hdr_cnt,
                                   EST_OPERATION op)
{
    int i;
    int cl = 0;
    int content_type_present = 0, content_length_present = 0;
    int cmp_result;

    /*
     * Traverse all the http headers and process the ones that need to be
     * checked
     */
    for (i = 0; i < hdr_cnt; i++) {
        /*
         * Content type
         */
        memcmp_s(hdrs[i].name, sizeof(EST_HTTP_HDR_CT), EST_HTTP_HDR_CT,
            sizeof(EST_HTTP_HDR_CT), &cmp_result);
        if (!cmp_result) {
            content_type_present = 1;
            /*
             * Verify content is pkcs7 data
             */
            memcmp_s(hdrs[i].value,
                     strnlen_s(est_op_map[op].content_type, est_op_map[op].length),
                     est_op_map[op].content_type, strnlen_s(est_op_map[op].content_type, est_op_map[op].length),
                      &cmp_result);
            if (cmp_result) {
                EST_LOG_ERR("HTTP content type is %s", hdrs[i].value);
                return 0;
                }
        } else {
            /*
             * Content Length
             */
            memcmp_s(hdrs[i].name, sizeof(EST_HTTP_HDR_CL), EST_HTTP_HDR_CL,
                sizeof(EST_HTTP_HDR_CL), &cmp_result);
            if (!cmp_result) {
                content_length_present = 1;
                cl = atoi(hdrs[i].value);
            }
        }
    }
    
    /*
     * Make sure all the necessary headers were present.
     */
    if (content_type_present == 0 ) {
        EST_LOG_ERR("Missing HTTP content type  header");
        return 0;
    } else if (content_length_present == 0 ) {
        EST_LOG_ERR("Missing HTTP content length header");
        return 0;
    } 
    
    return cl;
}
예제 #3
0
void ConnectionHandler::SendResponse(Reply* reply)
{
	for (size_t i = 0; i < reply->headers.size(); i++)
	{
		char * line = reply->headers.at(i);

		boost::asio::async_write(socket_,
			boost::asio::buffer(line, strnlen_s(line, 512)),
			boost::bind(&ConnectionHandler::HandleWrite, this, boost::asio::placeholders::error));
	}
	if (reply->text_content)
	{
		char* line = reply->text_content;

		boost::asio::async_write(socket_,
			boost::asio::buffer(line, strnlen_s(line, 2048)),
			boost::bind(&ConnectionHandler::HandleWrite, this, boost::asio::placeholders::error));
	}
	else if (reply->file_location)
	{
		boost::system::error_code write_error;
		// send file as binary data
		// // load file (binary) and set possition at the end of file
		std::ifstream source_file(reply->file_location, std::ios_base::binary | std::ios_base::ate);
		if (source_file)
		{
			char file_buffer[8192]; //TODO 8192 should be const / Buffersize of 8192 is efficient, because it equals 1 or 2 disk blocks 
			size_t file_size = source_file.tellg();
			//set pointer to start of file
			source_file.seekg(0);

			while (true)
			{
				if (!source_file.eof()) //if -> pointer not at end of file
				{
					source_file.read(file_buffer, 8192); //TODO 1024 should be const
					if (source_file.gcount() <= 0) // if -> amount of bytes read <= 0
						cout << "Read file error" << endl;
					boost::asio::write(socket_, boost::asio::buffer(file_buffer, source_file.gcount()), boost::asio::transfer_all(), write_error);
					if (write_error)
						cout << "Socket write error" << endl;
				}
				else 
				{
					break;
				}
			}
			cout << "send file went successfull" << endl;
		}
	}
}
예제 #4
0
static struct curl_slist *acvp_add_auth_hdr(ACVP_CTX *ctx, struct curl_slist *slist) {
    char *bearer = NULL;
    char bearer_title[] = "Authorization: Bearer ";
    int bearer_title_size = (int)sizeof(bearer_title) - 1;
    int bearer_size = 0;

    if (!ctx->jwt_token && !(ctx->tmp_jwt && ctx->use_tmp_jwt)) {
        /*
         * We don't have a token to embed
         */
        return slist;
    }

    if (ctx->use_tmp_jwt && !ctx->tmp_jwt) {
        ACVP_LOG_ERR("Trying to use tmp_jwt, but it is NULL");
        return slist;
    }

    if (ctx->use_tmp_jwt) {
        bearer_size = strnlen_s(ctx->tmp_jwt, ACVP_JWT_TOKEN_MAX) + bearer_title_size;
    } else {
        bearer_size = strnlen_s(ctx->jwt_token, ACVP_JWT_TOKEN_MAX) + bearer_title_size;
    }

    bearer = calloc(bearer_size + 1, sizeof(char));
    if (!bearer) {
        ACVP_LOG_ERR("unable to allocate memory.");
        goto end;
    }

    if (ctx->use_tmp_jwt) {
        snprintf(bearer, bearer_size + 1, "%s%s", bearer_title, ctx->tmp_jwt);
    } else {
        snprintf(bearer, bearer_size + 1, "%s%s", bearer_title, ctx->jwt_token);
    }

    slist = curl_slist_append(slist, bearer);

    free(bearer);

end:
    if (ctx->use_tmp_jwt) {
        /* 
         * This was a single-use token.
         * Turn it off now... the library might turn it back on later.
         */
        ctx->use_tmp_jwt = 0;
    }

    return slist;
}
예제 #5
0
파일: utils.c 프로젝트: intelrsasw/intelRSD
bool str_end_with(char *str, char *substr)
{
    int lenstr = strnlen_s(str, RSIZE_MAX_STR);
    int lensubstr = strnlen_s(substr, RSIZE_MAX_STR);
    char *p = str + lenstr - lensubstr;
    char *p2 = substr;

    if (lenstr < lensubstr)
        return false;
    while(*p!='\0')
        if(*p++ != *p2++)
            return false;
    return true;
}
예제 #6
0
파일: util.c 프로젝트: timlenertz/EUI
EUIError EUIUtil_DuplicateString(const char* str, char** copy, size_t* length, size_t maxLength) {
	if(str == NULL) return NULL;
	
	#if __STDC_LIB_EXT1__
	size_t len = strnlen_s(str, maxLength);
	#else
	size_t len = strlen(str);
	#endif
	
	if(len == 0) return EUIErr(EUIErrorCode_InvalidArgument);
	
	char* cpy = (char*) malloc(len + 1);
	if(cpy == NULL) return EUIError(EUIErrorCode_MemoryAllocationError);
	
	#if __STDC_LIB_EXT1__
	memcpy_s((void*)cpy, len + 1, (const void*)str, len + 1);
	#else
	errno_t err = memcpy((void*)cpy, (const void*)str, len + 1);
	if(err != 0) {
		free((void*)cpy);
		return EUIErr(EUIErrorCode_SystemError);
	}
	#endif
	
	*copy = cpy;
	if(length) *length = len;
	
	return EUISuccess;
}
예제 #7
0
파일: ex6_02.c 프로젝트: NoMan2000/c-prog
int main(void)
{
  char list[MAX_LEN];                                      // Stores the list of comma separated words
  const char comma[] = ",";                                // The only word delimiter

  printf("Enter a comma separated list of words:\n");
  gets_s(list, sizeof(list));                              // Read the list of words

  // Remove spaces
  size_t index = 0;                                        // Character position
  size_t i = 0;
  do
  {
    if(isspace(list[i]))                                   // If it's whitespace...
      continue;                                            // ... skip the character...
    list[index++] = list[i];                               // ... otherwise copy the character
  } while(list[i++] != '\0');

  // Find words in list
  char *ptr = NULL;
  size_t list_len = strnlen_s(list, MAX_LEN);
  char *pWord = strtok_s(list, &list_len, comma, &ptr);    // Find 1st word
  if(pWord)
  {
    do
    {
      printf("%s\n", pWord);
      pWord = strtok_s(NULL, &list_len, comma, &ptr);      // Find subsequent words
    }while(pWord);                                         // NULL ends tokenizing
  }

	return 0;
}
예제 #8
0
파일: Ex11_05.c 프로젝트: NoMan2000/c-prog
/*****************************************
 * Creates a Name object on the heap and *
 * reads the first and second names from *
 * stdin.                                *
 * The freenodes() function takes care   *
 * of releasing the memory for names.    *
 *****************************************/
Name *readname(void)
{
  Name *pName = malloc(sizeof(Name));
  printf_s("Enter the first name: ");
  fgets(pName->first, FIRST_MAX, stdin);
  size_t len = strnlen_s(pName->first, FIRST_MAX);
  if(pName->first[len - 1] == '\n')                   // If there's a newline at the end 
    pName->first[len - 1] = '\0';                     // overwrite it.

  printf_s("Enter the second name: ");
  fgets(pName->second, SECOND_MAX, stdin);
  len = strnlen_s(pName->second, SECOND_MAX);
  if(pName->second[len - 1] == '\n')                  // If there's a newline at the end
    pName->second[len - 1] = '\0';                    // overwrite it.
  return pName;
}
예제 #9
0
파일: main.c 프로젝트: intelrsasw/intelRSD
int main(int argc, char** argv) {
	char plaintext[CIPHER_LENGTH_MAX] = {0};
	char keyfile[CIPHER_LENGTH_MAX] = {0};

	// Get plaintext to encrypt.
	if (argc < 3) {
		printf("error: Too few arguments.\n");
		printf("usage: %s plaintext key_file_path\n", argv[0]);;
		return -1;
	}

	int plaintext_length = strnlen_s(argv[1], RSIZE_MAX_STR);
	if (plaintext_length > 256-1) {
		printf("error: plaintext too long\n");
		printf("plaintext length: %d plaintext max length: %d\n",plaintext_length, 256);
		return -1;
	}
	strncpy_s(plaintext, sizeof(plaintext), argv[1], sizeof(plaintext));

	strncpy_s(keyfile, sizeof(plaintext), argv[2], sizeof(keyfile));

	char ciphertext[CIPHER_LENGTH_MAX] = {};
	rmm_encrypt(plaintext, keyfile, ciphertext);
	printf("ciphertext is:%s\n", ciphertext);

    return 0;
}
	void onReadable(Poco::Net::ReadableNotification* pNf)
	{
		pNf->release();

		try
		{
			char buffer[256] = { 0, };
			int n = m_socket.receiveBytes(buffer, sizeof(buffer));
			if (n > 0)
			{
				std::cout << "클라이언트에서 받은 메시지: " << buffer << std::endl;

				char szSendMessage[256] = { 0, };
				sprintf_s(szSendMessage, 256 - 1, "Re:%s", buffer);
				int nMsgLen = (int)strnlen_s(szSendMessage, 256 - 1);

				m_socket.sendBytes(szSendMessage, nMsgLen);
			}
			else
			{
				m_socket.shutdownSend();
				delete this;  // 메모리 해제하지 않으면 소멸자가 호출되지 않는다.
			}
		}
		catch (Poco::Exception& exc)
		{
			std::cerr << "EchoServer: " << exc.displayText() << std::endl;

			m_socket.shutdown();
			delete this;  
		}
	}
예제 #11
0
/**
  *  @brief open serial port
  *
  *  @param
  *  @return
  */
static int serial_open(char *dev)
{
	struct ipmi_msg req = {0};

	req.union_app_req.serial.serial_flag = IPMI_SERIAL_OPEN_DEV;
	req.netfn = OEM_IPMI_NETFN;
	req.cmd   = OEM_SERIAL_OPEN_CMD;

	memcpy_s(req.data, sizeof(req.data), dev, strnlen_s(dev, RSIZE_MAX_STR));

	req.data_len = strnlen_s(dev, RSIZE_MAX_STR);

	libipmi_serial_cmd(&req, serial_open_resp_handler, NULL);

	return 0;
}
예제 #12
0
파일: utils.c 프로젝트: intelrsasw/intelRSD
bool is_str_uuid(const char *str)
{
	if ((strnlen_s(str, RSIZE_MAX_STR) <= ID_STR_MAX_LEN) && (TRUE == is_str_num(str)))
		return FALSE;
	else
		return TRUE;
}
	virtual void run()
	{
		try
		{
			int recvSize = 0;

			do
			{
				char buffer[256] = { 0, };
				recvSize = socket().receiveBytes(buffer, sizeof(buffer));
				std::cout << "클라이언트에서 받은 메시지: " << buffer << std::endl;


				char szSendMessage[256] = { 0, };
				sprintf_s(szSendMessage, 128 - 1, "Re:%s", buffer);
				int nMsgLen = (int)strnlen_s(szSendMessage, 256 - 1);

				socket().sendBytes(szSendMessage, nMsgLen);				
			} while (recvSize > 0);

			std::cout << "클라이언트와 연결이 끊어졌습니다" << std::endl;
		}
		catch (Poco::Exception& exc)
		{
			std::cerr << "Session: " << exc.displayText() << std::endl;
		}
	}
예제 #14
0
	static array<unsigned char>^ GetString(char const* str)
	{
		size_t len = strnlen_s(str, 512);
		array<unsigned char>^ result = gcnew array<unsigned char>(len);
		for (size_t i = 0u; i < len; ++i)
			result[i] = str[i];
		return result;
	}
예제 #15
0
        bool combinePath(char *buff, int buffSize, const char *const path, const char *const filename) noexcept
        {
            bool appendSlash = false;
            auto len = (path == nullptr ? 0 : strnlen_s(path, 128));
            if (len > 0 && *(path + len - 1) != '\\') appendSlash = true;

            return sprintf_s(buff, buffSize, "%s%s%s", path, (appendSlash ? "\\" : ""), filename) > 0;
        }
예제 #16
0
파일: main.c 프로젝트: intelrsasw/intelRSD
static void main_loop(int fd)
{
	int ret_code;
	char cmd_string[JSONRPC_MAX_STRING_LEN] = {0};
	fd_set fds;
	struct sockaddr_in addr;
	socklen_t addrlen = sizeof(addr);
	jrpc_req_pkg_t req;
	json_t *rsp = NULL;
	int func_id = 0;
	int reg_connection = -1;

	char *rsp_str = malloc(JSONRPC_MAX_STRING_LEN);

	if (rsp_str == NULL)
		goto err;

	for (;;) {
		FD_ZERO(&fds);
		FD_SET(fd, &fds);

		ret_code = select(fd + 1, &fds, NULL, NULL, NULL);
		if (ret_code < 0)
			continue;

		memset(cmd_string, 0, sizeof(cmd_string));
		ret_code = recvfrom(fd, cmd_string, sizeof(cmd_string), 0, (struct sockaddr *)&addr, &addrlen);
		if (ret_code < 0)
			continue;

		rsp = json_object();
		if (rsp == NULL)
			goto err;

		rmm_log(INFO, "receive: %s.\n", cmd_string);
		parse_req(cmd_string, &req, &func_id);
		ret_code = process_req(func_id, &req, rsp);
		jrpc_req_pkg_free(&req);
		if (ret_code < 0) {
			continue;
		}

		memset(rsp_str, 0, JSONRPC_MAX_STRING_LEN);
		ret_code = jrpc_create_result_rsp_string(req.id, JSONRPC_ID_TYPE_NORMAL, rsp, JSON_OBJECT, rsp_str);
		if (ret_code < 0)
			continue;

		rmm_log(INFO, "send: %s.\n", rsp_str);
		sendto(fd, rsp_str, strnlen_s(rsp_str, JSONRPC_MAX_STRING_LEN)+1, 0, (struct sockaddr *)&addr, addrlen);
	}

	free(rsp_str);

err:

	close(fd);
	return;
}
예제 #17
0
/*
 * This function parses the HTTP status code
 * in the first header.  Only a handful of codes are
 * handled by EST.  We are not a full HTTP stack.  Any
 * unrecognized codes will result in an error.
 * Note that HTTP 1.1 is expected.
 */
static int est_io_parse_response_status_code (unsigned char *buf)
{
    if (!strncmp((const char *)buf, EST_HTTP_HDR_200,
                        strnlen_s(EST_HTTP_HDR_200, EST_HTTP_HDR_MAX))) {
        return 200;
    } else if (!strncmp((const char *)buf, EST_HTTP_HDR_202,
                        strnlen_s(EST_HTTP_HDR_202, EST_HTTP_HDR_MAX))) {
        return 202;
    } else if (!strncmp((const char *)buf, EST_HTTP_HDR_204,
                        strnlen_s(EST_HTTP_HDR_204, EST_HTTP_HDR_MAX))) {
        return 204;
    } else if (!strncmp((const char *)buf, EST_HTTP_HDR_400,
                        strnlen_s(EST_HTTP_HDR_400, EST_HTTP_HDR_MAX))) {
        return 400;
    } else if (!strncmp((const char *)buf, EST_HTTP_HDR_401,
                        strnlen_s(EST_HTTP_HDR_401, EST_HTTP_HDR_MAX))) {
        return 401;
    } else if (!strncmp((const char *)buf, EST_HTTP_HDR_404,
                        strnlen_s(EST_HTTP_HDR_404, EST_HTTP_HDR_MAX))) {
        return 404;
    } else if (!strncmp((const char *)buf, EST_HTTP_HDR_423,
                        strnlen_s(EST_HTTP_HDR_423, EST_HTTP_HDR_MAX))) {
        return 423;
    } else {
        EST_LOG_ERR("Unhandled HTTP response %s", buf);
        return -1;
    }
}
예제 #18
0
파일: utils.c 프로젝트: intelrsasw/intelRSD
bool check_str_len(const char *str, int len)
{
	if ((str == NULL) || (strnlen_s(str, RSIZE_MAX_STR) > len)) {
		return FALSE;
	} else
		return TRUE;

	return TRUE;
}
예제 #19
0
int main(void)
{
  char multiple[] = "a string";
  char *p = multiple;

  for(int i = 0 ; i < strnlen_s(multiple, sizeof(multiple)) ; ++i)
    printf("multiple[%d] = %c  *(p+%d) = %c  &multiple[%d] = %p  p+%d = %p\n",
                       i, multiple[i], i, *(p+i), i, &multiple[i], i, p+i);
  return 0;
}
예제 #20
0
static void AddEnvironmentVariable(struct environment* env,const char* varName, const char* valueString)
{
    size_t len;
    size_t envSize = MAX_PATH - (env->p_head-env->env);
    StringCbCopyA(env->p_head, envSize, varName);
    StringCbCatA(env->p_head, envSize, "=");
    StringCbCatA(env->p_head, envSize, valueString);
    StringCbCatA(env->p_head, envSize, "\0");
    len = strnlen_s(env->p_head, envSize);
    env->p_head += (len + 1);
}
예제 #21
0
char *logger_alloc_copy_string(const char *str) {
    logger_assert(NULL != str);

    size_t size = strnlen_s(str, RSIZE_MAX_STR);
    char *buffer = logger_memory_alloc(size + 1);
    if (NULL != buffer) {
        strncpy_s(buffer, RSIZE_MAX_STR, str, size);
        buffer[size] = '\0';
    }

    return buffer;
}
예제 #22
0
static json_t *rf_listeners_post(struct rest_uri_param *param)
{
	json_t *req = NULL;
	json_t *obj = NULL;
	int32 mask = 0;
	listener_dest_t listener;
	int32 listener_idx = 0;
	uint32 ary_size = sizeof(sub_listener_attrs)/sizeof(input_attr_t);

	req = json_parse(param->json_data);
	if (req == NULL) {
		update_response_info(param, HTTP_BAD_REQUEST);
		HTTPD_ERR("json parse error\n");
		return NULL;
	}

	if (libwrap_check_input_attrs(sub_listener_attrs, ary_size, req, NULL) != RESULT_OK) {
		update_response_info(param, HTTP_BAD_REQUEST);
		goto out;
	}

	obj = libwrap_get_attr_json(sub_listener_attrs, ary_size, "Protocol");
	if (obj) {
		int8 *input = NULL;
		input = json_string_value(obj);
		if (input && check_str_len(input, REST_EVENT_PROTOCOL)) {
			if (strncmp("Redfish", input, strnlen_s("Redfish", RSIZE_MAX_STR)) !=0 ) {
				update_response_info(param, HTTP_BAD_REQUEST);
				goto out;
			}
		} else {
			update_response_info(param, HTTP_BAD_REQUEST);
			goto out;
		}
	}

	mask |= RF_EVENT_MASK_ALL;

	if (process_listener(req, &listener, mask) != 0) {
		update_response_info(param, HTTP_BAD_REQUEST);
		HTTPD_ERR("process listener error\n");
		goto out;
	}

	listener_idx = libwrap_get_evt_listener_idx(mask, listener.dest);
	snprintf_s_si(param->rsp, HREF_URL_LEN, "http://%s/redfish/v1/EventService/Subscriptions/%d", param->host, listener_idx);
	update_response_info(param, HTTP_CREATED);

out:
	if (req)
		json_free(req);
	return NULL;
}
예제 #23
0
int parseMacAddr( _TCHAR *macstr, uint8_t *octet_string ) {
	int i;
	_TCHAR *cur = macstr;

	if( strnlen_s( macstr, MACSTR_LENGTH ) != 17 ) return -1;

	for( i = 0; i < ETHER_ADDR_OCTETS; ++i ) {
		octet_string[i] = strtol( cur, &cur, 16 ) & 0xFF;
		++cur;
	}

	return 0;
}
예제 #24
0
파일: utils.c 프로젝트: intelrsasw/intelRSD
bool is_str_num(const char *str)
{
	int i = 0;

	if (NULL == str)
		return FALSE;

	for (i = 0; i < strnlen_s(str, RSIZE_MAX_STR); i++) {
		if (!((str[i] == '+') || (str[i] == '-') || ((str[i] >= '0') && (str[i] <= '9'))))
			return FALSE;
	}
	return TRUE;
}
예제 #25
0
int32 evt_listener_pack_json(json_t *result, evt_listener_t *listener)
{
	int8 evt_type[128] = {};
	int32 i = 0;
	json_t *evt_type_item = NULL;

	if (strnlen_s(listener->url, sizeof(listener->url)-1) == 0) {
		HTTPD_ERR("invalid subscribe destination\n");
		return -1;
	}

	json_object_add(result, RMM_JSON_ODATA_CONTEXT, json_string(listener->odata_context));
	json_object_add(result, RMM_JSON_ODATA_ID, json_string(listener->odata_id));
	json_object_add(result, RMM_JSON_ODATA_TYPE, json_string(listener->odata_type));
	json_object_add(result, RMM_JSON_RF_ID, json_string(listener->id));
	json_object_add(result, RMM_JSON_RF_NAME, json_string(listener->name));
	json_object_add(result, RMM_JSON_RF_DESC, json_string(listener->description));
	json_object_add(result, RMM_JSON_RF_DEST_URL, json_string(listener->url));

	evt_type_item = json_array();
	if (evt_type_item == NULL) {
		HTTPD_ERR("json array request fail\n");
		return -1;
	}

	for (i = 0; i < listener->evt_index; i++) {
		memset(evt_type, 0, sizeof(evt_type));
		get_event_type_by_node_type(listener->event_types[i], evt_type, sizeof(evt_type));
		if (strnlen_s(evt_type, sizeof(evt_type)-1) != 0)
			json_array_add(evt_type_item, json_string(evt_type));
	}
	json_object_add(result, RMM_JSON_RF_EVT_TYPES, evt_type_item);

	json_object_add(result, RMM_JSON_RF_CONTEXT, json_string(listener->context));
	json_object_add(result, RMM_JSON_RF_PROTOCOL, json_string(listener->protocol));

	return 0;
}
예제 #26
0
void CFormatUtil::Initialization(char *pType)
{
	if (NULL != m_pcFormat)
	{
		delete m_pcFormat;
		m_pcFormat = NULL;
	}

	m_iLength    = 0;
	m_iItemCount = 0;
	m_pcFormat   = NULL;

	size_t iSize = sizeof(FORAMTITEM);
	for (int i = 0; i < MAX_FORMAT_ITEM; i++)
		memset(&m_sFormat[i], 0, iSize);

	char *pDefault = "aAbBcdHIjmMpSUwWxXyYzZNPTG"; 
	size_t iLength = strnlen_s(pDefault, MAX_FORMAT_ITEM - 1);
	memset(m_cType, 0, MAX_FORMAT_ITEM);
	memcpy(m_cType, pDefault, iLength);

	size_t iLen2 = strnlen_s(pType, MAX_FORMAT_ITEM - 1);
	if (0 == iLen2)
		return;

	for (size_t i = 0; i < iLength; i++)
	{
		size_t j = 0;
		char &cData = m_cType[i];
		for (j; j < iLen2; j++)
		{
			if (pType[j] == cData)
				break;
		}
		if (j == iLen2)
			cData = '\0';
	}
}
예제 #27
0
BOOL CFormatUtil::SetFormat(char *pcFormat)
{
	if (NULL == pcFormat)
		return FALSE;

	m_iLength = strnlen_s(pcFormat, MAX_PATH);
	m_pcFormat = new char[m_iLength + 1];
	memcpy(m_pcFormat, pcFormat, m_iLength);
	m_pcFormat[m_iLength] = '\0';

	FormatPaser();

	return TRUE;
}
예제 #28
0
int main()
{
	boost::asio::io_service io_service;
		
	boost::asio::ip::tcp::endpoint endpoint( boost::asio::ip::tcp::v4(), PORT_NUMBER );
	boost::asio::ip::tcp::acceptor acceptor( io_service, endpoint );
		
	boost::asio::ip::tcp::socket socket(io_service);
	acceptor.accept(socket);
	
	std::cout << "클라이언트 접속" << std::endl;
	
	for (;;)
	{
		std::array<char, 128> buf;
		//buf.assign(0);
		boost::system::error_code error;

		size_t len = socket.read_some(boost::asio::buffer(buf), error);

		if( error )
		{
			if( error == boost::asio::error::eof )
			{
				std::cout << "클라이언트와 연결이 끊어졌습니다" << std::endl;
			}
			else 
			{
				std::cout << "error No: " << error.value() << " error Message: " << error.message() << std::endl;
			}

			break;
		}

		std::cout << "클라이언트에서 받은 메시지: " << &buf[0] << std::endl;
				
		char szMessage[128] = {0,};
		sprintf_s( szMessage, 128-1, "Re:%s", &buf[0] );
		int nMsgLen = strnlen_s( szMessage, 128-1 );

		boost::system::error_code ignored_error;
		socket.write_some(boost::asio::buffer(szMessage, nMsgLen), ignored_error);
		
		std::cout << "클라이언트에 보낸 메시지: " << szMessage << std::endl;
	}
    
	getchar();
	return 0;
}
예제 #29
0
void UnicodeCString2Ansi(CString &str, char* pDst, int nDstLen)
{
	USES_CONVERSION;

#if _UNICODE
	char* pTmp = W2A(str);
#else
	char* pTmp = (char*)(LPCTSTR)str;
#endif

	int nLen = strnlen_s(pTmp, nDstLen-1);

	ZeroMemory(pDst, nDstLen);
	strcpy_s(pDst, nLen+1, pTmp);
}
int main()
{
	Poco::DateTime now;
	char szClientName[256] = { 0, };
	sprintf_s(szClientName, 256 - 1, "(%d-%d)", now.second(), now.millisecond());
		
	std::cout << "clinet(" << szClientName << ") 서버에 연결 시도..." << std::endl;
	Poco::Net::StreamSocket ss;

	try
	{
		ss.connect(Poco::Net::SocketAddress("localhost", PORT));

		for (int i = 0; i < 7; ++i)
		{
			char szMessage[256] = { 0, };
			sprintf_s(szMessage, 256 - 1, "%d, Send Message From %s", i, szClientName);
			auto nMsgLen = (int)strnlen_s(szMessage, 256 - 1);

			ss.sendBytes(szMessage, nMsgLen);

			std::cout << "서버에 보낸 메시지: " << szMessage << std::endl;


			char buffer[256] = { 0, };
			auto len = ss.receiveBytes(buffer, sizeof(buffer));

			if (len <= 0)
			{
				std::cout << "서버와 연결이 끊어졌습니다" << std::endl;
				break;
			}

			std::cout << "서버로부터 받은 메시지: " << buffer << std::endl;

			Poco::Thread::sleep(256);
		}

		ss.close();
	}
	catch (Poco::Exception& exc)
	{
		std::cout << "서버 접속 실패: " << exc.displayText() << std::endl;
	}
		
	getchar();
	return 0;
}