//unixpositive.c
#include <stdarg.h>
#include <stdio.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#include <sys/un.h>
void error(int status, int err,char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
if(err)
fprintf(stderr,":%s(%d)/n",strerror(err),err);
if(status)
exit(status);
}
int client(char *pathname,struct sockaddr_un* server , char *protocol) {
struct sockaddr_un client;
int s,type;
const int on = 1;
if(strcmp(protocol,"tcp")==0)
type = SOCK_STREAM;
else {
type = SOCK_DGRAM;
}
if((s=socket(AF_LOCAL, type, 0)) <= 0)
error(1, 0, "create socket failed!");
if(type==SOCK_DGRAM){
bzero(&client,sizeof(struct sockaddr_un));
client.sun_family=AF_LOCAL;
strcpy(client.sun_path,tmpnam(NULL));
bind(s,(struct sockaddr *)&client,sizeof(client));
}
bzero(server,sizeof(struct sockaddr_un));
server->sun_family=AF_LOCAL;
strcpy(server->sun_path,pathname);
if((type==SOCK_STREAM)&&connect(s,(struct sockaddr *)server,sizeof(*server)))
error(1, errno, "connect error!");
return s;
}
//unixtcpclient.c
#include <stdarg.h>
#include <stdio.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#include <sys/select.h>
#include <math.h>
#include <sys/un.h>
void process_client(int s) {
char buff[128];
int rc,maxfd;
fd_set rset;
FD_ZERO(&rset);
while(1) {
FD_SET(s,&rset);
FD_SET(0,&rset);
maxfd=s+1;
if(select(maxfd,&rset,NULL,NULL,NULL)==-1)
error(1,0,"select error!");
if(FD_ISSET(s,&rset)) {
rc = recv(s,buff,sizeof(buff),0);
if(rc <= 0)
break;
buff[rc]='/0';
write(1,buff,rc);
}
if(FD_ISSET(0,&rset)) {
if(fgets(buff,sizeof(buff),stdin)==NULL)
shutdown(s,SHUT_WR);
send(s,buff,strlen(buff),0);
}
}
/*
while(fgets(buff,sizeof(buff),stdin)!=NULL) {
send(s,buff,strlen(buff),0);
rc = recv(s,buff,sizeof(buff),0);
if(rc <= 0)
break;
buff[rc]='/0';
write(1,buff,rc);
bzero(buff,sizeof(buff));
}
*/
}
int main(int argc, char **argv) {
struct sockaddr_un server,temp;
char *pathname;
int s, c, len;
if(argc < 2)
error(1,0,"parameters less than 2");
else if(argc == 2) {
pathname = argv[1];
}
s = client(pathname, &server, "tcp");
process_client(s);
close(s);
exit(0);
}
//unixudpclient.c
#include <stdarg.h>
#include <stdio.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#include <sys/un.h>
void process_client(int s, struct sockaddr_un *server) {
char buff[128];
int rc;
struct sockaddr_un reply;
int len;
while(fgets(buff,sizeof(buff),stdin)!=NULL){
sendto(s, buff, strlen(buff),0, (struct sockaddr *)server, sizeof(*server));
rc=recvfrom(s,buff,sizeof(buff), 0, (struct sockaddr *)&reply,&len);
buff[rc]='/0';
write(1,buff,rc);
}
}
int main(int argc, char **argv) {
struct sockaddr_un server;
char *pathname;
int s, c, len;
if(argc < 2)
error(1,0,"parameters less than 2");
else if(argc == 2) {
pathname = argv[1];
}
s = client(pathname, &server , "udp");
process_client( s, &server);
close(s);
exit(0);
}