Skip to content

Instantly share code, notes, and snippets.

@deemru deemru/icmp.c
Created Feb 27, 2018

Embed
What would you like to do?
minimal icmp for ios
#include <arpa/inet.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#define PACKETSIZE 64
struct icmp_echo {
u_char icmp_type;
u_char icmp_code;
u_short icmp_cksum;
u_short icmp_echo_id;
u_short icmp_echo_seq;
};
struct icmp_pkt
{
struct ip ip;
struct icmp_echo icmp;
char msg[PACKETSIZE-sizeof( struct icmp )];
};
static unsigned short checksum( void * b, int len )
{
unsigned short * buf = b;
unsigned int sum = 0;
unsigned short result;
for( sum = 0; len > 1; len -= 2 ) sum += *buf++;
if( len == 1 )
sum += *(unsigned char *)buf;
sum = (sum >> 16) + (sum & 0xFFFF);
sum += (sum >> 16);
result = ~sum;
return result;
}
static uint16_t g_ip_id;
static uint16_t g_icmp_id;
static uint16_t g_icmp_seq;
static void make_icmp_pkt( struct icmp_pkt * pkt, uint32_t src, uint32_t dst )
{
pkt->ip.ip_v = 4;
pkt->ip.ip_hl = sizeof( struct ip ) >> 2;
pkt->ip.ip_tos = 0;
pkt->ip.ip_len = htons( sizeof( struct icmp_pkt ) );
pkt->ip.ip_id = htons( g_ip_id++ );
pkt->ip.ip_off = htons( IP_DF );
pkt->ip.ip_ttl = 64;
pkt->ip.ip_p = IPPROTO_ICMP;
pkt->ip.ip_sum = 0;
pkt->ip.ip_src.s_addr = src;
pkt->ip.ip_dst.s_addr = dst;
pkt->ip.ip_sum = checksum( &pkt->ip, sizeof( pkt->ip ) );
pkt->icmp.icmp_type = ICMP_ECHO;
pkt->icmp.icmp_code = 0;
pkt->icmp.icmp_cksum = 0;
pkt->icmp.icmp_echo_id = htons( g_icmp_id );
pkt->icmp.icmp_echo_seq = htons( g_icmp_seq );
for( size_t i = 0; i < sizeof( pkt->msg ); i++ )
pkt->msg[i] = i;
pkt->icmp.icmp_cksum = checksum( &pkt->icmp, sizeof( pkt->icmp ) + sizeof( pkt->msg ) );
}
static uint32_t make_ip( const char * sz )
{
struct sockaddr_in sin;
inet_pton( AF_INET, sz, &sin.sin_addr);
return sin.sin_addr.s_addr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.