- recvfrom mis-populates sin_port in sockaddr_in struct

PDA

View Full Version : recvfrom mis-populates sin_port in sockaddr_in struct


Geoff Hungerford
07-24-2004, 06:03 PM
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.

Phil Frisbie, Jr.
07-24-2004, 06:04 PM
I just answered this on the OTHER group you posted to.....

Geoff Hungerford wrote:
> THE PROBLEM: I would like to know the port from which I have just
> received a UDP packet.
<snip>

--
Phil Frisbie, Jr.
Hawk Software
http://www.hawksoft.com