C 소켓통신 http post 받기

kjh05072000의 이미지

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <errno.h>
#include "string.h"
#include "time.h"
#include "sys/types.h"
#include "sys/socket.h"
#include "netinet/in.h"
//소켓 프로그래밍에 사용될 헤더파일 선언
#define BUF_LEN 128
//메시지 송수신에 사용될 버퍼 크기를 선언
 
 
int main(int argc, char *argv[])
{
	char buffer[BUF_LEN];
	struct sockaddr_in server_addr, client_addr;
	char temp[20];
	int server_fd, client_fd;
    //server_fd, client_fd : 각 소켓 번호
    	int len, msg_size;
 
 
    	if(argc != 2)
    	{
        	printf("usage : %s [port]\n", argv[0]);
        	exit(0);
    	}
 
    	if((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
    {// 소켓 생성
       	printf("Server : Can't open stream socket\n");
       	exit(0);
    	}
    	memset(&server_addr, 0x00, sizeof(server_addr));
 
   //server_Addr 을 NULL로 초기화
 
    	server_addr.sin_family = AF_INET;
    	server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    	server_addr.sin_port = htons(atoi(argv[1]));
    //server_addr 셋팅
 
    	if(bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) <0)
    	{//bind() 호출
       	printf("Server : Can't bind local address.\n");
       	exit(0);
    	}
 
    	if(listen(server_fd, 5) < 0)
    {//소켓을 수동 대기모드로 설정
       	printf("Server : Can't listening connect.\n");
       	exit(0);
    	}
 
    	memset(buffer, 0x00, sizeof(buffer));
    	printf("Server : wating connection request.\n");
    	len = sizeof(client_addr);
    	while(1)
    	{
        	client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &len);
        if(client_fd < 0)
        {
            printf("Server: accept failed.\n");
            exit(0);
        }
        inet_ntop(AF_INET, &client_addr.sin_addr.s_addr, temp, sizeof(temp));
        printf("Server : %s client connected.\n", temp);
        msg_size = read(client_fd, buffer, 1024);
	printf("%s", buffer);
 
        close(client_fd);
	printf("Server : %s client closed.\n", temp);
	}
 
	close(server_fd);
 
	return 0;
 
}


안드로이드 앱쪽에서
web post를 이용해서
위 서버쪽으로 보내는데
받을때 어떤식으로 받아야할지 몰라서
그냥 msg_size = read(client_fd, buffer, 1024); 으로 받아서
printf로 출력을 하니까

POST / HTTP/1.1
content-length: 5
User-Agent: Dalvik/1.2.0 (Linux; U; Android 2.2; google_sdk Build/FRF91)
Host: 192.168.118.130:12345
Connection: Keep-Alive
Content-Type: application/x-www-form-urlencoded

이것만 출력되고
전송시키는 데이터 예를들자면 green 이라는 문자열을 보냈는데..
없네요..
어떤식으로 받아야 green을 받을 수 있을까요 ?

익명 사용자의 이미지

무슨 말씀이신지 잘 모르겠습니다만 POST 데이터의 경우 보통 Content-Length 헤더에 있는 사이즈만큼
한번 더 read 를 해야 합니다. 또한 이를 이용한 서비스 거부 공격이 존재하므로 Timeout 도 걸어둬야 합니다.

kjh05072000의 이미지

글에도 적었지만..
http post를 이용해서
전송되는 데이터를 어떻게 받을지 모른다는 소리입니다;;
보통 보내는 소스는 있는데..
서버쪽에서 받는건 예제가 잘 없고..
있다하더라도.. 이해하기가 힘들더군요.. ㅠ
어떤식으로 해서 받아야되는지
여쭙고 싶은겁니다.. ㅠ

익명 사용자의 이미지

무슨 말씀이신지 더 모르겠습니다만 제가 위에서 얘기한건 서버에서 받는 쪽에 대해 얘기한 겁니다.

raymundo의 이미지

http://www.cs.tut.fi/~jkorpela/forms/cgic.html#post

여기 샘플 프로그램을 한 번 보시면 될 것 같습니다.

좋은 하루 되세요!

익명 사용자의 이미지

위 익명님이 정확히 설명하셨는데, 제대로 이해를 못하시네요.
팁을 드리자면, 잘모르겠으면 먼저 apache+php 기타 등등으로 input이 제대로 오는지 검증을 해보세요.

input이 제대로 오는게 맞다면, rfc2616을 먼저 읽으시고 그대로 만드시면 되고,
그래도 이해가 안가면 wireshark같은 걸로 프로그램 코딩은 잠시 접어두고 apache와 왔다갔다 하는 패킷을 찍어보세요.
이렇게 패킷을 찍어서 봐도 어떻게 받아야 하는지 감이 오지 않는다면, 앞의 과정을 제대로 안했거나 뭔가 잘못하고 있다는 겁니다.

익명 사용자의 이미지

http post 요청을 모두 받아들이기 전에 close(client_fd) 하셨기 때문에 당연히 나머지 부분을 printf()를 통해서 볼 수 없겠지요. 일단 현 시점에서는 read(); printf(); 를 루프로 감싸서 테스트해 보면서 감을 잡아 보시기 바랍니다. read()의 리턴값도 함께 살펴보면서요.

close(client_fd) 할 적절한 최소한의 시점은 요청을 모두 받아들여 처리한 후, 상황에 맞는 응답을 client에 보낸 후입니다.

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.