Search code examples
c++winapiudpip-addresspacket

Getting the destination IP of incoming UDP packet in C++


I found the function: GetTcpTable in C++. In the header: iphlpapi.h. That gives me the destination IP of TCP packet and I was wondering if there's a function from the same header that would give me the destination IP of UDP packet... I tried the function: GetUdpTable but it gives only the local IP and port. I will be more than happy if that function has also code example in C++ of course. Thank you anyway!

EDIT: I using pcap.h now and i still don't know how to catch UDP packets and take from them the ip. There is a code that i can use?


Solution

  • GetTcpTable() does not give you the destination IP of TCP packets. It merely gives you a list of currently listening TCP ports and active TCP connections.

    GetUdpTable() can give you the list of currently listening UDP ports, where UDP packets can be sent to. There are no connections in UDP.

    But, if you want to know the actual destination IP for each UDP packet received, and without having to use a low-level capture library like WinPCap, then you can use the WSARecvMsg() function to receive your UDP packets, rather than using the recvfrom() or even recv() function.

    WSARecvMsg() can report metadata about each packet, most notably the IP_PKTINFO (IPv4) and IPV6_PKTINFO (IPv6) control blocks, which specify the destination IP of the packet and the index of the network interface that received the packet.

    You need to use WSAIoctl(SIO_GET_EXTENSION_FUNCTION_POINTER) to obtain a pointer to the WSARecvMsg() function (see Why is the WSARecvMsg function implemented as a function pointer and can this pointer be reused? for the reason why), and use setsockopt() to enable the IP_PKTINFO/IPV6_PKTINFO socket option, before you start calling WSARecvMsg() to receive packets.

    See Function to retrieve the header destination address from a packet in windows XP for an example.