Socket datagram
hubert at spica.ucsb.edu
hubert at spica.ucsb.edu
Tue May 14 09:45:51 AEST 1991
Hi! I am testing the socket's datagram facility and I can't figure
out why the following program doesn't work. The a.out give me
error message like "bad address". Could someone explain it ?
By the way, I just want to use these system call instead of
the listen ,accept and connect for the socket_stream.
Thanks.
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
main()
{
int s1,s2,ret;
char mesg0[20],mesg1[20],mesg2[20],mesg3[20],mesg4[20];
struct sockaddr sock1,sock2;
sock1.sa_family=PF_UNIX;
sock2.sa_family=PF_UNIX;
sprintf(sock1.sa_data,"sock1");
sprintf(sock2.sa_data,"sock2");
unlink(sock1.sa_data);
unlink(sock2.sa_data);
if ((s2=socket(PF_UNIX, SOCK_DGRAM,0)) == -1)
perror("child socket creating error \n");
if (bind(s2, &sock2,sizeof(sock2))==-1)
perror("child binding eror\n");
if ((s1=socket(PF_UNIX, SOCK_DGRAM,0)) == -1)
perror("parent socket creating error \n");
if (bind(s1, &sock1,sizeof(sock1))==-1)
perror("parent binding eror\n");
sprintf(mesg0,"first");
if (sendto(s1, mesg0, sizeof(mesg0),0, &sock2,sizeof(sock2))==-1)
perror("parent send error\n");
if (fork()==0)
{
printf("child birth\n");
if (recvfrom(s2, mesg2, sizeof(mesg2),0,&sock1,sizeof(sock1))==-1)
perror("child receive error\n");
printf("child receives mesg %s\n",mesg2);
sprintf(mesg3,"child's messag");
if (sendto(s2, mesg3, sizeof(mesg3),0, &sock1,sizeof(sock1))==-1)
perror("send error\n");
exit(0);
}
printf("mother\n");
if (recvfrom(s1, mesg4, sizeof(mesg4),0,&sock2, sizeof(sock2))==-1)
perror("receive error\n");
printf("%s\n",mesg2);
wait(&ret);
unlink(sock1.sa_data);
unlink(sock2.sa_data);
if (close(s1)==-1)
perror("close error\n");
if (close(s2)==-1)
perror("close error\n");
}
--
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Hung-Hsien Chang ( Hubert) E-mail: hubert at cs.ucsb.edu
P.S: Hubert is not my middle name; it is easier for American friends to call me.
More information about the Comp.unix.wizards
mailing list