سؤال

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?

هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top