일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
Tags
- Nodejs
- openssl
- SWIFT
- 앱스토어
- OSX
- 앱리소스
- MSYS2
- git
- 안드로이드
- Android
- 애플
- OTP
- css
- MFA
- apple
- FIDO2
- otpkey
- Xcode
- fido
- WebAuthn
- kmip
- 2FA
- 앨범북
- MYSQL
- SSH
- appres
- 인증
- SwiftUI
- SSL
- albumbook
Archives
- Today
- Total
인디노트
iphdr 를 이용해서 tcphdr 를 찾는 C 코드 본문
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
void process_packet(unsigned char *buffer, int size);
int main()
{
int sock_raw;
int tcp_count = 0;
struct sockaddr_in source, dest;
unsigned char *buffer = (unsigned char*)malloc(65536);
sock_raw = socket(AF_INET, SOCK_RAW, IPPROTO_TCP);
if (sock_raw < 0)
{
printf("Error creating socket. Exiting...\n");
return 1;
}
while (1)
{
struct sockaddr saddr;
int saddr_len = sizeof(saddr);
int data_size = recvfrom(sock_raw, buffer, 65536, 0, &saddr, &saddr_len);
if (data_size < 0)
{
printf("Error receiving data. Exiting...\n");
return 1;
}
process_packet(buffer, data_size);
}
close(sock_raw);
printf("TCP count: %d\n", tcp_count);
return 0;
}
void process_packet(unsigned char *buffer, int size)
{
struct iphdr *iph = (struct iphdr*)buffer;
if (iph->protocol == IPPROTO_TCP)
{
struct tcphdr *tcph = (struct tcphdr*)(buffer + (iph->ihl * 4));
printf("Source Port: %d\n", ntohs(tcph->source));
printf("Dest Port: %d\n", ntohs(tcph->dest));
printf("Sequence Number: %u\n", ntohl(tcph->seq));
printf("Acknowledge Number: %u\n", ntohl(tcph->ack_seq));
printf("Header Length: %d\n", tcph->doff * 4);
printf("Flags: ");
if (tcph->urg)
printf("U");
if (tcph->ack)
printf("A");
if (tcph->psh)
printf("P");
if (tcph->rst)
printf("R");
if (tcph->syn)
printf("S");
if (tcph->fin)
printf("F");
printf("\n\n");
}
}
위 코드에서 process_packet() 함수는 모든 IP 패킷을 처리하고, 프로토콜이 TCP인 경우에만 tcphdr를 찾아 출력합니다. main() 함수에서는 소켓을 생성하고 패킷을 계속 수신하며, 수신된 TCP 패킷의 개수를 출력합니다. 주의할 점은 이 코드는 raw socket을 사용하므로 root 권한이 필요합니다.
반응형
'개발 플랫폼 및 언어 > 네트워크 기술' 카테고리의 다른 글
eth0 에서 recvfrom 함수로 읽어서 그대로 eth1 으로 write 함수로 전송 하는 C 코드 (0) | 2023.04.13 |
---|---|
ethhdr 의 src 및 dst 를 변경하는 C 코드 (0) | 2023.04.13 |
ICMP ping 구현의 C 코드 (0) | 2023.04.12 |
TCP 전송의 C 코드 (0) | 2023.04.12 |
sendto 로 UDP 데이터 전송 C 코드 (0) | 2023.04.12 |
Comments