Use of htons() and ntohs()

This is a discussion on Use of htons() and ntohs() within the C Programming forums, part of the General Programming Boards category; How can i use these functions to convert nertwork data to host data? (im sure that was poorly worded but ...

  1. #1
    Registered User
    Join Date
    Dec 2003
    Posts
    16

    Question Use of htons() and ntohs()

    How can i use these functions to convert nertwork data to host data? (im sure that was poorly worded but im fairly new to this). I have a captured ICMP packet and have read from the file into a buffer and then populated a structure representing ethernet, ip packet and icmp structures.

    I think i need to use the above ntohs and nothl functions on some of the data to make sense of it. I am just assuming this because if i were to use the program backwards to craft a packet, i would need to use honts and hontl on things like the packet identification and packet length.

    So how could i use this on data already stored in a structure.

    Any pointers or example code would be very much appreciated.

    Cheers

    Andy

  2. #2
    Registered User
    Join Date
    Mar 2005
    Posts
    135

  3. #3
    Sr. Software Engineer filker0's Avatar
    Join Date
    Sep 2005
    Location
    West Virginia
    Posts
    235
    Also, on Linux, do a "man htons" or "man htonl" or even "man byteorder".
    Insert obnoxious but pithy remark here

  4. #4
    Registered User
    Join Date
    Dec 2003
    Posts
    16
    I had a look at the MSDN example of u_short ntohs(...etc), but i dont see how i can use that in my situation. I reckon im being dense.

    printf(" type length is %x\n", ethernet.typelength);

    i need to use ntohs on that structure element, can i use it in the printf statement somehow? Or is there a way of setting a condition on the structure element itself so that when data is entered into it the function is automatically used. Maybe something along the lines of:

    <code>

    struct ip_struct
    {
    unsigned int ver:4;
    unsigned int ihl:4;
    unsigned char tos:8; unsigned int ntohs(length):16;
    unsigned int ntohs(identification):16;
    </code>

    I know that is far from correct but im a man clutching at straws!

  5. #5
    Sr. Software Engineer filker0's Avatar
    Join Date
    Sep 2005
    Location
    West Virginia
    Posts
    235
    Code:
    printf(" type length is %x\n", ntohs(ethernet.typelength));
    should do it just fine.
    Insert obnoxious but pithy remark here

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21