lkml.org 
[lkml]   [2001]   [Sep]   [18]   [last100]   RSS Feed
Views: [wrap][no wrap]   [headers]  [forward] 
 
Messages in this thread
/
Date
From
SubjectUDP over unix domain socket

the attached files are client and server. they simply have to send a
string each other in UDP packets via unix domain socket. i'm wondered,
because every time when the server receives a string with recvfrom(),
'*fromlen' is 2 and 'from' points to some unknown structure.
i am using slackware linux with kernel 2.2.19

#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <string.h>

#define SOCKPATH "localsocket"

void err_sys( const char * const );



int main()
{
struct sockaddr_un uaddr, caddr;
int usock, res;
char buffer[32] = "";
socklen_t len;

memset( &uaddr, 0, sizeof(uaddr) );
uaddr.sun_family = AF_LOCAL;
strcpy( uaddr.sun_path, SOCKPATH );

if( ( usock = socket( PF_LOCAL, SOCK_DGRAM, 0 ) ) == -1 )
err_sys( "socket()" );
printf( "User Datagram Socket %d\n", usock );

printf( "uaddr sockaddr_un has %d bytes\n", (len=SUN_LEN(&uaddr)) );
if( sendto( usock, "Hail", 4, 0, (struct sockaddr*)&uaddr, len ) == -1 )
err_sys( "sendto()" );

printf( "caddr sockaddr_un has %d bytes\n", (len=SUN_LEN(&caddr)) );
if( recvfrom( usock, buffer, sizeof(buffer), 0,
(struct sockaddr*)&caddr, &len ) == -1 )
err_sys( "recvfrom()" );

printf( "Received %d bytes\n", res );
printf( "Buffer now is \"%s\"\n", buffer );
}



void err_sys( const char * const mesg )
{
perror( mesg );
exit( -1 );
}#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <string.h>



#define SOCKPATH "localsocket"



void err_sys( const char * const );



int main()
{
struct sockaddr_un uaddr, caddr;
int usock, res;
socklen_t ulen;
char buffer[ 128 ];

usock = socket( PF_LOCAL, SOCK_DGRAM, 0 );
if( usock == -1 )
err_sys( "socket()" );

memset( &uaddr, 0, sizeof(uaddr) );
uaddr.sun_family = AF_LOCAL;
strcpy( uaddr.sun_path, SOCKPATH );

unlink( SOCKPATH );
res = bind( usock, (struct sockaddr*)&uaddr, SUN_LEN(&uaddr) );
if( res == -1 )
err_sys( "bind()" );
printf( "Socket bind()\n" );

for( ; ; )
{
ulen = SUN_LEN(&uaddr);
ulen = 0;

printf( "uaddr sockaddr_un has %d\n", ulen );
res = recvfrom( usock, buffer, sizeof(buffer), 0,
(struct sockaddr*)&caddr, &ulen );
if( res == -1 )
err_sys( "recvfrom()" );

buffer[res] = '\0';
printf( "Received %d bytes\n", res );
printf( "Remote structure has %d bytes\n", ulen );
/* (unsigned)(htons(*((short*)caddr.sun_path))) ); */

res = sendto( usock, "Hello\r\n", 7, 0,
(struct sockaddr*)&caddr, ulen );
if( res == -1 )
err_sys( "sendto()" );
}
}



void err_sys( const char * const mesg )
{
perror( mesg );
exit( -1 );
}
\
 
 \ /
  Last update: 2005-03-22 13:03    [W:0.031 / U:0.268 seconds]
©2003-2018 Jasper Spaans|hosted at Digital Ocean and TransIP|Read the blog|Advertise on this site