recvfrom in socket programming with C -
recvfrom in socket programming with C -
so trying understand socket programming in c when came across code:
/* sample udp client */ #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> #include <string.h> int main(int argc, char**argv) { int sockfd,n; struct sockaddr_in servaddr; char sendline[] = "hello udp server! udp client"; char recvline[1000]; if (argc != 2) { printf("usage: ./%s <ip address>\n",argv[0]); homecoming -1; } sockfd=socket(af_inet,sock_dgram,0); bzero(&servaddr,sizeof(servaddr)); servaddr.sin_family = af_inet; servaddr.sin_addr.s_addr=inet_addr(argv[1]); servaddr.sin_port=htons(32000); sendto(sockfd,sendline,strlen(sendline),0,(struct sockaddr *)&servaddr,sizeof(servaddr)); n=recvfrom(sockfd,recvline,10000,0,null,null); recvline[n]=0; printf("received: %s\n",recvline); homecoming 0; }
it seems recvfrom()
phone call not need ip address send message. @ man pages revealed next lines:
if src_addr not null, , underlying protocol provides source address, source address filled in. when src_addr null, nil filled in; in case, addrlen not used, , should null.
so think underlying protocol provides source ip address. problem is, how figure out address receive message ? that, 1 time send message address, cannot utilize same socket send messages other addresses ? keeps on using same address ?
please help. couldn't find reply anywhere in google or lecture note.
thank in advance.
you have misconception recvfrom
pulls info particular source address.
recvfrom
used connectionless protocols udp. when udp packet received, source address. src_addr
returns address application usage.
if expecting messages particular address, there 2 ways. (1) either can ignore packets received other addresses comparing address returned in src_addr
, or (2) utilize connect
specify particular remote address expecting messages , lower socket layer takes care of ignoring packets other sources. after connect, utilize recv
instead of recvfrom
.
sending messages done through sendto
. seem confusing 2 calls. using sendto
possible send messages difference addresses on same socket.
c sockets udp recvfrom
Comments
Post a Comment