print IP number from received UDP packet

Discussion in 'C++' started by Orendavd, Jun 17, 2007.

  1. Orendavd

    Orendavd Guest

    hi there,
    I have a working UDP server in c++, how to I print the IP of the
    received packet???
     
    Orendavd, Jun 17, 2007
    #1
    1. Advertisements

  2. Orendavd

    Ian Collins Guest

    If you know how to access it and its type, the same as any other
    variable of that type. If you don't know either of these, you are off
    topic and should ask in a platform specific group to find out how.
     
    Ian Collins, Jun 17, 2007
    #2
    1. Advertisements

  3. Orendavd

    vietor liu Guest

    test use socket api ,function recv() parameter

    Vietor Liu
     
    vietor liu, Jun 18, 2007
    #3
  4. Orendavd

    James Kanze Guest

    I don't know. IP addresses can be a bit strange. The obvious
    answer is to define a user type IP, and provide a << operator
    for it, but that still sort of begs the question. I've seen IP
    addresses in three different formats: char[4], 32 bit int (or
    unsigned int), in *network* byte order, and 32 bit int or
    unsigned int in native byte order. None of these will give the
    traditional a.b.c.d format when printed as a variable of that
    type. You need some extra code:

    For char[4]:

    std::eek:stream&
    operator<<(
    std::eek:stream& dest,
    Ip const& obj )
    {
    for ( int i = 0 ; i < 4 ; ++ i ) {
    if ( i != 0 ) {
    dest << '.' ;
    }
    dest << (int)(unsigned char)obj.value[ i ] ;
    }
    return dest ;
    }

    For unsigned int, native byte order:

    std::eek:stream&
    operator<<(
    std::eek:stream& dest,
    Ip const& obj )
    {
    int shift = 32 ;
    while ( shift > 0 ) {
    shift -= 8 ;
    dest << ((obj.value >> shift) & 0xFF) ;
    if ( shift != 0 ) {
    dest << '.' ;
    }
    }
    return dest ;
    }

    And network byte order:

    std::eek:stream&
    operator<<(
    std::eek:stream& dest,
    Ip const& obj )
    {
    unsigned char const*p
    = reinterpret_cast< unsigned char const* >( &obj.value ) ;
    for ( int i = 0 ; i < 4 ; ++ i ) {
    if ( i != 0 ) {
    dest << '.' ;
    }
    dest << (int)( p[ i ] ) ;
    }
    return dest ;
    }
    How you get the IP depends on your platform or your library, but
    formatting it, once you've got it, requires some work as well.
     
    James Kanze, Jun 18, 2007
    #4
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.