weird about send udp packet to local lan

I'm using visual studio 2003 to write a simple program of communcation with local LAN via UDP socket. And I'm trying to not use MFC. The following is a small piece of code I used to test UDP socket:

static void sendMsg(char *buf, int len)
{
SOCKET sock;
struct sockaddr_in addr;

sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0)
    return;

addr.sin_family = AF_INET;
    addr.sin_port = htons(PORT);
addr.sin_addr.s_addr = inet_addr("192.168.2.108"); // Specify dest IP

sendto(sock, buf, len, 0, (struct sockaddr*)&addr, sizeof(addr));

closesocket(sock);
}

To verify if the packet is send out, I use wireshark to capture packet.

My PC's IP is 192.168.1.107. The strange is that if dest IP is a local IP like 192.168.1.108, I cannot capture the packet in wireshark. But if the dest IP is 192.168.1.1 (gateway) or 192.168.1.255(broadcast) or outside of LAN ip like 192.168.2.108, I can capture the UDP packet.

Who can explain this for me? Is there any wrong with my code?

Answers


If you're sending an UDP packet to an IP address that is not known by your machine, it will ask for the machine's MAC address first via the ARP protocol.

If it gets a response, it will send your packet to the MAC address it receives, if it cannot get a response about the MAC address, the UDP packet won't be sent at all.

192.168.1.1 is an existing machine (the default router) and everything outside your LAN will go through that existing default router, so you will see your UDP packets transmitted. If you try to send to a non existing IP on your LAN, you won't see any packet sent since ARP will fail before your packet is even transmitted.


Need Your Help

Windows unicode commandline argv

c++ visual-studio winapi qt unicode

So getting into the new millenia I rewrote my c++ code with:

What's the difference between Delphi and Rad Studio?

delphi rad-studio

I can't find a feature comparison list. I believe they can both can create native unmanaged code, right? Does Delphi by itself feature RAD?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.