PDA

View Full Version : How can get server's ip of udp by socket file description?


XRainbow
04-24-2003, 03:17 AM
:oops: Hi,everyone.When I use UDP server,I want to get address and port of udp through socket file description.When I use getsockname() in Windows2000,I got the right address and port,but in Linux I got port 0. Can someone give me some solutions?Thank you!

mlampkin
04-24-2003, 06:02 AM
Which side of the connection are you trying to get the address (port) from ... and what is the exact steps (binding, connecting, etc.) you are performing prior to trying to find the port number?

Michael

XRainbow
04-24-2003, 06:45 AM
I want to get address(port) through socket fd in another process,it looks like below:

/*process_a.c*/
...
struct sockaddr_in addr;
fd = socket(AF_INET,SOCK_DGRAM,0);

bzero(&addr,sizeof(struct sockaddr_in));

addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_port = htons(port);

bind(fd,(struct sockaddr*)&addr,sizeof(struct sockaddr));
...

/*process_b.c*/
struct sockaddr_in addr;
socklen_t len;
len = sizeof(struct sockaddr_in);
getsockname(fd,(struct sockaddr*)&addr,&len);/*fd is provided by process_a*/
...

But I got 0 from addr.sin_port,why?

RobSeace
04-24-2003, 01:03 PM
How are you passing the FD between processes? Is it just
inherited via fork(), or are you doing AF_UNIX/sendmsg() type
FD-passing?

Either way, I'm not sure why it wouldn't work... You say the
port is 0, but how about the IP? Is that correct? (Actually, I
see you're binding to INADDR_ANY, so that's probably just
showing up as 0 too, so you don't know if that's correct, or
just another case of not properly filling in the value...) Are you
checking for an error return from getsockname()? Maybe it's
failing for some reason... (If so, see what "errno" is...)

mlampkin
04-24-2003, 11:12 PM
A quirk of the Linux system (and others for that matter) is that when you create a udp socket and send data out of it, it is not associated with an interface / port etc. until the first packet is sent... after a packet is sent, it is associated with the appropriate interface and so forth...

So a guess is (and its only a guess since I don't have a linux system handy right now to check)... is that it might be the "delayed" binding that is causing the return of a 0 for the port (I know, that doesn't make 100% sense but its all that comes to mind)... and the question would be, after you accept the first incoming packet... if you checked the sock name again, does it continue to return a port of 0 or does it set things to their proper value?!

Michael