关于recvfrom中是否需要指定接收地址,如果有兴趣定位发送者,可以使用recvfrom来得到数据发送者的源地址。
// numBytes = recvfrom(sfd, resp,BUF_SIZE, 0, NULL, NULL);numBytes = recvfrom(sfd, resp,BUF_SIZE, 0, (struct sockaddr*)&svaddr,&len);
#include <stdio.h> #include "ud_ucase.h" int main(int argc, char *argv[]) { struct sockaddr_un svaddr, claddr; int sfd, j; ssize_t msgLen; ssize_t numBytes; char resp[BUF_SIZE]; socklen_t len; if(argc < 2 || strcmp(argv[1], "--help") == 0) usageErr("%s msg...\n", argv[0]); sfd = socket(AF_UNIX, SOCK_DGRAM, 0);//进程间数据报socket if(sfd == -1) errExit("socket"); memset(&claddr, 0, sizeof(struct sockaddr_un)); claddr.sun_family = AF_UNIX; snprintf(claddr.sun_path, sizeof(claddr.sun_path), "/tmp/ud_ucase_cl.%ld", (long)getpid());//本地socket和文件路径相关联,网络socket是和网络地址绑定 if(bind(sfd, (struct sockaddr *)&claddr, sizeof(struct sockaddr_un)) == -1) errExit("bind"); memset(&svaddr, 0, sizeof(struct sockaddr_un)); svaddr.sun_family = AF_UNIX; strncpy(svaddr.sun_path, SV_SOCK_PATH, sizeof(svaddr.sun_path)-1); for(j=1; j< argc; j++) { len = sizeof(struct sockaddr_un); msgLen = strlen(argv[j]); if(sendto(sfd, argv[j], msgLen, 0, (struct sockaddr *)&svaddr, sizeof(struct sockaddr_un)) != msgLen) fatal("sendto"); // numBytes = recvfrom(sfd, resp,BUF_SIZE, 0, NULL, NULL); numBytes = recvfrom(sfd, resp,BUF_SIZE, 0, (struct sockaddr*)&svaddr,&len); if(numBytes == -1) errExit("recvfrom"); printf("Response %d: %.*s\n",j, (int)numBytes, resp); } remove(claddr.sun_path); exit(EXIT_SUCCESS); }
《Linux编程手册》数据报客户端例子
最新推荐文章于 2024-02-29 14:55:23 发布