How do I get IP address from Ptr<Socket>

2,183 views
Skip to first unread message

Aditya Bhave

unread,
Mar 11, 2010, 4:52:34 PM3/11/10
to ns-3-users
Hi all,

I am using the following piece of code

void ReceivePacket (Ptr<Socket> socket)
{
NS_LOG_UNCOND("Received a Packet!");
}

....
....
NodeContainer c;
........
TypeId tid = TypeId::LookupByName ("ns3::UdpSocketFactory");
Ptr<Socket> recvSink = Socket::CreateSocket (c.Get (1), tid);
InetSocketAddress local = InetSocketAddress (Ipv4Address::GetAny (),
80);
recvSink->Bind (local);
recvSink->SetRecvCallback (MakeCallback (&ReceivePacket));

I want to retrieve the IP address (of the receiver) associated with
the socket in the ReceivePacket() method. How do I do that in NS3?

Thanks for your help
Aditya Bhave

Tom Henderson

unread,
Mar 12, 2010, 1:29:56 AM3/12/10
to ns-3-...@googlegroups.com

Address addr;
recvSink->GetSockName (addr);
InetSocketAddress iaddr = InetSocketAddress::ConvertFrom (addr);

Aditya Bhave

unread,
Mar 12, 2010, 1:39:48 AM3/12/10
to ns-3-users
Thanks Tom, but how do I print the final address in dotted decimal
notation?

Aditya Bhave

unread,
Mar 12, 2010, 1:56:38 AM3/12/10
to ns-3-users
Also I want to print the address of the node that sent the packet. Is
this possible with my current setup, or will I need to code some other
type of packet sink?

--Aditya Bhave

Tom Henderson

unread,
Mar 12, 2010, 2:33:42 AM3/12/10
to ns-3-...@googlegroups.com
On 3/11/10 10:39 PM, Aditya Bhave wrote:
> Thanks Tom, but how do I print the final address in dotted decimal
> notation?

try:
std::cout << iaddr.GetIpv4 () << ":" << iaddr.GetPort () << std::endl;

> Also I want to print the address of the node that sent the packet. Is
> this possible with my current setup, or will I need to code some other
> type of packet sink?

The plan is to put a tag on the packet to convey IP_PKTINFO but this
patch needs to be finished off. See this tracker issue:
http://www.nsnam.org/bugzilla/show_bug.cgi?id=671

- Tom

noel.fa...@gmail.com

unread,
Jul 14, 2016, 7:13:44 AM7/14/16
to ns-3-users
Just in case anyone came across this problem, to get the IP address of the sender use the GetPeerName function of the socket. The following is a very simple code snippet located in a receive callback function.

void
ReceiverReceiveCb (Ptr<Socket> socket)
{
    Address addr;

  socket->GetPeerName (addr);
  InetSocketAddress iaddr = InetSocketAddress::ConvertFrom (addr);

  std::cout << "Received one packet!  Socket: " << iaddr.GetIpv4 () << " port: " << iaddr.GetPort ();
}

NOTE: For this to work the sockets need to be connected. If the sockets are not connected GetPeerName will return ERROR_NOTCONN.

Hope this helps.

- Noel
Reply all
Reply to author
Forward
0 new messages