recvfrom mis-populates sin_port in sockaddr_in struct

Discussion in 'Linux Networking' started by Geoff Hungerford, Jun 25, 2003.

  1. THE PROBLEM: I would like to know the port from which I have just
    received a UDP packet.

    I'm running Redhat Linux 9 (2.4.20). In the sample code that follows,
    the structure udpInAddr is declared as follows:

    struct sockaddr_in udpInAddr;

    and looking for the sender's port in udpInAddr.sin_port after recvfrom
    returns simply does not work. Following the call to recvfrom, I also
    look at all 16 bytes in the structure udpAddrIn (not shown in sample
    code). It turns out that in the spot where I should see the sin_port,
    I see another 2 bytes that can be easily recognized by snooping all
    the packets on the LAN.

    Snoop reveals that the two bytes returned in the sockaddr_in structure
    following the call to recvfrom are the same two bytes just preceeding
    the actual port in the UDP packet. In my case the port is easy to
    recognize: It's 0xEEEE (which also conveniently overcomes
    network-byte-order issues).

    So it appears as if the call to recvfrom incorrectly populates the
    sockaddr_in.sin_port field, selecting the wrong two bytes of data from
    the UDP packet. This is damaging my mind. I've searched everywhere,
    seen this question posed, but never answered. 1000 blessings upon the
    kind soul who can explain this.

    - Geoff


    SAMPLE CODE (without error checking, obvious declarations, etc.):

    udpRecvfd = socket(AF_INET, SOCK_DGRAM, 0);

    bzero(&udpInAddr, sizeof(udpInAddr));
    udpInAddr.sin_family = AF_INET;
    udpInAddr.sin_port = htons(0xeeee);
    udpInAddr.sin_addr.s_addr = INADDR_ANY;

    bind(udpRecvfd, (struct sockaddr *)&udpInAddr, sizeof(udpInAddr));

    bzero(udpPkg.udpRecvBuf, sizeof(udpPkg.udpRecvBuf));
    addr_size = sizeof(udpInAddr);

    bytes_read = recvfrom(udpRecvfd,
    udpPkg.udpRecvBuf,
    1024,
    0,
    (struct sockaddr *)&udpInAddr,
    &addr_size);

    printf("broadcast received from: %s, port=%d\n",
    inet_ntoa(udpInAddr.sin_addr),
    ntohs(udpInAddr.sin_port));


    RESULT:

    IP address printed to stdout is correct, port is incorrect.
     
    Geoff Hungerford, Jun 25, 2003
    #1
    1. Advertisements

  2. I just answered this on the OTHER group you posted to.....

    <snip>
     
    Phil Frisbie, Jr., Jun 26, 2003
    #2
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.