- 论坛徽章:
- 0
|
本帖最后由 dengjin_cu 于 2010-03-31 20:12 编辑
错误是sendmsg: Operation not permitted
我已经用了root权限了,该怎么解决呢,附上代码
sender.c
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<sys/un.h>
#define CMS_LEN (sizeof(struct cmsghdr)+sizeof(struct ucred))
union{
struct cmsghdr cm;
char col[CMSG_SPACE(sizeof(struct ucred))];
}un_control;
int main(){
struct sockaddr_un sun;
struct msghdr msg;
int sock;
struct cmsghdr* pcmsg;
struct ucred *cred;
sock = socket(AF_LOCAL,SOCK_STREAM,0);
if(sock < 0){
perror("socket"exit(-1);
}
sun.sun_family = AF_LOCAL;
strncpy(sun.sun_path,"/home/eric/unix_test",sizeof(sun.sun_path)-1);
if(connect(sock,(struct sockaddr*)&sun,sizeof(sun)) < 0){
perror("connect"exit(-1);
}
msg.msg_name = NULL;
msg.msg_namelen = 0;
msg.msg_controllen = sizeof(un_control.col);
msg.msg_control = (void *)un_control.col;
pcmsg = CMSG_FIRSTHDR(&msg);
pcmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
pcmsg->cmsg_level = SOL_SOCKET;
pcmsg->cmsg_type = SCM_CREDENTIALS;
if(sendmsg(sock,&msg,0) < 0){
perror("sendmsg"exit(-1);
}
}
receiver.c
#include<stdio.h>
#include<stdlib.h>
#include<sys/un.h>
#include<unistd.h>
#include<sys/socket.h>
#include<sys/types.h>
#define CMS_LEN (sizeof(struct cmsghdr)+sizeof(struct ucred))
int main(){
struct msghdr msg;
struct sockaddr_un sun;
int listenfd,connfd,n = 1;
listenfd = socket(AF_LOCAL,SOCK_STREAM,0);
if(listenfd < 0){
perror("socket"exit(-1);
}
unlink("/home/eric/unix_test"
bzero(&sun,sizeof(sun));
sun.sun_family = AF_LOCAL;
strncpy(sun.sun_path,"/home/eric/unix_test",sizeof(sun.sun_path)-1);
setsockopt(listenfd,SOL_SOCKET,SO_REUSEADDR,&n,sizeof(n));
if(bind(listenfd,(struct sockaddr*)&sun,sizeof(sun)) < 0){
perror("bind"exit(-1);
}
listen(listenfd,5);
for(;{
connfd = accept(listenfd,NULL,NULL);
printf("get a connected\n"
struct cmsghdr* pcmsg;
struct ucred* pcred;
recvmsg(connfd,&msg,0);
pcmsg = CMSG_FIRSTHDR(&msg);
if(pcmsg && pcmsg->cmsg_len == CMS_LEN){
if(pcmsg->cmsg_level == SOL_SOCKET && \
pcmsg->cmsg_type == SCM_CREDENTIALS){
pcred = (struct ucred*)CMSG_DATA(pcmsg);
printf("real uid=%d\n"
"real gid=%d\npid=%d\n",pcred->uid,\
pcred->gid,\
pcred->pid);
}
}
}
return 0;
} |
|