Skip to content

Instantly share code, notes, and snippets.

@GunjiD
Created August 15, 2020 11:09
Show Gist options
  • Save GunjiD/a3aa72e553288efdfb7960e1dc34279b to your computer and use it in GitHub Desktop.
Save GunjiD/a3aa72e553288efdfb7960e1dc34279b to your computer and use it in GitHub Desktop.
ntoh and hton implementation
#include <string.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netpacket/packet.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <net/if.h>
#include <netinet/in_systm.h>
#include <malloc.h>
uint16_t packet_ntohs(uint16_t network_short);
uint32_t packet_ntohl(uint32_t network_long);
uint16_t packet_htons(uint16_t host_short);
uint32_t packet_htonl(uint32_t host_long);
int main(int argc, char *argv[]){
uint16_t a = 0x1234;
uint32_t b = 0x12345678;
printf("a = %x\n", a);
printf("a to host byte order = %x\n", packet_ntohs(a));
printf("b = %x\n", b);
printf("b to host byte order = %x\n", packet_ntohl(b));
uint16_t c = packet_ntohs(a);
uint32_t d = packet_ntohl(b);
printf("c = %x\n", c);
printf("c to network byte order = %x\n", packet_htons(c));
printf("d = %x\n", d);
printf("d to network byte order = %x\n", packet_htonl(d));
return 0;
}
uint16_t packet_ntohs(uint16_t network_short){
uint16_t tmp = 0;
tmp = (network_short >> 0) & 0xff;
tmp = tmp << 8;
tmp |= (network_short >> 8) & 0xff;
return tmp;
}
uint32_t packet_ntohl(uint32_t network_long){
uint32_t tmp = 0;
for(int i = 0; i < 4; i++){
tmp |= (network_long >> i * 8) &0xff;
if(i == 3) break;
tmp = tmp << 8;
}
return tmp;
}
uint16_t packet_htons(uint16_t host_short){
uint16_t tmp = 0;
tmp = (host_short << 0) & 0xff00;
tmp = tmp >> 8;
tmp |= (host_short << 8) & 0xff00;
return tmp;
}
uint32_t packet_htonl(uint32_t host_long){
uint32_t tmp = 0;
for(int i = 0; i < 4; i++){
tmp |= (host_long << i * 8) &0xff000000;
if(i == 3) break;
tmp = tmp >> 8;
}
return tmp;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment