2012-02-20 1 views
3

패킷 스니퍼에 대한 처리기 작성 시도. 전송 및 inet_ntoa()과 관련하여 문제가 있습니다.원시 패킷 데이터 및 inet_ntoa()로 캐스팅

uint32_t *iphdr_srcaddr = malloc(sizeof(uint32_t)); 
if (*packet_ethertype == ETHERTYPE_IP) { /* IPv4 */ 
    // copy packet data to vars 
    memcpy(iphdr_srcaddr, packet+26, 4); 

    // change to host-byte-order 
    *iphdr_srcaddr = ntohl(*iphdr_srcaddr); 

    struct in_addr *test; 
    test = (struct in_addr*) iphdr_srcaddr; 

    printf("uint32_t: %u\n", *iphdr_srcaddr); // Gives the correct long integer for the address 
    printf("struct in_addr: %u\n", test->s_addr); // Gives the correct long integer through the cast 

    char *test2; 
    test2 = inet_ntoa(*test); 
} 

을 이제 내가 SEGV를 얻을 printf("%s\n", test)하려고하면 다음과 같이 코드입니다. 나는 포인터와 값을 섞어서 어리석은 캐스팅을하고 있다고 확신한다. 나는이 올바른 방향으로 날을 가리키고 있는지,하지만 난 그것이 무엇을 의미하는지에 확실하지 않다 내가 고칠 수있는 방법뿐만 아니라

Program received signal SIGSEGV, Segmentation fault. 
0x00007ffff787ec61 in __strlen_sse2() from /lib/libc.so.6 

컴파일 경고 :

오류가 아래의 실행 중에 수신
mypcap.c: In function ‘handle_sniffed’: 
mypcap.c:61:15: warning: assignment makes pointer from integer without a cast [enabled by default] 

이 경고는 아마 (오른쪽 헤더를 포함하지 않았기 때문에) 당신이 inet_ntoa()에 대한 범위 올바른 프로토 타입이없는 것을 나타냅니다 라인 test2 = inet_ntoa(*test);

+0

샘플 호출 test''인쇄 할 수; 대신에'test2'를 출력하겠습니까? – reuben

+1

왜 로컬 변수를 사용하는 대신에'uint32_t'를 얻기 위해서'malloc'을 사용하고 있습니까? –

답변

7

을 의미합니다. 즉, 컴파일러는 반환 유형이 int이라고 가정합니다.

test2을 전달해야 할 때 testprintf()으로 전달 중입니다.

또한

:

  • 하나의 uint32_t을 할당 malloc()를 사용할 필요가 없습니다;
  • inet_ntoa()은 네트워크 바이트 순서로 입력되기 때문에 ntohl()에 전화 할 필요가 없습니다. 및
  • inet_ntoa()은 오래되어 - inet_ntop()은 새 코드에서 사용해야합니다.

시도 :

#include <arpa/inet.h> 

if (*packet_ethertype == ETHERTYPE_IP) { /* IPv4 */ 
    struct in_addr sin_addr; 
    char straddr[INET_ADDRSTRLEN]; 

    memcpy(&sin_addr.s_addr, packet+26, 4); 

    if (inet_ntop(AF_INET, &sin_addr, straddr, sizeof straddr)) 
     printf("%s\n", straddr); 
    else 
     perror("inet_ntop"); 
} 
+0

이것은 정확한 방향으로 나를 지적하고 대단히 도움이되었습니다. 감사. – axon