Search code examples
c++udp

bridged network mode unable to route packet


I want to send udp packets from my host to my virtual machine. My code shows no error but no packet is captured by wireshark in my virtual machine. Below is my code

#include<stdio.h>
#include<stdlib.h>
#include<WinSock2.h>
#include<Ws2tcpip.h>
#include<iostream>
#include<tchar.h>
#define IN_PORT 8888
#define OUT_PORT 50

#pragma comment(lib,"ws2_32.lib") //Winsock Library
// to run use command gcc flood.cpp -lwsock32 -lstdc++
int main(){
    SOCKET s;
    struct sockaddr_in src,dst;
    WSADATA wsa;
    long long count = 0;
    const char* srcIP = "192.168.137.1";
    const char* dstIP = "192.168.137.71";
    const char* pkt = "This is a Probe";
    //Initialise winsock
    printf("\nInitialising Winsock...");
    if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
    {
        printf("Failed. Error Code : %d",WSAGetLastError());
        exit(EXIT_FAILURE);
    }
    src.sin_family = AF_INET;
    src.sin_addr.s_addr = inet_addr(srcIP);
    src.sin_port = htons(IN_PORT);
    
    dst.sin_family = AF_INET;
    dst.sin_addr.s_addr = inet_addr(dstIP);
    dst.sin_port = htons(OUT_PORT);

    if ( (s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == SOCKET_ERROR)
    {
        printf("socket() failed with error code : %d" , WSAGetLastError());
        exit(EXIT_FAILURE);
    }

    if( bind(s ,(struct sockaddr *)&src , sizeof(src)) == SOCKET_ERROR)
    {
        printf("Bind failed with error code : %d" , WSAGetLastError());
        exit(EXIT_FAILURE);
    }

    if (sendto(s, pkt, strlen(pkt), 0, (struct sockaddr*) &dst, sizeof(dst)) == SOCKET_ERROR)
    {
        printf("sendto() failed with error code : %d" , WSAGetLastError());
        exit(EXIT_FAILURE);
    }
    closesocket(s);
    WSACleanup();
    return 0;
}

my command: gcc flood.cpp -lwsock32 -lstdc++

Update1: I use virtualbox. My virtual machine is windows server 2019 and the firewall is disabled. I'm using a bridged network setting. My host and client are pingable to each other. The wireshark in my host with the correct NIC can't capture any packet.

Update2: I just saw a ARP packet which inquired my virtual machine IP is sent everytime I excuted the program. Looks like the routing is unsuccessful, thus, make the udp packet unable to locate the destination. What might be the case?


Solution

  • I found out the problem is the if statement. The function in if isn't called. I deleted all the ifs and it worked.