print IP number from received UDP packet

O

Orendavd

hi there,
I have a working UDP server in c++, how to I print the IP of the
received packet???
 
I

Ian Collins

hi there,
I have a working UDP server in c++, how to I print the IP of the
received packet???
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.
 
V

vietor liu

hi there,
I have a working UDP server in c++, how to I print the IP of the
received packet???
test use socket api ,function recv() parameter

Vietor Liu
 
J

James Kanze

(e-mail address removed) wrote:
If you know how to access it and its type, the same as any other
variable of that type.

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 ;
}
If you don't know either of these, you are off topic and
should ask in a platform specific group to find out how.

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.
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,767
Messages
2,569,571
Members
45,045
Latest member
DRCM

Latest Threads

Top